diff --git a/algorithms/README.md b/algorithms/README.md index f1e12ee243..dc12b528da 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -6,3 +6,5 @@ - [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java) - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) +- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) +- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java new file mode 100644 index 0000000000..86522950ef --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java @@ -0,0 +1,53 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class BinarySearch { + + public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) { + + int index = Integer.MAX_VALUE; + + while (low <= high) { + + int mid = (low + high) / 2; + + if (sortedArray[mid] < key) { + low = mid + 1; + } else if (sortedArray[mid] > key) { + high = mid - 1; + } else if (sortedArray[mid] == key) { + index = mid; + break; + } + } + return index; + } + + public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) { + + int middle = (low + high) / 2; + if (high < low) { + return -1; + } + + if (key == sortedArray[middle]) { + return middle; + } else if (key < sortedArray[middle]) { + return runBinarySearchRecursively(sortedArray, key, low, middle - 1); + } else { + return runBinarySearchRecursively(sortedArray, key, middle + 1, high); + } + } + + public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) { + int index = Arrays.binarySearch(sortedArray, key); + return index; + } + + public int runBinarySearchUsingJavaCollections(List sortedList, Integer key) { + int index = Collections.binarySearch(sortedList, key); + return index; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java index ce2ba03af5..fed4ebed48 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java @@ -18,12 +18,12 @@ public class MiniMax { constructTree(root); } - private void constructTree(Node node) { - List listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones()); - boolean isMaxPlayer = !node.isMaxPlayer(); + private void constructTree(Node parentNode) { + List listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones()); + boolean isChildMaxPlayer = !parentNode.isMaxPlayer(); listofPossibleHeaps.forEach(n -> { - Node newNode = new Node(n, isMaxPlayer); - node.addChild(newNode); + Node newNode = new Node(n, isChildMaxPlayer); + parentNode.addChild(newNode); if (newNode.getNoOfBones() > 0) { constructTree(newNode); } diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java new file mode 100644 index 0000000000..3611ec8e49 --- /dev/null +++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java @@ -0,0 +1,41 @@ +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; + + +public class BinarySearchTest { + + int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + int key = 6; + int expectedIndexForSearchKey = 7; + int low = 0; + int high = sortedArray.length - 1; + List sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); + } + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); + } + + @Test + public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); + } + + @Test + public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + BinarySearch binSearch = new BinarySearch(); + Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); + } + +} diff --git a/apache-shiro/.gitignore b/apache-shiro/.gitignore new file mode 100644 index 0000000000..020cda4898 --- /dev/null +++ b/apache-shiro/.gitignore @@ -0,0 +1,4 @@ + +/.idea/ +/target/ +/apache-shiro.iml \ No newline at end of file diff --git a/apache-shiro/README.md b/apache-shiro/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml new file mode 100644 index 0000000000..711ddb5cee --- /dev/null +++ b/apache-shiro/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + com.baeldung + apache-shiro + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.2.RELEASE + + + + 1.4.0 + 1.2.17 + 1.7.25 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-freemarker + + + org.apache.shiro + shiro-spring-boot-web-starter + ${apache-shiro-core-version} + + + org.apache.shiro + shiro-core + ${apache-shiro-core-version} + + + org.slf4j + jcl-over-slf4j + ${slf4j-version} + runtime + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + runtime + + + log4j + log4j + ${log4j-version} + runtime + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.2 + + 1.8 + 1.8 + + + + + + + \ No newline at end of file diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java new file mode 100644 index 0000000000..5e341f251b --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/Main.java @@ -0,0 +1,85 @@ +package com.baeldung; + +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.*; +import org.apache.shiro.mgt.DefaultSecurityManager; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.realm.Realm; +import org.apache.shiro.realm.text.IniRealm; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Main { + + private static final transient Logger log = LoggerFactory.getLogger(Main.class); + + public static void main(String[] args) { + + Realm realm = new MyCustomRealm(); + SecurityManager securityManager = new DefaultSecurityManager(realm); + + SecurityUtils.setSecurityManager(securityManager); + Subject currentUser = SecurityUtils.getSubject(); + + if (!currentUser.isAuthenticated()) { + UsernamePasswordToken token + = new UsernamePasswordToken("user", "password"); + token.setRememberMe(true); + try { + currentUser.login(token); + } catch (UnknownAccountException uae) { + log.error("Username Not Found!", uae); + } catch (IncorrectCredentialsException ice) { + log.error("Invalid Credentials!", ice); + } catch (LockedAccountException lae) { + log.error("Your Account is Locked!", lae); + } catch (AuthenticationException ae) { + log.error("Unexpected Error!", ae); + } + } + + log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); + + if (currentUser.hasRole("admin")) { + log.info("Welcome Admin"); + } else if(currentUser.hasRole("editor")) { + log.info("Welcome, Editor!"); + } else if(currentUser.hasRole("author")) { + log.info("Welcome, Author"); + } else { + log.info("Welcome, Guest"); + } + + if(currentUser.isPermitted("articles:compose")) { + log.info("You can compose an article"); + } else { + log.info("You are not permitted to compose an article!"); + } + + if(currentUser.isPermitted("articles:save")) { + log.info("You can save articles"); + } else { + log.info("You can not save articles"); + } + + if(currentUser.isPermitted("articles:publish")) { + log.info("You can publish articles"); + } else { + log.info("You can not publish articles"); + } + + Session session = currentUser.getSession(); + session.setAttribute("key", "value"); + String value = (String) session.getAttribute("key"); + if (value.equals("value")) { + log.info("Retrieved the correct value! [" + value + "]"); + } + + currentUser.logout(); + + System.exit(0); + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java new file mode 100644 index 0000000000..8d792c76a5 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java @@ -0,0 +1,102 @@ +package com.baeldung; + +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.jdbc.JdbcRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.*; + +public class MyCustomRealm extends JdbcRealm { + + private Map credentials = new HashMap<>(); + private Map> roles = new HashMap<>(); + private Map> perm = new HashMap<>(); + + { + credentials.put("user", "password"); + credentials.put("user2", "password2"); + credentials.put("user3", "password3"); + + roles.put("user", new HashSet<>(Arrays.asList("admin"))); + roles.put("user2", new HashSet<>(Arrays.asList("editor"))); + roles.put("user3", new HashSet<>(Arrays.asList("author"))); + + perm.put("admin", new HashSet<>(Arrays.asList("*"))); + perm.put("editor", new HashSet<>(Arrays.asList("articles:*"))); + perm.put("author", + new HashSet<>(Arrays.asList("articles:compose", + "articles:save"))); + + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) + throws AuthenticationException { + + UsernamePasswordToken uToken = (UsernamePasswordToken) token; + + if(uToken.getUsername() == null + || uToken.getUsername().isEmpty() + || !credentials.containsKey(uToken.getUsername()) + ) { + throw new UnknownAccountException("username not found!"); + } + + + return new SimpleAuthenticationInfo( + uToken.getUsername(), credentials.get(uToken.getUsername()), + getName()); + } + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + Set roleNames = new HashSet<>(); + Set permissions = new HashSet<>(); + + principals.forEach(p -> { + try { + Set roles = getRoleNamesForUser(null, (String) p); + roleNames.addAll(roles); + permissions.addAll(getPermissions(null, null,roles)); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); + info.setStringPermissions(permissions); + return info; + } + + @Override + protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { + if(!roles.containsKey(username)) { + throw new SQLException("username not found!"); + } + + return roles.get(username); + } + + @Override + protected Set getPermissions(Connection conn, String username, Collection roleNames) throws SQLException { + for (String role : roleNames) { + if (!perm.containsKey(role)) { + throw new SQLException("role not found!"); + } + } + + Set finalSet = new HashSet<>(); + for (String role : roleNames) { + finalSet.addAll(perm.get(role)); + } + + return finalSet; + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/ShiroSpringApplication.java b/apache-shiro/src/main/java/com/baeldung/ShiroSpringApplication.java new file mode 100644 index 0000000000..e12d3ebffa --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/ShiroSpringApplication.java @@ -0,0 +1,45 @@ +package com.baeldung; + +import org.apache.shiro.realm.Realm; +import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; +import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +/** + * Created by smatt on 21/08/2017. + */ +@SpringBootApplication +public class ShiroSpringApplication { + + private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class); + + public static void main(String... args) { + SpringApplication.run(ShiroSpringApplication.class, args); + } + + + @Bean + public Realm realm() { + return new MyCustomRealm(); + } + + + @Bean + public ShiroFilterChainDefinition shiroFilterChainDefinition() { + DefaultShiroFilterChainDefinition filter + = new DefaultShiroFilterChainDefinition(); + + filter.addPathDefinition("/secure", "authc"); + filter.addPathDefinition("/**", "anon"); + + return filter; + } + + + + +} diff --git a/apache-shiro/src/main/java/com/baeldung/controllers/ShiroSpringController.java b/apache-shiro/src/main/java/com/baeldung/controllers/ShiroSpringController.java new file mode 100644 index 0000000000..e6e72b2579 --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/controllers/ShiroSpringController.java @@ -0,0 +1,105 @@ +package com.baeldung.controllers; + +import com.baeldung.models.UserCredentials; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import javax.servlet.http.HttpServletRequest; + +@Controller +public class ShiroSpringController { + + + + @GetMapping("/") + public String index() { + return "index"; + } + + + @RequestMapping( value = "/login", method = {RequestMethod.GET, RequestMethod.POST}) + public String login(HttpServletRequest req, UserCredentials cred, RedirectAttributes attr) { + + if(req.getMethod().equals(RequestMethod.GET.toString())) { + return "login"; + } + else { + + Subject subject = SecurityUtils.getSubject(); + + if(!subject.isAuthenticated()) { + UsernamePasswordToken token = new UsernamePasswordToken( + cred.getUsername(), cred.getPassword(), cred.isRememberMe()); + try { + subject.login(token); + } catch (AuthenticationException ae) { + ae.printStackTrace(); + attr.addFlashAttribute("error", "Invalid Credentials"); + return "redirect:/login"; + } + } + + return "redirect:/secure"; + } + } + + + @GetMapping("/secure") + public String secure(ModelMap modelMap) { + + Subject currentUser = SecurityUtils.getSubject(); + String role = "", permission = ""; + + if(currentUser.hasRole("admin")) { + role = role + "You are an Admin"; + } + else if(currentUser.hasRole("editor")) { + role = role + "You are an Editor"; + } + else if(currentUser.hasRole("author")) { + role = role + "You are an Author"; + } + + if(currentUser.isPermitted("articles:compose")) { + permission = permission + "You can compose an article, "; + } else { + permission = permission + "You are not permitted to compose an article!, "; + } + + if(currentUser.isPermitted("articles:save")) { + permission = permission + "You can save articles, "; + } else { + permission = permission + "\nYou can not save articles, "; + } + + if(currentUser.isPermitted("articles:publish")) { + permission = permission + "\nYou can publish articles"; + } else { + permission = permission + "\nYou can not publish articles"; + } + + modelMap.addAttribute("username", currentUser.getPrincipal()); + modelMap.addAttribute("permission", permission); + modelMap.addAttribute("role", role); + + return "secure"; + } + + + @PostMapping("/logout") + public String logout() { + Subject subject = SecurityUtils.getSubject(); + subject.logout(); + return "redirect:/"; + } + +} diff --git a/apache-shiro/src/main/java/com/baeldung/models/UserCredentials.java b/apache-shiro/src/main/java/com/baeldung/models/UserCredentials.java new file mode 100644 index 0000000000..51b429046a --- /dev/null +++ b/apache-shiro/src/main/java/com/baeldung/models/UserCredentials.java @@ -0,0 +1,40 @@ +package com.baeldung.models; + +public class UserCredentials { + + private String username; + private String password; + private boolean rememberMe = false; + + public UserCredentials() {} + + 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; + } + + public boolean isRememberMe() { + return rememberMe; + } + + public void setRememberMe(boolean rememberMe) { + this.rememberMe = rememberMe; + } + + @Override + public String toString() { + return "username = " + getUsername() + + "\nrememberMe = " + isRememberMe(); + } +} diff --git a/apache-shiro/src/main/resources/application.properties b/apache-shiro/src/main/resources/application.properties new file mode 100644 index 0000000000..5bcb6b3352 --- /dev/null +++ b/apache-shiro/src/main/resources/application.properties @@ -0,0 +1,11 @@ +server.port=9000 +server.servlet-path=/ +server.context-path=/ + +#shiro-spring-boot-config +shiro.loginUrl = /login +shiro.successUrl = /secure +shiro.unauthorizedUrl = /login + +#freemarker +spring.freemarker.suffix=.ftl diff --git a/apache-shiro/src/main/resources/log4j.properties b/apache-shiro/src/main/resources/log4j.properties new file mode 100644 index 0000000000..897bf08221 --- /dev/null +++ b/apache-shiro/src/main/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n + +log4j.logger.org.apache=WARN + +log4j.logger.org.apache.shiro=INFO + +log4j.logger.org.apache.shiro.util.ThreadContext=WARN +log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN \ No newline at end of file diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini new file mode 100644 index 0000000000..0bb7567d1e --- /dev/null +++ b/apache-shiro/src/main/resources/shiro.ini @@ -0,0 +1,9 @@ +[users] +user = password,admin +user2 = password2,editor +user3 = password3,author + +[roles] +admin = * +editor = articles:* +author = articles:compose,articles:save \ No newline at end of file diff --git a/apache-shiro/src/main/resources/templates/index.ftl b/apache-shiro/src/main/resources/templates/index.ftl new file mode 100644 index 0000000000..0210d656fc --- /dev/null +++ b/apache-shiro/src/main/resources/templates/index.ftl @@ -0,0 +1,10 @@ + + + Index + + +

Welcome Guest!

+
+ Login + + \ No newline at end of file diff --git a/apache-shiro/src/main/resources/templates/login.ftl b/apache-shiro/src/main/resources/templates/login.ftl new file mode 100644 index 0000000000..3a0552dc2e --- /dev/null +++ b/apache-shiro/src/main/resources/templates/login.ftl @@ -0,0 +1,27 @@ + + + Login + + +

Login

+
+
+ <#if (error?length > 0)??> +

${error}

+ <#else> + + + +
+ +

+ +
+ +

+ Remember Me +

+ +
+ + \ No newline at end of file diff --git a/apache-shiro/src/main/resources/templates/secure.ftl b/apache-shiro/src/main/resources/templates/secure.ftl new file mode 100644 index 0000000000..4466a0162f --- /dev/null +++ b/apache-shiro/src/main/resources/templates/secure.ftl @@ -0,0 +1,15 @@ + + + Secure + + +

Welcome ${username}!

+

Role: ${role}

+

Permissions

+

${permission}

+
+
+ +
+ + \ No newline at end of file diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties index 00e0b7e410..97b19f4cb7 100644 --- a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties +++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties @@ -1,4 +1,4 @@ resource.loader=webapp webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader -webapp.resource.loader.path = . +webapp.resource.loader.path = webapp.resource.loader.cache = true \ No newline at end of file diff --git a/asciidoctor/README.md b/asciidoctor/README.md index 164200d227..3c602b6abd 100644 --- a/asciidoctor/README.md +++ b/asciidoctor/README.md @@ -1,3 +1,4 @@ ### Relevant articles -- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) \ No newline at end of file +- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor) +- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book) diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 989f6e5354..a602cd11b9 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -35,7 +35,12 @@ src/docs/asciidoc target/docs/asciidoc + + ${project.basedir}/src/themes + custom + pdf + book diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/asciidoctor/src/docs/asciidoc/test.adoc index 5a86a00440..fec1f73584 100644 --- a/asciidoctor/src/docs/asciidoc/test.adoc +++ b/asciidoctor/src/docs/asciidoc/test.adoc @@ -1,3 +1,13 @@ -== Introduction Section +:icons: font -Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#. \ No newline at end of file + += Generating book with AsciiDoctorj +Baeldung + +[abstract] +This is the actual content. + +== First Section + +This is first section of the book where you can include some nice icons like icon:comment[]. +You can also create http://www.baeldung.com[links] diff --git a/asciidoctor/src/themes/custom-theme.yml b/asciidoctor/src/themes/custom-theme.yml new file mode 100644 index 0000000000..a3c8c00510 --- /dev/null +++ b/asciidoctor/src/themes/custom-theme.yml @@ -0,0 +1,29 @@ +title_page: + align: left + +page: + layout: portrait + margin: [0.75in, 1in, 0.75in, 1in] + size: A4 +base: + font_color: #333333 + line_height_length: 17 + line_height: $base_line_height_length / $base_font_size +link: + font_color: #009900 + +header: + height: 0.5in + line_height: 1 + recto_content: + center: '{document-title}' + verso_content: + center: '{document-title}' + +footer: + height: 0.5in + line_height: 1 + recto_content: + right: '{chapter-title} | *{page-number}*' + verso_content: + left: '*{page-number}* | {chapter-title}' \ No newline at end of file diff --git a/aws/pom.xml b/aws/pom.xml index 8d60240c87..c66c420fae 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -18,9 +18,41 @@ 1.3.0 1.1.0 2.8.0 + 1.11.154 + 4.12 + 2.8.9 + 3.8.0 + + + com.amazonaws + aws-java-sdk + ${aws-java-sdk.version} + + + + junit + junit + ${junit.version} + test + + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + com.amazonaws aws-lambda-java-core diff --git a/aws/src/main/java/com/baeldung/s3/AWSS3Service.java b/aws/src/main/java/com/baeldung/s3/AWSS3Service.java new file mode 100644 index 0000000000..792e41a188 --- /dev/null +++ b/aws/src/main/java/com/baeldung/s3/AWSS3Service.java @@ -0,0 +1,87 @@ +package com.baeldung.s3; + +import java.io.File; +import java.util.List; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3Client; +import com.amazonaws.services.s3.model.Bucket; +import com.amazonaws.services.s3.model.CopyObjectResult; +import com.amazonaws.services.s3.model.DeleteObjectsRequest; +import com.amazonaws.services.s3.model.DeleteObjectsResult; +import com.amazonaws.services.s3.model.ObjectListing; +import com.amazonaws.services.s3.model.PutObjectResult; +import com.amazonaws.services.s3.model.S3Object; + +public class AWSS3Service { + private final AmazonS3 s3client; + + public AWSS3Service() { + this(new AmazonS3Client() { + }); + } + + public AWSS3Service(AmazonS3 s3client) { + this.s3client = s3client; + } + + //is bucket exist? + public boolean doesBucketExist(String bucketName) { + return s3client.doesBucketExist(bucketName); + } + + //create a bucket + public Bucket createBucket(String bucketName) { + return s3client.createBucket(bucketName); + } + + //list all buckets + public List listBuckets() { + return s3client.listBuckets(); + } + + //delete a bucket + public void deleteBucket(String bucketName) { + s3client.deleteBucket(bucketName); + } + + //uploading object + public PutObjectResult putObject(String bucketName, String key, File file) { + return s3client.putObject(bucketName, key, file); + } + + //listing objects + public ObjectListing listObjects(String bucketName) { + return s3client.listObjects(bucketName); + } + + //get an object + public S3Object getObject(String bucketName, String objectKey) { + return s3client.getObject(bucketName, objectKey); + } + + //copying an object + public CopyObjectResult copyObject( + String sourceBucketName, + String sourceKey, + String destinationBucketName, + String destinationKey + ) { + return s3client.copyObject( + sourceBucketName, + sourceKey, + destinationBucketName, + destinationKey + ); + } + + //deleting an object + public void deleteObject(String bucketName, String objectKey) { + s3client.deleteObject(bucketName, objectKey); + } + + //deleting multiple Objects + public DeleteObjectsResult deleteObjects(DeleteObjectsRequest delObjReq) { + return s3client.deleteObjects(delObjReq); + } +} diff --git a/aws/src/main/java/com/baeldung/s3/S3Application.java b/aws/src/main/java/com/baeldung/s3/S3Application.java new file mode 100644 index 0000000000..fdfb909f73 --- /dev/null +++ b/aws/src/main/java/com/baeldung/s3/S3Application.java @@ -0,0 +1,101 @@ +package com.baeldung.s3; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.s3.model.Bucket; +import com.amazonaws.services.s3.model.DeleteObjectsRequest; +import com.amazonaws.services.s3.model.ObjectListing; +import com.amazonaws.services.s3.model.S3Object; +import com.amazonaws.services.s3.model.S3ObjectInputStream; +import com.amazonaws.services.s3.model.S3ObjectSummary; + +public class S3Application { + + private static final AWSCredentials credentials; + private static String bucketName; + + static { + //put your accesskey and secretkey here + credentials = new BasicAWSCredentials( + "", + "" + ); + } + + public static void main(String[] args) throws IOException { + //set-up the client + AmazonS3 s3client = AmazonS3ClientBuilder + .standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion(Regions.US_EAST_2) + .build(); + + AWSS3Service awsService = new AWSS3Service(s3client); + + bucketName = "baeldung-bucket"; + + //creating a bucket + if(awsService.doesBucketExist(bucketName)) { + System.out.println("Bucket name is not available." + + " Try again with a different Bucket name."); + return; + } + awsService.createBucket(bucketName); + + //list all the buckets + for(Bucket s : awsService.listBuckets() ) { + System.out.println(s.getName()); + } + + //deleting bucket + awsService.deleteBucket("baeldung-bucket-test2"); + + //uploading object + awsService.putObject( + bucketName, + "Document/hello.txt", + new File("/Users/user/Document/hello.txt") + ); + + //listing objects + ObjectListing objectListing = awsService.listObjects(bucketName); + for(S3ObjectSummary os : objectListing.getObjectSummaries()) { + System.out.println(os.getKey()); + } + + //downloading an object + S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt"); + S3ObjectInputStream inputStream = s3object.getObjectContent(); + FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt")); + + //copying an object + awsService.copyObject( + "baeldung-bucket", + "picture/pic.png", + "baeldung-bucket2", + "Document/picture.png" + ); + + //deleting an object + awsService.deleteObject(bucketName, "Document/hello.txt"); + + //deleting multiple objects + String objkeyArr[] = { + "Document/hello2.txt", + "Document/picture.png" + }; + + DeleteObjectsRequest delObjReq = new DeleteObjectsRequest("baeldung-bucket") + .withKeys(objkeyArr); + awsService.deleteObjects(delObjReq); + } +} diff --git a/aws/src/test/java/com/baeldung/s3/AWSS3ServiceIntegrationTest.java b/aws/src/test/java/com/baeldung/s3/AWSS3ServiceIntegrationTest.java new file mode 100644 index 0000000000..d386704513 --- /dev/null +++ b/aws/src/test/java/com/baeldung/s3/AWSS3ServiceIntegrationTest.java @@ -0,0 +1,113 @@ +package com.baeldung.s3; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.model.CopyObjectResult; +import com.amazonaws.services.s3.model.DeleteObjectsRequest; +import com.amazonaws.services.s3.model.DeleteObjectsResult; +import com.amazonaws.services.s3.model.PutObjectResult; + +public class AWSS3ServiceIntegrationTest { + + private static final String BUCKET_NAME = "bucket_name"; + private static final String KEY_NAME = "key_name"; + private static final String BUCKET_NAME2 = "bucket_name2"; + private static final String KEY_NAME2 = "key_name2"; + + private AmazonS3 s3; + private AWSS3Service service; + + @Before + public void setUp() { + s3 = mock(AmazonS3.class); + service = new AWSS3Service(s3); + } + + @Test + public void whenInitializingAWSS3Service_thenNotNull() { + assertThat(new AWSS3Service()).isNotNull(); + } + + @Test + public void whenVerifyingIfS3BucketExist_thenCorrect() { + service.doesBucketExist(BUCKET_NAME); + verify(s3).doesBucketExist(BUCKET_NAME); + } + + @Test + public void whenVerifyingCreationOfS3Bucket_thenCorrect() { + service.createBucket(BUCKET_NAME); + verify(s3).createBucket(BUCKET_NAME); + } + + @Test + public void whenVerifyingListBuckets_thenCorrect() { + service.listBuckets(); + verify(s3).listBuckets(); + } + + @Test + public void whenDeletingBucket_thenCorrect() { + service.deleteBucket(BUCKET_NAME); + verify(s3).deleteBucket(BUCKET_NAME); + } + + @Test + public void whenVerifyingPutObject_thenCorrect() { + File file = mock(File.class); + PutObjectResult result = mock(PutObjectResult.class); + when(s3.putObject(anyString(), anyString(), (File) any())).thenReturn(result); + + assertThat(service.putObject(BUCKET_NAME, KEY_NAME, file)).isEqualTo(result); + verify(s3).putObject(BUCKET_NAME, KEY_NAME, file); + } + + @Test + public void whenVerifyingListObjects_thenCorrect() { + service.listObjects(BUCKET_NAME); + verify(s3).listObjects(BUCKET_NAME); + } + + @Test + public void whenVerifyingGetObject_thenCorrect() { + service.getObject(BUCKET_NAME, KEY_NAME); + verify(s3).getObject(BUCKET_NAME, KEY_NAME); + } + + @Test + public void whenVerifyingCopyObject_thenCorrect() { + CopyObjectResult result = mock(CopyObjectResult.class); + when(s3.copyObject(anyString(), anyString(), anyString(), anyString())).thenReturn(result); + + assertThat(service.copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2)).isEqualTo(result); + verify(s3).copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2); + } + + @Test + public void whenVerifyingDeleteObject_thenCorrect() { + service.deleteObject(BUCKET_NAME, KEY_NAME); + verify(s3).deleteObject(BUCKET_NAME, KEY_NAME); + } + + @Test + public void whenVerifyingDeleteObjects_thenCorrect() { + DeleteObjectsRequest request = mock(DeleteObjectsRequest.class); + DeleteObjectsResult result = mock(DeleteObjectsResult.class); + when(s3.deleteObjects((DeleteObjectsRequest)any())).thenReturn(result); + + assertThat(service.deleteObjects(request)).isEqualTo(result); + verify(s3).deleteObjects(request); + } + +} diff --git a/bootique/config.yml b/bootique/config.yml new file mode 100644 index 0000000000..269b4ab867 --- /dev/null +++ b/bootique/config.yml @@ -0,0 +1,11 @@ +log: + level: warn + appenders: + - type: file + logFormat: '%c{20}: %m%n' + file: /home/logger.log + +jetty: + context: /hello + connector: + port: 10001 diff --git a/bootique/dependency-reduced-pom.xml b/bootique/dependency-reduced-pom.xml new file mode 100644 index 0000000000..ed18f4e42a --- /dev/null +++ b/bootique/dependency-reduced-pom.xml @@ -0,0 +1,50 @@ + + + + bootique-parent + io.bootique.parent + 0.12 + + 4.0.0 + com.baeldung.bootique + bootique + bootique + 1.0-SNAPSHOT + http://maven.apache.org + + + + maven-shade-plugin + + + + + + io.bootique + bootique-test + 0.23 + test + + + junit + junit + 3.8.1 + test + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + com.baeldung.bootique.App + + + diff --git a/bootique/pom.xml b/bootique/pom.xml new file mode 100644 index 0000000000..28b716e104 --- /dev/null +++ b/bootique/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung.bootique + bootique + jar + 1.0-SNAPSHOT + bootique + http://maven.apache.org + + + com.baeldung.bootique.App + + + + io.bootique.parent + bootique-parent + 0.12 + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + + + io.bootique.jersey + bootique-jersey + compile + + + io.bootique.logback + bootique-logback + compile + + + io.bootique + bootique-test + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + \ No newline at end of file diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java new file mode 100644 index 0000000000..cc1b90ce7d --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -0,0 +1,41 @@ +package com.baeldung.bootique; + +import com.baeldung.bootique.module.ModuleBinder; +import com.baeldung.bootique.router.IndexController; +import com.baeldung.bootique.router.SaveController; +import com.google.inject.Module; +import io.bootique.Bootique; +import io.bootique.jersey.JerseyModule; +import io.bootique.log.BootLogger; + +import java.util.function.Supplier; + +public class App { + + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } + + @Override + public void stdout(String arg0) { + // ... + } + + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } + + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java new file mode 100644 index 0000000000..8811d48652 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -0,0 +1,15 @@ +package com.baeldung.bootique.module; + +import com.baeldung.bootique.service.HelloService; +import com.baeldung.bootique.service.impl.HelloServiceImpl; +import com.google.inject.Binder; +import com.google.inject.Module; + +public class ModuleBinder implements Module { + + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java new file mode 100644 index 0000000000..cf78177e6d --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -0,0 +1,13 @@ +package com.baeldung.bootique.module; + +import com.google.inject.Module; +import io.bootique.BQModuleProvider; + +public class ModuleProvider implements BQModuleProvider { + + @Override + public Module module() { + return new ModuleBinder(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java new file mode 100644 index 0000000000..6e3b31df41 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class IndexController { + + @GET + public String index() { + return "Hello, baeldung!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java new file mode 100644 index 0000000000..f38f59708c --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -0,0 +1,20 @@ +package com.baeldung.bootique.router; + +import com.baeldung.bootique.service.HelloService; +import com.google.inject.Inject; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +@Path("/save") +public class SaveController { + + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java new file mode 100644 index 0000000000..74c0401cc3 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java @@ -0,0 +1,7 @@ +package com.baeldung.bootique.service; + +public interface HelloService { + + boolean save(); + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java new file mode 100644 index 0000000000..d2c0b5b838 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.bootique.service.impl; + +import com.baeldung.bootique.service.HelloService; + +public class HelloServiceImpl implements HelloService { + + @Override + public boolean save() { + return true; + } + +} diff --git a/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider new file mode 100644 index 0000000000..714cf3a2df --- /dev/null +++ b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider @@ -0,0 +1 @@ +com.baeldung.bootique.module.ModuleProvider \ No newline at end of file diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java new file mode 100644 index 0000000000..8856780ed4 --- /dev/null +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -0,0 +1,27 @@ +package com.baeldung.bootique; + +import com.baeldung.bootique.service.HelloService; +import io.bootique.BQRuntime; +import io.bootique.test.junit.BQDaemonTestFactory; +import io.bootique.test.junit.BQTestFactory; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AppTest { + + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); + + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } + +} diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/camel-api/src/main/java/com/baeldung/camel/Application.java index f805385ff9..aadd37a3b4 100644 --- a/camel-api/src/main/java/com/baeldung/camel/Application.java +++ b/camel-api/src/main/java/com/baeldung/camel/Application.java @@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @ComponentScan(basePackages="com.baeldung.camel") -public class Application extends SpringBootServletInitializer { +public class Application{ @Value("${server.port}") String serverPort; @@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer { .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); /** -The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to your REST services request and response types. -This allows you, as a developer, to work with the POJOs in Java code. +The Rest DSL supports automatic binding json/xml contents to/from +POJOs using Camels Data Format. +By default the binding mode is off, meaning there is no automatic +binding happening for incoming and outgoing messages. +You may want to use binding if you develop POJOs that maps to +your REST services request and response types. */ rest("/api/").description("Teste REST Service") diff --git a/core-java-9/README.md b/core-java-9/README.md index 3e82ffe14b..22d6903f06 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -13,3 +13,6 @@ - [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) +- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams) +- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java index 299f74e877..5dc00dba25 100644 --- a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java @@ -6,7 +6,7 @@ public class ServiceMain { public static void main(String[] args) throws InterruptedException { ProcessHandle thisProcess = ProcessHandle.current(); - long pid = thisProcess.getPid(); + long pid = thisProcess.pid(); Optional opArgs = Optional.ofNullable(args); String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java new file mode 100644 index 0000000000..93579019a1 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.java9.language; + +import org.junit.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +public class Java9ObjectsAPIUnitTest { + + private List aMethodReturningNullList(){ + return null; + } + + @Test + public void givenNullObject_whenRequireNonNullElse_thenElse(){ + List aList = Objects.requireNonNullElse( + aMethodReturningNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(Collections.EMPTY_LIST)); + } + + private List aMethodReturningNonNullList(){ + return List.of("item1", "item2"); + } + + @Test + public void givenObject_whenRequireNonNullElse_thenObject(){ + List aList = Objects.requireNonNullElse( + aMethodReturningNonNullList(), Collections.EMPTY_LIST); + assertThat(aList, is(List.of("item1", "item2"))); + } + + @Test(expected = NullPointerException.class) + public void givenNull_whenRequireNonNullElse_thenException(){ + Objects.requireNonNullElse(null, null); + } + + @Test + public void givenObject_whenRequireNonNullElseGet_thenObject(){ + List aList = Objects.requireNonNullElseGet(null, List::of); + assertThat(aList, is(List.of())); + } + + @Test + public void givenNumber_whenInvokeCheckIndex_thenNumber(){ + int length = 5; + assertThat(Objects.checkIndex(4, length), is(4)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){ + int length = 5; + Objects.checkIndex(5, length); + } + + + @Test + public void givenSubRange_whenCheckFromToIndex_thenNumber(){ + int length = 6; + assertThat(Objects.checkFromToIndex(2,length,length), is(2)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){ + int length = 6; + Objects.checkFromToIndex(2,7,length); + } + + + @Test + public void givenSubRange_whenCheckFromIndexSize_thenNumber(){ + int length = 6; + assertThat(Objects.checkFromIndexSize(2,3,length), is(2)); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){ + int length = 6; + Objects.checkFromIndexSize(2, 6, length); + } + + +} diff --git a/core-java-concurrency/.gitignore b/core-java-concurrency/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-concurrency/.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-concurrency/README.md b/core-java-concurrency/README.md new file mode 100644 index 0000000000..f1d95482d4 --- /dev/null +++ b/core-java-concurrency/README.md @@ -0,0 +1,32 @@ +========= + +## Core Java Concurrency Examples + +### Relevant Articles: +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) +- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) +- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) +- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) +- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) +- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) +- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks) +- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) +- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) +- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) +- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) +- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) +- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) +- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) +- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers) +- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) +- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser) +- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) +- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables) +- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier) +- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) +- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) +- [Semaphores in Java](http://www.baeldung.com/java-semaphore) diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml new file mode 100644 index 0000000000..bf858047e9 --- /dev/null +++ b/core-java-concurrency/pom.xml @@ -0,0 +1,237 @@ + + 4.0.0 + com.baeldung + core-java-concurrency + 0.1.0-SNAPSHOT + jar + + core-java-concurrency + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + com.google.guava + guava + ${guava.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + + + core-java-concurrency + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + ${project.basedir} + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + + + 21.0 + 3.5 + 3.6.1 + 2.5 + 4.1 + 4.01 + + + 3.6.1 + 1.7.0 + + + diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java new file mode 100644 index 0000000000..b77019eea5 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.Scheduledexecutorservice; + +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public class ScheduledExecutorServiceDemo { + + public void execute() { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + + ScheduledFuture scheduledFuture = executorService.schedule(() -> { + // Task + }, 1, TimeUnit.SECONDS); + + executorService.scheduleAtFixedRate(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + executorService.scheduleWithFixedDelay(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + Future future = executorService.schedule(() -> { + // Task + return "Hellow world"; + }, 1, TimeUnit.SECONDS); + + executorService.shutdown(); + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java new file mode 100644 index 0000000000..e3a1629ce1 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class SafeCounterWithLock { + private volatile int counter; + + int getValue() { + return counter; + } + + synchronized void increment() { + counter++; + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java new file mode 100644 index 0000000000..18ade35efb --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -0,0 +1,21 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SafeCounterWithoutLock { + private final AtomicInteger counter = new AtomicInteger(0); + + int getValue() { + return counter.get(); + } + + void increment() { + while(true) { + int existingValue = getValue(); + int newValue = existingValue + 1; + if(counter.compareAndSet(existingValue, newValue)) { + return; + } + } + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java new file mode 100644 index 0000000000..500ef5bd7e --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class UnsafeCounter { + private int counter; + + int getValue() { + return counter; + } + + void increment() { + counter++; + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java similarity index 85% rename from core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java index 9dcd0a3e47..b301e994d5 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java @@ -19,13 +19,15 @@ public class NumbersProducer implements Runnable { try { generateNumbers(); } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + Thread.currentThread() + .interrupt(); } } private void generateNumbers() throws InterruptedException { for (int i = 0; i < 100; i++) { - numbersQueue.put(ThreadLocalRandom.current().nextInt(100)); + numbersQueue.put(ThreadLocalRandom.current() + .nextInt(100)); } for (int j = 0; j < poisonPillPerProducer; j++) { numbersQueue.put(poisonPill); diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java similarity index 87% rename from core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java index 977dae4fdb..758bdecd0c 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java @@ -15,14 +15,12 @@ public class CyclicBarrierDemo { private int NUM_PARTIAL_RESULTS; private int NUM_WORKERS; - private void runSimulation(int numWorkers, int numberOfPartialResults) { NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_WORKERS = numWorkers; cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread()); - System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " - + NUM_PARTIAL_RESULTS + " partial results each"); + System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each"); for (int i = 0; i < NUM_WORKERS; i++) { Thread worker = new Thread(new NumberCruncherThread()); worker.setName("Thread " + i); @@ -38,8 +36,7 @@ public class CyclicBarrierDemo { List partialResult = new ArrayList<>(); for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { Integer num = random.nextInt(10); - System.out.println(thisThreadName - + ": Crunching some numbers! Final result - " + num); + System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num); partialResult.add(num); } partialResults.add(partialResult); @@ -57,13 +54,12 @@ public class CyclicBarrierDemo { @Override public void run() { String thisThreadName = Thread.currentThread().getName(); - System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS - + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); + System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); int sum = 0; for (List threadResult : partialResults) { System.out.print("Adding "); for (Integer partialResult : threadResult) { - System.out.print(partialResult+" "); + System.out.print(partialResult + " "); sum += partialResult; } System.out.println(); diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java new file mode 100644 index 0000000000..a9b92d9f4a --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.CyclicBarrier; + +public class CyclicBarrierExample { + + public void start() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> { + // Task + System.out.println("All previous tasks are completed"); + }); + + Thread t1 = new Thread(new Task(cyclicBarrier), "T1"); + Thread t2 = new Thread(new Task(cyclicBarrier), "T2"); + Thread t3 = new Thread(new Task(cyclicBarrier), "T3"); + + if (!cyclicBarrier.isBroken()) { + t1.start(); + t2.start(); + t3.start(); + } + } +} + diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java new file mode 100644 index 0000000000..cc9ed105dc --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +public class Task implements Runnable { + + private CyclicBarrier barrier; + + public Task(CyclicBarrier barrier) { + this.barrier = barrier; + } + + @Override + public void run() { + try { + System.out.println("Thread : " + Thread.currentThread().getName() + " is waiting"); + barrier.await(); + System.out.println("Thread : " + Thread.currentThread().getName() + " is released"); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java similarity index 86% rename from core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java index 5f72758e71..312eb929ed 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java @@ -27,9 +27,6 @@ public class DelayObject implements Delayed { @Override public String toString() { - return "{" + - "data='" + data + '\'' + - ", startTime=" + startTime + - '}'; + return "{" + "data='" + data + '\'' + ", startTime=" + startTime + '}'; } } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java similarity index 96% rename from core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java index c5672706ad..4de420900a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java @@ -15,7 +15,8 @@ public class Philosopher implements Runnable { Thread.sleep(((int) (Math.random() * 100))); } - @Override public void run() { + @Override + public void run() { try { while (true) { doAction(System.nanoTime() + ": Thinking"); // thinking diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java new file mode 100644 index 0000000000..84998cb489 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class ExecutorDemo { + + public void execute() { + Executor executor = new Invoker(); + executor.execute(()->{ + // task to be performed + }); + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/Invoker.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/Invoker.java new file mode 100644 index 0000000000..d9f11986d6 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/Invoker.java @@ -0,0 +1,12 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class Invoker implements Executor { + + @Override + public void execute(Runnable r) { + r.run(); + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java new file mode 100644 index 0000000000..83a9fb6692 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -0,0 +1,27 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class ExecutorServiceDemo { + + ExecutorService executor = Executors.newFixedThreadPool(10); + + public void execute() { + + executor.submit(() -> { + new Task(); + }); + + executor.shutdown(); + executor.shutdownNow(); + try { + executor.awaitTermination(20l, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/Task.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/Task.java new file mode 100644 index 0000000000..9a21bca80c --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.executorservice; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FutureDemo.java new file mode 100644 index 0000000000..4794d5cb61 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -0,0 +1,44 @@ +package com.baeldung.concurrent.future; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class FutureDemo { + + public String invoke() { + + String str = null; + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; + }); + + future.cancel(false); + + try { + future.get(20, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e1) { + e1.printStackTrace(); + } + + if (future.isDone() && !future.isCancelled()) { + try { + str = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + + return str; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java new file mode 100644 index 0000000000..3a1d8555d3 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.semaphore; + +import java.util.concurrent.Semaphore; + +public class SemaPhoreDemo { + + static Semaphore semaphore = new Semaphore(10); + + public void execute() throws InterruptedException { + + System.out.println("Available permit : " + semaphore.availablePermits()); + System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength()); + + if (semaphore.tryAcquire()) { + semaphore.acquire(); + // perform some critical operations + semaphore.release(); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/skiplist/Event.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java similarity index 100% rename from core-java/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java rename to core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java new file mode 100644 index 0000000000..f708804cae --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadfactory; + +import java.util.concurrent.ThreadFactory; + +public class BaeldungThreadFactory implements ThreadFactory { + + private int threadId; + private String name; + + public BaeldungThreadFactory(String name) { + threadId = 1; + this.name = name; + } + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, name + "-Thread_" + threadId); + System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); + threadId++; + return t; + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java new file mode 100644 index 0000000000..d2af97b761 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.threadfactory; + +public class Demo { + + public void execute() { + BaeldungThreadFactory factory = new BaeldungThreadFactory("BaeldungThreadFactory"); + for (int i = 0; i < 10; i++) { + Thread t = factory.newThread(new Task()); + t.start(); + } + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Task.java new file mode 100644 index 0000000000..a69623c667 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.threadfactory; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java new file mode 100644 index 0000000000..063c835481 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.volatilekeyword; + + +public class SharedObject { + private volatile int count=0; + + void increamentCount(){ + count++; + } + public int getCount(){ + return count; + } +} diff --git a/core-java/src/main/java/com/baeldung/threadlocal/Context.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java similarity index 65% rename from core-java/src/main/java/com/baeldung/threadlocal/Context.java rename to core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java index 241fb2f1e0..88b78fb259 100644 --- a/core-java/src/main/java/com/baeldung/threadlocal/Context.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java @@ -4,14 +4,14 @@ package com.baeldung.threadlocal; public class Context { private final String userName; - public Context(String userName) { + Context(String userName) { this.userName = userName; } @Override public String toString() { return "Context{" + - "userNameSecret='" + userName + '\'' + - '}'; + "userNameSecret='" + userName + '\'' + + '}'; } } diff --git a/core-java/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java similarity index 76% rename from core-java/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java rename to core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java index e5854e218a..8cb4b3968f 100644 --- a/core-java/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java @@ -5,11 +5,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class SharedMapWithUserContext implements Runnable { - public final static Map userContextPerUserId = new ConcurrentHashMap<>(); + final static Map userContextPerUserId = new ConcurrentHashMap<>(); private final Integer userId; private UserRepository userRepository = new UserRepository(); - public SharedMapWithUserContext(Integer userId) { + SharedMapWithUserContext(Integer userId) { this.userId = userId; } diff --git a/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java similarity index 92% rename from core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java rename to core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java index de7e4a0369..d4ab906c30 100644 --- a/core-java/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java @@ -10,7 +10,7 @@ public class ThreadLocalWithUserContext implements Runnable { private final Integer userId; private UserRepository userRepository = new UserRepository(); - public ThreadLocalWithUserContext(Integer userId) { + ThreadLocalWithUserContext(Integer userId) { this.userId = userId; } diff --git a/core-java/src/main/java/com/baeldung/threadlocal/UserRepository.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java similarity index 71% rename from core-java/src/main/java/com/baeldung/threadlocal/UserRepository.java rename to core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java index 3fe76f75c0..2597594940 100644 --- a/core-java/src/main/java/com/baeldung/threadlocal/UserRepository.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java @@ -4,7 +4,7 @@ import java.util.UUID; public class UserRepository { - public String getUserNameForUserId(Integer userId) { + String getUserNameForUserId(Integer userId) { return UUID.randomUUID().toString(); } } diff --git a/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java similarity index 56% rename from core-java/src/main/java/com/baeldung/threadpool/CountingTask.java rename to core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java index effdf54916..a7447d040f 100644 --- a/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -2,19 +2,21 @@ package com.baeldung.threadpool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; -import java.util.stream.Collectors; public class CountingTask extends RecursiveTask { private final TreeNode node; - public CountingTask(TreeNode node) { + CountingTask(TreeNode node) { this.node = node; } @Override protected Integer compute() { - return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join)); + return node.getValue() + node.getChildren().stream() + .map(childNode -> new CountingTask(childNode).fork()) + .mapToInt(ForkJoinTask::join) + .sum(); } } diff --git a/core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java-concurrency/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java rename to core-java-concurrency/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java new file mode 100644 index 0000000000..65dfed01a2 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java @@ -0,0 +1,25 @@ +package com.baeldung.threadpool; + +import com.google.common.collect.Sets; + +import java.util.Set; + +public class TreeNode { + + private int value; + + private Set children; + + TreeNode(int value, TreeNode... children) { + this.value = value; + this.children = Sets.newHashSet(children); + } + + public int getValue() { + return value; + } + + public Set getChildren() { + return children; + } +} diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java similarity index 83% rename from core-java/src/main/java/com/baeldung/transferqueue/Consumer.java rename to core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java index 69d7ff2390..f3be6a030e 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -9,13 +9,12 @@ import java.util.concurrent.atomic.AtomicInteger; public class Consumer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); - private final TransferQueue transferQueue; private final String name; - private final int numberOfMessagesToConsume; - public final AtomicInteger numberOfConsumedMessages = new AtomicInteger(); + final int numberOfMessagesToConsume; + final AtomicInteger numberOfConsumedMessages = new AtomicInteger(); - public Consumer(TransferQueue transferQueue, String name, int numberOfMessagesToConsume) { + Consumer(TransferQueue transferQueue, String name, int numberOfMessagesToConsume) { this.transferQueue = transferQueue; this.name = name; this.numberOfMessagesToConsume = numberOfMessagesToConsume; diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java similarity index 84% rename from core-java/src/main/java/com/baeldung/transferqueue/Producer.java rename to core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java index c7df7c410a..b73cf5ac19 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Producer.java +++ b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java @@ -12,10 +12,10 @@ public class Producer implements Runnable { private final TransferQueue transferQueue; private final String name; - private final Integer numberOfMessagesToProduce; - public final AtomicInteger numberOfProducedMessages = new AtomicInteger(); + final Integer numberOfMessagesToProduce; + final AtomicInteger numberOfProducedMessages = new AtomicInteger(); - public Producer(TransferQueue transferQueue, String name, Integer numberOfMessagesToProduce) { + Producer(TransferQueue transferQueue, String name, Integer numberOfMessagesToProduce) { this.transferQueue = transferQueue; this.name = name; this.numberOfMessagesToProduce = numberOfMessagesToProduce; diff --git a/core-java-concurrency/src/main/java/log4j.properties b/core-java-concurrency/src/main/java/log4j.properties new file mode 100644 index 0000000000..5fe42d854c --- /dev/null +++ b/core-java-concurrency/src/main/java/log4j.properties @@ -0,0 +1,9 @@ +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=DEBUG, A1 + +# A1 is set to be a ConsoleAppender. +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/core-java-concurrency/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java similarity index 82% rename from core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 0c3a13d176..45d2ec68e4 100644 --- a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -4,7 +4,11 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.*; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -15,7 +19,6 @@ public class CompletableFutureLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class); - @Test public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { Future completableFuture = calculateAsync(); @@ -27,11 +30,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsync() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.complete("Hello"); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.complete("Hello"); + return null; + }); return completableFuture; } @@ -47,11 +51,12 @@ public class CompletableFutureLongRunningUnitTest { private Future calculateAsyncWithCancellation() throws InterruptedException { CompletableFuture completableFuture = new CompletableFuture<>(); - Executors.newCachedThreadPool().submit(() -> { - Thread.sleep(500); - completableFuture.cancel(false); - return null; - }); + Executors.newCachedThreadPool() + .submit(() -> { + Thread.sleep(500); + completableFuture.cancel(false); + return null; + }); return completableFuture; } @@ -98,21 +103,24 @@ public class CompletableFutureLongRunningUnitTest { @Test public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World")); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); + CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello") + .thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2); assertEquals("Hello World", completableFuture.get()); } @Test public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { - CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); + CompletableFuture.supplyAsync(() -> "Hello") + .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); } @Test @@ -131,7 +139,9 @@ public class CompletableFutureLongRunningUnitTest { assertTrue(future2.isDone()); assertTrue(future3.isDone()); - String combined = Stream.of(future1, future2, future3).map(CompletableFuture::join).collect(Collectors.joining(" ")); + String combined = Stream.of(future1, future2, future3) + .map(CompletableFuture::join) + .collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined); } @@ -147,7 +157,8 @@ public class CompletableFutureLongRunningUnitTest { throw new RuntimeException("Computation error!"); } return "Hello, " + name; - }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); + }) + .handle((s, t) -> s != null ? s : "Hello, Stranger!"); assertEquals("Hello, Stranger!", completableFuture.get()); } diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java similarity index 85% rename from core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java index 2f1abef64e..8cddf31245 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java @@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest { @Test public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { - //given + // given ExecutorService executorService = Executors.newFixedThreadPool(8); LongBinaryOperator sum = Long::sum; LongAccumulator accumulator = new LongAccumulator(sum, 0L); int numberOfThreads = 4; int numberOfIncrements = 100; - //when - Runnable accumulateAction = () -> IntStream - .rangeClosed(0, numberOfIncrements) - .forEach(accumulator::accumulate); + // when + Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate); for (int i = 0; i < numberOfThreads; i++) { executorService.execute(accumulateAction); } - - //then + // then executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.shutdown(); assertEquals(accumulator.get(), 20200); - } } diff --git a/core-java/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java new file mode 100644 index 0000000000..e9b2e164ae --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java @@ -0,0 +1,38 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +public class ThreadSafeCounterTest { + + @Test + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java new file mode 100644 index 0000000000..cc7cc18bb5 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java @@ -0,0 +1,33 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +/** + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this + * test from build by adding this in manual test + */ +public class ThreadUnsafeCounterManualTest { + + @Test + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + UnsafeCounter unsafeCounter = new UnsafeCounter(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(unsafeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, unsafeCounter.getValue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java index fc343e4cee..d49a8b8590 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java @@ -18,7 +18,9 @@ public class CountdownLatchExampleIntegrationTest { // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList()); + List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); // When workers.forEach(Thread::start); @@ -26,7 +28,6 @@ public class CountdownLatchExampleIntegrationTest { outputScraper.add("Latch released"); // Then - outputScraper.forEach(Object::toString); assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released"); } @@ -35,7 +36,9 @@ public class CountdownLatchExampleIntegrationTest { // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList()); + List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); // When workers.forEach(Thread::start); @@ -63,7 +66,6 @@ public class CountdownLatchExampleIntegrationTest { outputScraper.add("Workers complete"); // Then - outputScraper.forEach(Object::toString); assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete"); } diff --git a/core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java index 5f8b05a974..c2513f38c1 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java @@ -22,7 +22,6 @@ public class SquareCalculatorIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class); - @Rule public TestName name = new TestName(); diff --git a/core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java index 3014ae38b2..f3ced219f7 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java @@ -49,9 +49,7 @@ public class SynchronizedHashMapWithRWLockManualTest { private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) { for (int i = 0; i < threadCount; i++) - service.execute(() -> { - object.get("key" + threadCount); - }); + service.execute(() -> object.get("key" + threadCount)); } } diff --git a/core-java/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java diff --git a/core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java new file mode 100644 index 0000000000..8770cb4e90 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -0,0 +1,71 @@ +package com.baeldung.concurrent.volatilekeyword; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +public class SharedObjectManualTest { + + private SharedObject sharedObject; + private int valueReadByThread2; + private int valueReadByThread3; + + @Before + public void setUp() { + sharedObject = new SharedObject(); + } + + @Test + public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writer = new Thread(() -> sharedObject.increamentCount()); + writer.start(); + + + Thread readerOne = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread2 = sharedObject.getCount(); + }); + readerOne.start(); + + Thread readerTwo = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread3 = sharedObject.getCount(); + }); + readerTwo.start(); + + assertEquals(1, valueReadByThread2); + assertEquals(1, valueReadByThread3); + + } + + @Test + public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writerOne = new Thread(() -> sharedObject.increamentCount()); + writerOne.start(); + Thread.sleep(100); + + Thread writerTwo = new Thread(() -> sharedObject.increamentCount()); + writerTwo.start(); + Thread.sleep(100); + + Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount()); + readerOne.start(); + + Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount()); + readerTwo.start(); + + assertEquals(2, valueReadByThread2); + assertEquals(2, valueReadByThread3); + + } +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index ec865f71c4..2971f14c41 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -47,7 +47,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.awaitTermination(1, TimeUnit.MINUTES); for (int i = 1; i <= MAX_SIZE; i++) { - assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); + assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1) + .intValue()); } assertEquals(MAX_SIZE, concurrentMap.size()); } @@ -69,7 +70,8 @@ public class ConcurrentMapAggregateStatusManualTest { executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); - assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); + assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1) + .intValue()); assertEquals(MAX_SIZE, concurrentMap.size()); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java index 33e3326427..cbac6e7f4c 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java @@ -12,7 +12,7 @@ import static org.junit.Assert.assertNull; public class ConcurrentMapNullKeyValueManualTest { - ConcurrentMap concurrentMap; + private ConcurrentMap concurrentMap; @Before public void setup() { diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java similarity index 62% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java index 5c1612ca60..3f36d0df5d 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java @@ -1,27 +1,31 @@ package com.baeldung.java.concurrentmap; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; -import java.util.concurrent.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class ConcurrentMapPerformanceManualTest { @Test public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception { - Map hashtable = new Hashtable<>(); - Map synchronizedHashMap = Collections.synchronizedMap(new HashMap<>()); - Map concurrentHashMap = new ConcurrentHashMap<>(); + final Map hashtable = new Hashtable<>(); + final Map synchronizedHashMap = Collections.synchronizedMap(new HashMap<>()); + final Map concurrentHashMap = new ConcurrentHashMap<>(); - long hashtableAvgRuntime = timeElapseForGetPut(hashtable); - long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap); - long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap); + final long hashtableAvgRuntime = timeElapseForGetPut(hashtable); + final long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap); + final long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap); System.out.println(String.format("Hashtable: %s, syncHashMap: %s, ConcurrentHashMap: %s", hashtableAvgRuntime, syncHashMapAvgRuntime, concurrentHashMapAvgRuntime)); @@ -31,13 +35,13 @@ public class ConcurrentMapPerformanceManualTest { } private long timeElapseForGetPut(Map map) throws InterruptedException { - ExecutorService executorService = Executors.newFixedThreadPool(4); - long startTime = System.nanoTime(); + final ExecutorService executorService = Executors.newFixedThreadPool(4); + final long startTime = System.nanoTime(); for (int i = 0; i < 4; i++) { executorService.execute(() -> { for (int j = 0; j < 500_000; j++) { - int value = ThreadLocalRandom.current().nextInt(10000); - String key = String.valueOf(value); + final int value = ThreadLocalRandom.current().nextInt(10000); + final String key = String.valueOf(value); map.put(key, value); map.get(key); } @@ -56,11 +60,11 @@ public class ConcurrentMapPerformanceManualTest { return 1; } } - int executeTimes = 5000; + final int executeTimes = 5000; - Map mapOfSameHash = new ConcurrentHashMap<>(); + final Map mapOfSameHash = new ConcurrentHashMap<>(); ExecutorService executorService = Executors.newFixedThreadPool(2); - long sameHashStartTime = System.currentTimeMillis(); + final long sameHashStartTime = System.currentTimeMillis(); for (int i = 0; i < 2; i++) { executorService.execute(() -> { for (int j = 0; j < executeTimes; j++) { @@ -71,10 +75,10 @@ public class ConcurrentMapPerformanceManualTest { executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); - long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime; - Map mapOfDefaultHash = new ConcurrentHashMap<>(); + final long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime; + final Map mapOfDefaultHash = new ConcurrentHashMap<>(); executorService = Executors.newFixedThreadPool(2); - long defaultHashStartTime = System.currentTimeMillis(); + final long defaultHashStartTime = System.currentTimeMillis(); for (int i = 0; i < 2; i++) { executorService.execute(() -> { for (int j = 0; j < executeTimes; j++) { @@ -85,11 +89,11 @@ public class ConcurrentMapPerformanceManualTest { executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); - long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime; + final long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime; assertEquals(executeTimes * 2, mapOfDefaultHash.size()); assertEquals(executeTimes * 2, mapOfSameHash.size()); System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration)); - assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10); + assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > (mapOfDefaultHashDuration * 10)); } } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java similarity index 80% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java index 768c31ee80..c0753db513 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java @@ -18,7 +18,7 @@ public class ConcurrentNavigableMapManualTest { public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { NavigableMap skipListMap = new ConcurrentSkipListMap<>(); - updateMapConcurrently(skipListMap, 4); + updateMapConcurrently(skipListMap); Iterator skipListIter = skipListMap.keySet().iterator(); int previous = skipListIter.next(); @@ -28,9 +28,9 @@ public class ConcurrentNavigableMapManualTest { } } - private void updateMapConcurrently(NavigableMap navigableMap, int concurrencyLevel) throws InterruptedException { - ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); - for (int i = 0; i < concurrencyLevel; i++) { + private void updateMapConcurrently(NavigableMap navigableMap) throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(4); + for (int i = 0; i < 4; i++) { executorService.execute(() -> { ThreadLocalRandom random = ThreadLocalRandom.current(); for (int j = 0; j < 10000; j++) { @@ -45,26 +45,26 @@ public class ConcurrentNavigableMapManualTest { @Test public void givenSkipListMap_whenNavConcurrently_thenCountCorrect() throws InterruptedException { NavigableMap skipListMap = new ConcurrentSkipListMap<>(); - int count = countMapElementByPollingFirstEntry(skipListMap, 10000, 4); + int count = countMapElementByPollingFirstEntry(skipListMap); assertEquals(10000 * 4, count); } @Test public void givenTreeMap_whenNavConcurrently_thenCountError() throws InterruptedException { NavigableMap treeMap = new TreeMap<>(); - int count = countMapElementByPollingFirstEntry(treeMap, 10000, 4); + int count = countMapElementByPollingFirstEntry(treeMap); assertNotEquals(10000 * 4, count); } - private int countMapElementByPollingFirstEntry(NavigableMap navigableMap, int elementCount, int concurrencyLevel) throws InterruptedException { - for (int i = 0; i < elementCount * concurrencyLevel; i++) { + private int countMapElementByPollingFirstEntry(NavigableMap navigableMap) throws InterruptedException { + for (int i = 0; i < 10000 * 4; i++) { navigableMap.put(i, i); } AtomicInteger counter = new AtomicInteger(0); - ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); - for (int j = 0; j < concurrencyLevel; j++) { + ExecutorService executorService = Executors.newFixedThreadPool(4); + for (int j = 0; j < 4; j++) { executorService.execute(() -> { - for (int i = 0; i < elementCount; i++) { + for (int i = 0; i < 10000; i++) { if (navigableMap.pollFirstEntry() != null) { counter.incrementAndGet(); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java similarity index 76% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 43cbb2d293..e4fac66fe3 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -16,8 +16,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { Map map = new ConcurrentHashMap<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -25,8 +29,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { Map map = new Hashtable<>(); List sumList = parallelSum100(map, 1000); - assertEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertEquals(0, wrongResultCount); } @@ -34,8 +42,12 @@ public class ConcurretMapMemoryConsistencyManualTest { public void givenHashMap_whenSumParallel_thenError() throws Exception { Map map = new HashMap<>(); List sumList = parallelSum100(map, 100); - assertNotEquals(1, sumList.stream().distinct().count()); - long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); + assertNotEquals(1, sumList.stream() + .distinct() + .count()); + long wrongResultCount = sumList.stream() + .filter(num -> num != 100) + .count(); assertTrue(wrongResultCount > 0); } diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java similarity index 89% rename from core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java index f7a7bd5fe0..9cdac72d59 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -2,7 +2,6 @@ package com.baeldung.java.concurrentmodification; import org.junit.Test; -import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -28,9 +27,9 @@ public class ConcurrentModificationUnitTest { List integers = newArrayList(1, 2, 3); - for (Iterator iterator = integers.iterator(); iterator.hasNext();) { + for (Iterator iterator = integers.iterator(); iterator.hasNext(); ) { Integer integer = iterator.next(); - if(integer == 2) { + if (integer == 2) { iterator.remove(); } } @@ -45,7 +44,7 @@ public class ConcurrentModificationUnitTest { List toRemove = newArrayList(); for (Integer integer : integers) { - if(integer == 2) { + if (integer == 2) { toRemove.add(integer); } } @@ -69,10 +68,10 @@ public class ConcurrentModificationUnitTest { Collection integers = newArrayList(1, 2, 3); List collected = integers - .stream() - .filter(i -> i != 2) - .map(Object::toString) - .collect(toList()); + .stream() + .filter(i -> i != 2) + .map(Object::toString) + .collect(toList()); assertThat(collected).containsExactly("1", "3"); } diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java index 41eb864fd9..a1f5b6f1e2 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java @@ -72,7 +72,7 @@ public class Java8ExecutorServiceIntegrationTest { assertTrue(threadPoolExecutor.isShutdown()); assertFalse(notExecutedTasks.isEmpty()); - assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98); + assertTrue(notExecutedTasks.size() < 98); } private List smartShutdown(ExecutorService executorService) { diff --git a/core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index 9d8d3c884b..5fb85bb2c4 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); - @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { diff --git a/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java rename to core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java similarity index 88% rename from core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java rename to core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java index 42e85fc586..502672dea1 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java +++ b/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java @@ -23,7 +23,10 @@ public class ThreadPoolInParallelStreamIntegrationTest { List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + long actualTotal = customThreadPool + .submit(() -> aList.parallelStream() + .reduce(0L, Long::sum)) + .get(); assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); } diff --git a/core-java-concurrency/src/test/resources/.gitignore b/core-java-concurrency/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-concurrency/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 559507e472..ef63ac81e9 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -23,7 +23,6 @@ - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) -- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) - [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) - [Random List Element](http://www.baeldung.com/java-random-list-element) @@ -31,12 +30,10 @@ - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda) - [Java – Directory Size](http://www.baeldung.com/java-folder-size) - [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources) -- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) - [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) - [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) - [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) @@ -57,18 +54,11 @@ - [The Basics of Java Generics](http://www.baeldung.com/java-generics) - [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) -- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) -- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) -- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) - [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) -- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) -- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) -- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) - [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap) - [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) - [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) -- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) - [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers) - [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) @@ -91,7 +81,6 @@ - [Avoiding ConcurrentModificationException when iterating and removing](http://www.baeldung.com/avoiding-concurrentmodificationexception-when-iterating-and-removing) - [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) - [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) -- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) - [Using Math.pow in Java](http://www.baeldung.com/java-math-pow) - [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) - [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) @@ -101,33 +90,35 @@ - [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset) - [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) - [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) -- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue) - [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path) - [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) - [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration) -- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue) -- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue) - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) -- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map) -- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) -- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) - [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) +- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) +- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number) +- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) +- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) +- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) +- [Changing the Order in a Sum Operation Can Produce Different Results?](http://www.baeldung.com/java-floating-point-sum-order) +- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) +- [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map) - [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy) - [Introduction to JDBC](http://www.baeldung.com/java-jdbc) -- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist) - [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string) -- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser) - [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error) - [Split a String in Java](http://www.baeldung.com/java-split-string) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) -- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) - [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) - [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) diff --git a/core-java/pom.xml b/core-java/pom.xml index 84a56c8bc7..586486027a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -80,7 +80,11 @@ - + + log4j + log4j + 1.2.17 + org.slf4j slf4j-api @@ -182,6 +186,16 @@ fscontext ${fscontext.version} + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + ${hirondelle-date4j.version} + @@ -382,7 +396,7 @@ - + 2.8.5 @@ -391,7 +405,7 @@ 1.1.7 - 21.0 + 22.0 3.5 1.55 1.10 @@ -404,17 +418,19 @@ 1.8.7 1.16.12 4.6-b01 + 2.9.9 + 1.5.1 1.3 4.12 - 1.10.19 + 2.8.9 3.6.1 1.7.0 + 3.6.0 2.19.1 - - \ No newline at end of file + diff --git a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java index d672b9a4f5..a10499b362 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java +++ b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java @@ -4,12 +4,12 @@ import java.io.Serializable; public class AppleProduct implements Serializable { - private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) -// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) + private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) + // private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) public String headphonePort; public String thunderboltPort; - public String lighteningPort; + public String lightningPort; public String getHeadphonePort() { return headphonePort; @@ -23,4 +23,8 @@ public class AppleProduct implements Serializable { return serialVersionUID; } + public String getLightningPort() { + return lightningPort; + } + } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java index 3ed2b8be1d..ad8e929898 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java @@ -9,11 +9,12 @@ public class DeserializationUtility { public static void main(String[] args) throws ClassNotFoundException, IOException { - String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; System.out.println("Deserializing AppleProduct..."); AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj); System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort()); System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort()); + System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort()); } public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException { diff --git a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java index 1dbcc40e6b..aa7f66659a 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java @@ -13,6 +13,7 @@ public class SerializationUtility { AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; + macBook.lightningPort = "lightningPort2020"; String serializedObj = serializeObjectToString(macBook); System.out.println("Serialized AppleProduct object to string:"); diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java new file mode 100644 index 0000000000..0d69d0e7ec --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.adapter; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class AdapterPatternDriver { + + public static void main(String args[]) { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); + LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); + LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java new file mode 100644 index 0000000000..0b97b8228c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeed { + public double bugattiVeyronInMPH() { + return 268; + } + + public double mcLarenInMPH() { + return 241; + } + + public double astonMartinInMPH() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java new file mode 100644 index 0000000000..d9255f0910 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCarsSpeedAdapter { + public double bugattiVeyronInKMPH(); + + public double mcLarenInKMPH(); + + public double astonMartinInKMPH(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java new file mode 100644 index 0000000000..2767b78e38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { + + @Override + public double bugattiVeyronInKMPH() { + double mph = super.bugattiVeyronInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double mcLarenInKMPH() { + double mph = super.mcLarenInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double astonMartinInKMPH() { + double mph = super.astonMartinInMPH(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java new file mode 100644 index 0000000000..ed3f75b4a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Blue implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Blue"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java new file mode 100644 index 0000000000..921deadcac --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java @@ -0,0 +1,14 @@ +package com.baeldung.designpatterns.bridge; + +public class BridgePatternDriver { + + public static void main(String[] args) { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java new file mode 100644 index 0000000000..91d2b01609 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.bridge; + +public interface Color { + public void fillColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java new file mode 100644 index 0000000000..8c22a94f00 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Red implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Red"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java new file mode 100644 index 0000000000..c4daf7a821 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.baeldung.designpatterns.bridge; + +public abstract class Shape { + protected Color color; + + public Shape(Color color) { + this.color = color; + } + + abstract public void drawShape(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java new file mode 100644 index 0000000000..6b377197eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Square extends Shape { + + public Square(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Square drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java new file mode 100644 index 0000000000..900e78cf2b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Triangle extends Shape { + + public Triangle(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Triangle drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java new file mode 100644 index 0000000000..881add8b21 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class BubbleLights extends TreeDecorator { + + public BubbleLights(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithBubbleLights(); + } + + private String decorateWithBubbleLights() { + return " with Bubble Lights"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java new file mode 100644 index 0000000000..80a0865567 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.decorator; + +public interface ChristmasTree { + public String decorate(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java new file mode 100644 index 0000000000..9241fd59db --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.decorator; + +public class ChristmasTreeImpl implements ChristmasTree { + + @Override + public String decorate() { + return "Christmas tree"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java new file mode 100644 index 0000000000..70b4f801cd --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -0,0 +1,18 @@ +package com.baeldung.designpatterns.decorator; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class DecoratorPatternDriver { + + public static void main(String[] args) { + // christmas tree with just one Garland + ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); + LOG.info(tree1.decorate()); + + // christmas tree with two Garlands and one Bubble lights + ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl()))); + LOG.info(tree2.decorate()); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java new file mode 100644 index 0000000000..d2efd6e451 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class Garland extends TreeDecorator { + + public Garland(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithGarland(); + } + + private String decorateWithGarland() { + return " with Garland"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java new file mode 100644 index 0000000000..5427d2ac7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.decorator; + +public abstract class TreeDecorator implements ChristmasTree { + private ChristmasTree tree; + + public TreeDecorator(ChristmasTree tree) { + this.tree = tree; + } + + @Override + public String decorate() { + return tree.decorate(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java new file mode 100644 index 0000000000..96a6bfb878 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.proxy; + +public interface ExpensiveObject { + public void process(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java new file mode 100644 index 0000000000..de31e22b30 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.proxy; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG;; + +public class ExpensiveObjectImpl implements ExpensiveObject { + + public ExpensiveObjectImpl() { + heavyInitialConfiguration(); + } + + @Override + public void process() { + LOG.info("processing complete."); + } + + private void heavyInitialConfiguration() { + LOG.info("Loading initial configuration..."); + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java new file mode 100644 index 0000000000..f36e688c90 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.proxy; + +public class ExpensiveObjectProxy implements ExpensiveObject{ + private static ExpensiveObject object; + + @Override + public void process() { + if(object == null) { + object = new ExpensiveObjectImpl(); + } + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java new file mode 100644 index 0000000000..088b069e28 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.proxy; + +public class ProxyPatternDriver { + public static void main(String[] args) { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java new file mode 100644 index 0000000000..0fc86e30a7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns.singleton; + +public class ClassSingleton { + + private static ClassSingleton INSTANCE; + private String info = "Initial class info"; + + private ClassSingleton(){ + } + + public static ClassSingleton getInstance(){ + if(INSTANCE == null){ + INSTANCE = new ClassSingleton(); + } + + return INSTANCE; + } + + // getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java new file mode 100644 index 0000000000..f75484477b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.singleton; + +public enum EnumSingleton { + + INSTANCE("Initial enum info"); //Name of the single instance + + private String info; + + private EnumSingleton(String info) { + this.info = info; + } + + public EnumSingleton getInstance(){ + return INSTANCE; + } + + //getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java new file mode 100644 index 0000000000..f8ca2ffa78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.singleton; + +public class Sandbox { + + public static void main(String[] args) { + + //Class singleton + + ClassSingleton classSingleton1 = ClassSingleton.getInstance(); + //OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible + + System.out.println(classSingleton1.getInfo()); //Initial class info + + ClassSingleton classSingleton2 = ClassSingleton.getInstance(); + classSingleton2.setInfo("New class info"); + + System.out.println(classSingleton1.getInfo()); //New class info + System.out.println(classSingleton2.getInfo()); //New class info + + //Enum singleton + + EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); + + System.out.println(enumSingleton1.getInfo()); //Initial enum info + + EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); + enumSingleton2.setInfo("New enum info"); + + System.out.println(enumSingleton1.getInfo()); //New enum info + System.out.println(enumSingleton2.getInfo()); //New enum info + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java new file mode 100644 index 0000000000..f7b6e4f3e9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +public class LogerUtil { + + public final static Logger LOG = Logger.getLogger("GLOBAL"); + + static { + configuration(); + } + + private static void configuration() { + Properties props = new Properties(); + try { + props.load( + new BufferedReader( + new InputStreamReader( + LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties") + ) + ) + ); + } catch (IOException e) { + System.out.println("log4jstructuraldp.properties file not configured properly"); + System.exit(0); + } + PropertyConfigurator.configure(props); + } +} diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java index 4afce56e39..7e6bb5d3b2 100644 --- a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java +++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java @@ -14,26 +14,25 @@ public class LookupFSJNDI { super(); init(); } - + private void init() throws NamingException { Hashtable env = new Hashtable(); - - env.put (Context.INITIAL_CONTEXT_FACTORY, - "com.sun.jndi.fscontext.RefFSContextFactory"); + + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // URI to namespace (actual directory) env.put(Context.PROVIDER_URL, "file:./src/test/resources"); - + ctx = new InitialContext(env); } public InitialContext getCtx() { return ctx; } - + public File getFile(String fileName) { File file; try { - file = (File)getCtx().lookup(fileName); + file = (File) getCtx().lookup(fileName); } catch (NamingException e) { file = null; } diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java index ae79787570..ebe59e33b1 100644 --- a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java +++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -43,6 +43,7 @@ public class CustomRecursiveAction extends RecursiveAction { private void processing(String work) { String result = work.toUpperCase(); - logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName()); + logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread() + .getName()); } } diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java new file mode 100644 index 0000000000..c46c3de65a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -0,0 +1,41 @@ +package com.baeldung.hashcode.entities; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; + User user = (User) o; + return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 31 * hash + (int) id; + hash = 31 * hash + (name == null ? 0 : name.hashCode()); + hash = 31 * hash + (email == null ? 0 : email.hashCode()); + logger.info("hashCode() method called - Computed hash: " + hash); + return hash; + } + // getters and setters here +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java index ede269528a..57aefdd169 100644 --- a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java +++ b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java @@ -5,6 +5,6 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Greeter { - - public String greet() default ""; + + public String greet() default ""; } diff --git a/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java b/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java new file mode 100644 index 0000000000..121e0f5d72 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java @@ -0,0 +1,91 @@ +package com.baeldung.javanetworking.uriurl; + +import java.io.BufferedReader; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class URIDemo { + private final Logger logger = LoggerFactory.getLogger(URIDemo.class); + + String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; + // parsed locator + String URISCHEME = "https"; + String URISCHEMESPECIFIC; + String URIHOST = "wordpress.org"; + String URIAUTHORITY = "wordpress.org:443"; + + String URIPATH = "/support/topic/page-jumps-within-wordpress/"; + int URIPORT = 443; + String URIQUERY = "replies=3"; + String URIFRAGMENT = "post-2278484"; + String URIUSERINFO; + String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT; + + URI uri; + URL url; + BufferedReader in = null; + String URIContent = ""; + + private String getParsedPieces(URI uri) { + logger.info("*** List of parsed pieces ***"); + URISCHEME = uri.getScheme(); + logger.info("URISCHEME: " + URISCHEME); + URISCHEMESPECIFIC = uri.getSchemeSpecificPart(); + logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC); + URIHOST = uri.getHost(); + URIAUTHORITY = uri.getAuthority(); + logger.info("URIAUTHORITY: " + URIAUTHORITY); + logger.info("URIHOST: " + URIHOST); + URIPATH = uri.getPath(); + logger.info("URIPATH: " + URIPATH); + URIPORT = uri.getPort(); + logger.info("URIPORT: " + URIPORT); + URIQUERY = uri.getQuery(); + logger.info("URIQUERY: " + URIQUERY); + URIFRAGMENT = uri.getFragment(); + logger.info("URIFRAGMENT: " + URIFRAGMENT); + + try { + url = uri.toURL(); + } catch (MalformedURLException e) { + logger.info("MalformedURLException thrown: " + e.getMessage()); + e.printStackTrace(); + } catch (IllegalArgumentException e) { + logger.info("IllegalArgumentException thrown: " + e.getMessage()); + e.printStackTrace(); + } + return url.toString(); + } + + public String testURIAsNew(String URIString) { + // creating URI object + try { + uri = new URI(URIString); + } catch (URISyntaxException e) { + logger.info("URISyntaxException thrown: " + e.getMessage()); + e.printStackTrace(); + throw new IllegalArgumentException(); + } + return getParsedPieces(uri); + } + + public String testURIAsCreate(String URIString) { + // creating URI object + uri = URI.create(URIString); + return getParsedPieces(uri); + } + + public static void main(String[] args) throws Exception { + URIDemo demo = new URIDemo(); + String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND); + demo.logger.info(contentCreate); + String contentNew = demo.testURIAsNew(demo.URICOMPOUND); + demo.logger.info(contentNew); + } +} diff --git a/core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java b/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java similarity index 97% rename from core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java rename to core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java index f8038a7e86..109a9951d2 100644 --- a/core-java/src/main/java/com/baeldung/javanetworking/url/URLDemo.java +++ b/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java @@ -1,9 +1,10 @@ -package com.baeldung.javanetworking.url; +package com.baeldung.javanetworking.uriurl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.net.URLConnection; diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 220b9a8ec6..21044f82c4 100644 --- a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); - public static void main(String[] args) { // TODO Auto-generated method stub diff --git a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java index 2bc078cdb0..b0c32e1487 100644 --- a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java +++ b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -44,7 +44,8 @@ public class MapIteration { } public void iterateUsingIteratorAndEntry(Map map) { - Iterator> iterator = map.entrySet().iterator(); + Iterator> iterator = map.entrySet() + .iterator(); while (iterator.hasNext()) { Map.Entry pair = iterator.next(); System.out.println(pair.getKey() + ":" + pair.getValue()); @@ -58,7 +59,9 @@ public class MapIteration { } public void iterateUsingStreamAPI(Map map) { - map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); + map.entrySet() + .stream() + .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); } public void iterateKeys(Map map) { diff --git a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java index dc509429f9..9f46345e04 100644 --- a/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java +++ b/core-java/src/main/java/com/baeldung/maths/BigIntegerImpl.java @@ -8,7 +8,7 @@ public class BigIntegerImpl { BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476"); BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476"); - + BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda); } diff --git a/core-java/src/main/java/com/baeldung/java/networking/README.md b/core-java/src/main/java/com/baeldung/networking/README.md similarity index 100% rename from core-java/src/main/java/com/baeldung/java/networking/README.md rename to core-java/src/main/java/com/baeldung/networking/README.md diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java similarity index 90% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java rename to core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java index 0d66406ac2..4f34972b1e 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; import java.util.List; @@ -9,7 +9,8 @@ public class PersistentCookieStore implements CookieStore, Runnable { public PersistentCookieStore() { store = new CookieManager().getCookieStore(); // deserialize cookies into store - Runtime.getRuntime().addShutdownHook(new Thread(this)); + Runtime.getRuntime() + .addShutdownHook(new Thread(this)); } @Override diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java similarity index 93% rename from core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java rename to core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java index 6d6371bfe0..0b5f6d7714 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java +++ b/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.cookies; +package com.baeldung.networking.cookies; import java.net.*; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java index 916442533b..35a083de26 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java similarity index 96% rename from core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java rename to core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java index 900d330786..34f2971cc4 100644 --- a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java +++ b/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import java.io.IOException; import java.net.DatagramPacket; diff --git a/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java new file mode 100644 index 0000000000..09794c2596 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java @@ -0,0 +1,85 @@ +package com.baeldung.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.stream.Collectors; + +public class BroadcastingClient { + private DatagramSocket socket; + private InetAddress address; + private int expectedServerCount; + private byte[] buf; + + public BroadcastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.address = InetAddress.getByName("255.255.255.255"); + } + + public int discoverServers(String msg) throws IOException { + initializeSocketForBroadcasting(); + copyMessageOnBuffer(msg); + + // When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value. + broadcastPacket(address); + + return receivePackets(); + } + + List listAllBroadcastAddresses() throws SocketException { + List broadcastList = new ArrayList<>(); + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + + if (networkInterface.isLoopback() || !networkInterface.isUp()) { + continue; + } + + broadcastList.addAll(networkInterface.getInterfaceAddresses() + .stream() + .filter(address -> address.getBroadcast() != null) + .map(address -> address.getBroadcast()) + .collect(Collectors.toList())); + } + return broadcastList; + } + + private void initializeSocketForBroadcasting() throws SocketException { + socket = new DatagramSocket(); + socket.setBroadcast(true); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void broadcastPacket(InetAddress address) throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java new file mode 100644 index 0000000000..b519f899bb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java @@ -0,0 +1,44 @@ +package com.baeldung.networking.udp.broadcast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class BroadcastingEchoServer extends Thread { + + protected DatagramSocket socket = null; + protected boolean running; + protected byte[] buf = new byte[256]; + + public BroadcastingEchoServer() throws IOException { + socket = new DatagramSocket(null); + socket.setReuseAddress(true); + socket.bind(new InetSocketAddress(4445)); + } + + public void run() { + running = true; + + while (running) { + try { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + running = false; + continue; + } + socket.send(packet); + } catch (IOException e) { + e.printStackTrace(); + running = false; + } + } + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java new file mode 100644 index 0000000000..9d63dd6386 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java @@ -0,0 +1,41 @@ +package com.baeldung.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +public class MulticastEchoServer extends Thread { + + protected MulticastSocket socket = null; + protected byte[] buf = new byte[256]; + protected InetAddress group = null; + + public MulticastEchoServer() throws IOException { + socket = new MulticastSocket(4446); + socket.setReuseAddress(true); + group = InetAddress.getByName("230.0.0.0"); + socket.joinGroup(group); + } + + public void run() { + try { + while (true) { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + InetAddress address = packet.getAddress(); + int port = packet.getPort(); + packet = new DatagramPacket(buf, buf.length, address, port); + String received = new String(packet.getData(), 0, packet.getLength()); + if (received.equals("end")) { + break; + } + socket.send(packet); + } + socket.leaveGroup(group); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java new file mode 100644 index 0000000000..e89abc939d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java @@ -0,0 +1,53 @@ +package com.baeldung.networking.udp.multicast; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +public class MulticastingClient { + private DatagramSocket socket; + private InetAddress group; + private int expectedServerCount; + private byte[] buf; + + public MulticastingClient(int expectedServerCount) throws Exception { + this.expectedServerCount = expectedServerCount; + this.socket = new DatagramSocket(); + this.group = InetAddress.getByName("230.0.0.0"); + } + + public int discoverServers(String msg) throws IOException { + copyMessageOnBuffer(msg); + multicastPacket(); + + return receivePackets(); + } + + private void copyMessageOnBuffer(String msg) { + buf = msg.getBytes(); + } + + private void multicastPacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446); + socket.send(packet); + } + + private int receivePackets() throws IOException { + int serversDiscovered = 0; + while (serversDiscovered != expectedServerCount) { + receivePacket(); + serversDiscovered++; + } + return serversDiscovered; + } + + private void receivePacket() throws IOException { + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive(packet); + } + + public void close() { + socket.close(); + } +} diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java b/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java new file mode 100644 index 0000000000..fbd9af2c30 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/numberofdigits/Benchmarking.java @@ -0,0 +1,131 @@ +package com.baeldung.numberofdigits; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG;; + +public class Benchmarking {; + + private static final int LOWER_BOUND = 1; + private static final int UPPER_BOUND = 999999999; + + + public static void main(String[] args) { + LOG.info("Testing all methods..."); + + long length = test_stringBasedSolution(); + LOG.info("String Based Solution : " + length); + + length = test_logarithmicApproach(); + LOG.info("Logarithmic Approach : " + length); + + length = test_repeatedMultiplication(); + LOG.info("Repeated Multiplication : " + length); + + length = test_shiftOperators(); + LOG.info("Shift Operators : " + length); + + length = test_dividingWithPowersOf2(); + LOG.info("Dividing with Powers of 2 : " + length); + + length = test_divideAndConquer(); + LOG.info("Divide And Conquer : " + length); + + } + + private static long test_stringBasedSolution() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.stringBasedSolution(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + private static long test_logarithmicApproach() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.logarithmicApproach(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + private static long test_repeatedMultiplication() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.repeatedMultiplication(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + private static long test_shiftOperators() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.shiftOperators(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + private static long test_dividingWithPowersOf2() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.dividingWithPowersOf2(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + private static long test_divideAndConquer() { + + long startTime, stopTime, elapsedTime; + startTime = System.currentTimeMillis(); + + int total = 0; + for (int i = LOWER_BOUND; i <= UPPER_BOUND; i++) { + total += NumberOfDigits.divideAndConquer(i); + } + + stopTime = System.currentTimeMillis(); + elapsedTime = stopTime - startTime; + + return elapsedTime; + } + + +} diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java new file mode 100644 index 0000000000..f455430750 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigits.java @@ -0,0 +1,97 @@ +package com.baeldung.numberofdigits; + +public class NumberOfDigits { + public static int stringBasedSolution(int number) { + int length = String.valueOf(number).length(); + return length; + } + + public static int logarithmicApproach(int number) { + int length = (int) Math.log10(number) + 1; + return length; + } + + public static int repeatedMultiplication(int number) { + int length = 0; + long temp = 1; + while(temp <= number) { + length++; + temp *= 10; + } + return length; + } + + public static int shiftOperators(int number) { + int length = 0; + long temp = 1; + while(temp <= number) { + length++; + temp = (temp << 3) + (temp << 1); + } + return length; + } + + public static int dividingWithPowersOf2(int number) { + int length = 1; + if (number >= 100000000) { + length += 8; + number /= 100000000; + } + if (number >= 10000) { + length += 4; + number /= 10000; + } + if (number >= 100) { + length += 2; + number /= 100; + } + if (number >= 10) { + length += 1; + } + return length; + } + + public static int divideAndConquer(int number) { + if (number < 100000){ + // 5 digits or less + if (number < 100){ + // 1 or 2 + if (number < 10) + return 1; + else + return 2; + }else{ + // 3 to 5 digits + if (number < 1000) + return 3; + else{ + // 4 or 5 digits + if (number < 10000) + return 4; + else + return 5; + } + } + } else { + // 6 digits or more + if (number < 10000000) { + // 6 or 7 digits + if (number < 1000000) + return 6; + else + return 7; + } else { + // 8 to 10 digits + if (number < 100000000) + return 8; + else { + // 9 or 10 digits + if (number < 1000000000) + return 9; + else + return 10; + } + } + } + } +} diff --git a/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java new file mode 100644 index 0000000000..4d76a5d677 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/numberofdigits/NumberOfDigitsDriver.java @@ -0,0 +1,27 @@ +package com.baeldung.numberofdigits; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class NumberOfDigitsDriver { + public static void main(String[] args) { + LOG.info("Testing all methods..."); + + long length = NumberOfDigits.stringBasedSolution(602); + LOG.info("String Based Solution : " + length); + + length = NumberOfDigits.logarithmicApproach(602); + LOG.info("Logarithmic Approach : " + length); + + length = NumberOfDigits.repeatedMultiplication(602); + LOG.info("Repeated Multiplication : " + length); + + length = NumberOfDigits.shiftOperators(602); + LOG.info("Shift Operators : " + length); + + length = NumberOfDigits.dividingWithPowersOf2(602); + LOG.info("Dividing with Powers of 2 : " + length); + + length = NumberOfDigits.divideAndConquer(602); + LOG.info("Divide And Conquer : " + length); + } +} diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java index 7f87b47476..11716b961d 100644 --- a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java +++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java @@ -14,7 +14,8 @@ public class Screenshot { } public void getScreenshot(int timeToWait) throws Exception { - Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit() + .getScreenSize()); Robot robot = new Robot(); BufferedImage img = robot.createScreenCapture(rectangle); ImageIO.write(img, "jpg", new File(path)); diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index cf5c253276..fa3901d5da 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -8,9 +8,8 @@ import java.net.*; public class EchoClient { - private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); - + private Socket clientSocket; private PrintWriter out; private BufferedReader in; diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java index ae00fc7cb4..d79a7c3ecb 100644 --- a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -1,6 +1,5 @@ package com.baeldung.stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/main/java/com/baeldung/string/StringHelper.java b/core-java/src/main/java/com/baeldung/string/StringHelper.java index dac0d1272e..a9cc71d36a 100644 --- a/core-java/src/main/java/com/baeldung/string/StringHelper.java +++ b/core-java/src/main/java/com/baeldung/string/StringHelper.java @@ -12,15 +12,10 @@ class StringHelper { } static String removeLastCharOptional(String s) { - return Optional.ofNullable(s) - .filter(str -> str.length() != 0) - .map(str -> str.substring(0, str.length() - 1)) - .orElse(s); + return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s); } static String removeLastCharRegexOptional(String s) { - return Optional.ofNullable(s) - .map(str -> str.replaceAll(".$", "")) - .orElse(s); + return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s); } } diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java index 130218acc2..21164a976c 100644 --- a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java +++ b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java @@ -25,11 +25,7 @@ public class MyTokenizer { } public List getTokensWithCollection(String str) { - return Collections - .list(new StringTokenizer(str, ",")) - .stream() - .map(token -> (String) token) - .collect(Collectors.toList()); + return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList()); } public List getTokensFromFile(String path, String delim) { diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java new file mode 100644 index 0000000000..5631616ea8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -0,0 +1,22 @@ +package com.baeldung.temporaladjuster; + +import java.time.DayOfWeek; +import java.time.temporal.ChronoField; +import java.time.temporal.ChronoUnit; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAdjuster; + +public class CustomTemporalAdjuster implements TemporalAdjuster { + + @Override + public Temporal adjustInto(Temporal temporal) { + switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { + case FRIDAY: + return temporal.plus(3, ChronoUnit.DAYS); + case SATURDAY: + return temporal.plus(2, ChronoUnit.DAYS); + default: + return temporal.plus(1, ChronoUnit.DAYS); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java deleted file mode 100644 index 9b43152074..0000000000 --- a/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.threadpool; - -import java.util.Set; - -import com.google.common.collect.Sets; - -public class TreeNode { - - int value; - - Set children; - - public TreeNode(int value, TreeNode... children) { - this.value = value; - this.children = Sets.newHashSet(children); - } - -} diff --git a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 23baf5d5b4..dcf186de93 100644 --- a/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -6,16 +6,16 @@ import java.security.NoSuchAlgorithmException; import java.util.UUID; public class UUIDGenerator { - + /** * These are predefined UUID for name spaces */ - private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; - private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; + private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); public static void main(String[] args) { try { @@ -35,7 +35,7 @@ public class UUIDGenerator { UUID uuid = UUID.randomUUID(); return uuid; } - + /** * Type 3 UUID Generation * @@ -47,7 +47,7 @@ public class UUIDGenerator { UUID uuid = UUID.nameUUIDFromBytes(bytes); return uuid; } - + /** * Type 5 UUID Generation * @@ -59,8 +59,7 @@ public class UUIDGenerator { UUID uuid = type5UUIDFromBytes(bytes); return uuid; } - - + public static UUID type5UUIDFromBytes(byte[] name) { MessageDigest md; try { @@ -69,27 +68,26 @@ public class UUIDGenerator { throw new InternalError("MD5 not supported", nsae); } byte[] bytes = md.digest(name); - bytes[6] &= 0x0f; /* clear version */ - bytes[6] |= 0x50; /* set to version 5 */ - bytes[8] &= 0x3f; /* clear variant */ - bytes[8] |= 0x80; /* set to IETF variant */ + bytes[6] &= 0x0f; /* clear version */ + bytes[6] |= 0x50; /* set to version 5 */ + bytes[8] &= 0x3f; /* clear variant */ + bytes[8] |= 0x80; /* set to IETF variant */ return constructType5UUID(bytes); } - + private static UUID constructType5UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; - - for (int i=0; i<8; i++) + + for (int i = 0; i < 8; i++) msb = (msb << 8) | (data[i] & 0xff); - - for (int i=8; i<16; i++) + + for (int i = 8; i < 16; i++) lsb = (lsb << 8) | (data[i] & 0xff); return new UUID(msb, lsb); } - /** * Unique Keys Generation Using Message Digest and Type 4 UUID * diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java index 1e1423f0b3..5e38eb6088 100644 --- a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java +++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java @@ -4,7 +4,7 @@ public class Rectangle extends Shape { private double width; private double length; - public Rectangle(double width, double length) { + Rectangle(double width, double length) { this.width = width; this.length = length; } diff --git a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java index 09344902b7..d291ac0d3b 100644 --- a/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java +++ b/core-java/src/main/java/org/baeldung/executable/ExecutableMavenJar.java @@ -1,11 +1,10 @@ package org.baeldung.executable; -import javax.swing.JOptionPane; +import javax.swing.*; public class ExecutableMavenJar { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1); } - } diff --git a/core-java/src/main/resources/log4jstructuraldp.properties b/core-java/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/core-java/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/DateDiffUnitTest.java b/core-java/src/test/java/com/baeldung/DateDiffUnitTest.java new file mode 100644 index 0000000000..324a0d4587 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/DateDiffUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung; + +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; + +public class DateDiffUnitTest { + + @Test + public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); + Date firstDate = sdf.parse("06/24/2017"); + Date secondDate = sdf.parse("06/30/2017"); + + long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime()); + long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { + LocalDate now = LocalDate.now(); + LocalDate sixDaysBehind = now.minusDays(6); + + Duration duration = Duration.between(now, sixDaysBehind); + long diff = Math.abs(duration.toDays()); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime sixMinutesBehind = now.minusMinutes(6); + + Duration duration = Duration.between(now, sixMinutesBehind); + long diff = Math.abs(duration.toMinutes()); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { + org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); + org.joda.time.LocalDate sixDaysBehind = now.minusDays(6); + + org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind); + long diff = Math.abs(period.getDays()); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDateTimesInJodaTime_whenDifferentiating_thenWeGetSix() { + org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now(); + org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6); + + org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind); + long diff = Math.abs(period.getDays()); + } + + @Test + public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() { + hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault()); + hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6); + + long diff = Math.abs(now.numDaysFrom(sixDaysBehind)); + + assertEquals(diff, 6); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index a10ec66f20..e7a76d1ab9 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest { @Test public void givenString_whenUsingParse_thenLocalDateTime() { - assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); - assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); + assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalDate()); + assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") + .toLocalTime()); } } diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index e158c0fd67..90e858f9ac 100644 --- a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -15,12 +15,14 @@ public class UseLocalDateUnitTest { @Test public void givenValues_whenUsingFactoryOf_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10).toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) + .toString()); } @Test public void givenString_whenUsingParse_thenLocalDate() { - assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString()); + assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") + .toString()); } @Test @@ -30,12 +32,14 @@ public class UseLocalDateUnitTest { @Test public void givenDate_whenUsingPlus_thenNextDay() { - assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); + assertEquals(LocalDate.now() + .plusDays(1), useLocalDate.getNextDay(LocalDate.now())); } @Test public void givenDate_whenUsingMinus_thenPreviousDay() { - assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); + assertEquals(LocalDate.now() + .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); } @Test @@ -45,7 +49,8 @@ public class UseLocalDateUnitTest { @Test public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { - assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); + assertEquals(1, useLocalDate.getFirstDayOfMonth() + .getDayOfMonth()); } @Test diff --git a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java index 887e7e41da..d7c1ee17d4 100644 --- a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java @@ -12,7 +12,7 @@ import org.junit.Test; public class DeserializationUnitTest { - private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA"; private static long userDefinedSerialVersionUID = 1234567L; @@ -25,20 +25,22 @@ public class DeserializationUnitTest { public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException { assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - + AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; - + macBook.lightningPort = "lightningPort2020"; + // serializes the "AppleProduct" object String serializedProduct = SerializationUtility.serializeObjectToString(macBook); // deserializes the "AppleProduct" object AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct); - + assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort)); assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort)); - + assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort)); + } /** @@ -59,7 +61,6 @@ public class DeserializationUnitTest { public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException { assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - // attempts to deserialize the "AppleProduct" object DeserializationUtility.deSerializeObjectFromString(serializedObj); } diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java new file mode 100644 index 0000000000..fb483a8a68 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns; + + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; + +public class AdapterPatternIntegrationTest { + @Test + public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); + assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); + assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java new file mode 100644 index 0000000000..56a7a704f2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.bridge.Blue; +import com.baeldung.designpatterns.bridge.Red; +import com.baeldung.designpatterns.bridge.Shape; +import com.baeldung.designpatterns.bridge.Square; +import com.baeldung.designpatterns.bridge.Triangle; + +public class BridgePatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void whenBridgePatternInvoked_thenConfigSuccess() { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Square drawn. ")); + assertThat((String) log.get(1).getMessage(), is("Color : Red")); + assertThat((String) log.get(2).getMessage(), is("Triangle drawn. ")); + assertThat((String) log.get(3).getMessage(), is("Color : Blue")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java new file mode 100644 index 0000000000..b3b3f988f1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.designpatterns.decorator.BubbleLights; +import com.baeldung.designpatterns.decorator.ChristmasTree; +import com.baeldung.designpatterns.decorator.ChristmasTreeImpl; +import com.baeldung.designpatterns.decorator.Garland; + +public class DecoratorPatternIntegrationTest { + private ChristmasTree tree; + + @Test + public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() { + //christmas tree with just one Garland + tree = new Garland(new ChristmasTreeImpl()); + assertEquals(tree.decorate(), "Christmas tree with Garland"); + + //christmas tree with two Garlands and one Bubble lights + tree = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights"); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java new file mode 100644 index 0000000000..7fa95b31d7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.proxy.ExpensiveObject; +import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy; + +public class ProxyPatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Loading initial configuration...")); + assertThat((String) log.get(1).getMessage(), is("processing complete.")); + assertThat((String) log.get(2).getMessage(), is("processing complete.")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java new file mode 100644 index 0000000000..613c26fa13 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java @@ -0,0 +1,29 @@ +package com.baeldung.designpatterns; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class TestAppenderDP extends AppenderSkeleton { + private final List log = new ArrayList(); + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(final LoggingEvent loggingEvent) { + log.add(loggingEvent); + } + + @Override + public void close() { + } + + public List getLog() { + return new ArrayList(log); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java index 811088cc0c..e91cbfcb75 100644 --- a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java +++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java @@ -21,7 +21,6 @@ public class FunctionalInterfaceUnitTest { private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); - @Test public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { Map nameMap = new HashMap<>(); @@ -83,7 +82,8 @@ public class FunctionalInterfaceUnitTest { return result; }); - List fibonacci5 = fibonacci.limit(5).collect(Collectors.toList()); + List fibonacci5 = fibonacci.limit(5) + .collect(Collectors.toList()); assertEquals(new Integer(1), fibonacci5.get(0)); assertEquals(new Integer(1), fibonacci5.get(1)); @@ -112,7 +112,9 @@ public class FunctionalInterfaceUnitTest { public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() { List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David"); - List namesWithA = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList()); + List namesWithA = names.stream() + .filter(name -> name.startsWith("A")) + .collect(Collectors.toList()); assertEquals(2, namesWithA.size()); assertTrue(namesWithA.contains("Angela")); @@ -135,7 +137,8 @@ public class FunctionalInterfaceUnitTest { List values = Arrays.asList(3, 5, 8, 9, 12); - int sum = values.stream().reduce(0, (i1, i2) -> i1 + i2); + int sum = values.stream() + .reduce(0, (i1, i2) -> i1 + i2); assertEquals(37, sum); diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java new file mode 100644 index 0000000000..60950fae7a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.hashcode.application; + +import com.baeldung.hashcode.entities.User; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; + +public class ApplicationTest { + + @Test + public void main_NoInputState_TextPrintedToConsole() throws Exception { + Map users = new HashMap<>(); + User user1 = new User(1L, "John", "john@domain.com"); + User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); + User user3 = new User(3L, "Mary", "mary@domain.com"); + + users.put(user1, user1); + users.put(user2, user2); + users.put(user3, user3); + + assertTrue(users.containsKey(user1)); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java new file mode 100644 index 0000000000..e356b4beef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -0,0 +1,34 @@ +package com.baeldung.hashcode.entities; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class UserTest { + + private User user; + private User comparisonUser; + + @Before + public void setUpUserInstances() { + this.user = new User(1L, "test", "test@domain.com"); + this.comparisonUser = this.user; + } + + @After + public void tearDownUserInstances() { + user = null; + comparisonUser = null; + } + + @Test + public void equals_EqualUserInstance_TrueAssertion() { + Assert.assertTrue(user.equals(comparisonUser)); + } + + @Test + public void hashCode_UserHash_TrueAssertion() { + Assert.assertEquals(1792276941, user.hashCode()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java index 4452b4db9a..eea019da2c 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -13,35 +13,26 @@ import static org.junit.Assert.*; public class Java8GroupingByCollectorUnitTest { - private static final List posts = Arrays.asList( - new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), - new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), - new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), - new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), - new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); + private static final List posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), + new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); @Test public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType)); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { - Map postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); + Map postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS)); assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE)); @@ -50,174 +41,135 @@ public class Java8GroupingByCollectorUnitTest { @Test public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { - Map likesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); + Map likesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); - assertEquals(50, likesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.REVIEW) - .intValue()); - assertEquals(20, likesPerType - .get(BlogPostType.GUIDE) - .intValue()); + assertEquals(50, likesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.REVIEW) + .intValue()); + assertEquals(20, likesPerType.get(BlogPostType.GUIDE) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { - EnumMap> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); + EnumMap> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { - Map> postsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, toSet())); + Map> postsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, toSet())); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { - ConcurrentMap> postsPerType = posts - .parallelStream() - .collect(groupingByConcurrent(BlogPost::getType)); + ConcurrentMap> postsPerType = posts.parallelStream() + .collect(groupingByConcurrent(BlogPost::getType)); - assertEquals(2, postsPerType - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, postsPerType - .get(BlogPostType.GUIDE) - .size()); - assertEquals(2, postsPerType - .get(BlogPostType.REVIEW) - .size()); + assertEquals(2, postsPerType.get(BlogPostType.NEWS) + .size()); + assertEquals(1, postsPerType.get(BlogPostType.GUIDE) + .size()); + assertEquals(2, postsPerType.get(BlogPostType.REVIEW) + .size()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { - Map averageLikesPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); + Map averageLikesPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); - assertEquals(25, averageLikesPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(20, averageLikesPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(10, averageLikesPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { - Map numberOfPostsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, counting())); + Map numberOfPostsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, counting())); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.NEWS) - .intValue()); - assertEquals(1, numberOfPostsPerType - .get(BlogPostType.GUIDE) - .intValue()); - assertEquals(2, numberOfPostsPerType - .get(BlogPostType.REVIEW) - .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS) + .intValue()); + assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE) + .intValue()); + assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW) + .intValue()); } @Test public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { - Map> maxLikesPerPostType = posts - .stream() - .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); + Map> maxLikesPerPostType = posts.stream() + .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); - assertTrue(maxLikesPerPostType - .get(BlogPostType.NEWS) - .isPresent()); - assertEquals(35, maxLikesPerPostType - .get(BlogPostType.NEWS) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS) + .isPresent()); + assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.GUIDE) - .isPresent()); - assertEquals(20, maxLikesPerPostType - .get(BlogPostType.GUIDE) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE) + .isPresent()); + assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE) + .get() + .getLikes()); - assertTrue(maxLikesPerPostType - .get(BlogPostType.REVIEW) - .isPresent()); - assertEquals(15, maxLikesPerPostType - .get(BlogPostType.REVIEW) - .get() - .getLikes()); + assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW) + .isPresent()); + assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW) + .get() + .getLikes()); } @Test public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { - Map>> map = posts - .stream() - .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); + Map>> map = posts.stream() + .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.GUIDE) - .size()); - assertEquals(1, map - .get("Author 1") - .get(BlogPostType.REVIEW) - .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.GUIDE) + .size()); + assertEquals(1, map.get("Author 1") + .get(BlogPostType.REVIEW) + .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.NEWS) - .size()); - assertEquals(1, map - .get("Author 2") - .get(BlogPostType.REVIEW) - .size()); - assertNull(map - .get("Author 2") - .get(BlogPostType.GUIDE)); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.NEWS) + .size()); + assertEquals(1, map.get("Author 2") + .get(BlogPostType.REVIEW) + .size()); + assertNull(map.get("Author 2") + .get(BlogPostType.GUIDE)); } @Test public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { - Map likeStatisticsPerType = posts - .stream() - .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); + Map likeStatisticsPerType = posts.stream() + .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS); diff --git a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java index 7098f88f30..a0bd1cf093 100644 --- a/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java +++ b/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java @@ -17,8 +17,8 @@ public class Java8MapAndFlatMap { @Test public void givenStream_whenCalledMap_thenProduceList() { List myList = Stream.of("a", "b") - .map(String::toUpperCase) - .collect(Collectors.toList()); + .map(String::toUpperCase) + .collect(Collectors.toList()); assertEquals(asList("A", "B"), myList); } @@ -27,9 +27,9 @@ public class Java8MapAndFlatMap { List> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b")); System.out.println(list); - System.out.println(list - .stream().flatMap(Collection::stream) - .collect(Collectors.toList())); + System.out.println(list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList())); } @Test @@ -40,13 +40,11 @@ public class Java8MapAndFlatMap { @Test public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() { - assertEquals(Optional.of(Optional.of("STRING")), Optional - .of("string") - .map(s -> Optional.of("STRING"))); + assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") + .map(s -> Optional.of("STRING"))); - assertEquals(Optional.of("STRING"), Optional - .of("string") - .flatMap(s -> Optional.of("STRING"))); + assertEquals(Optional.of("STRING"), Optional.of("string") + .flatMap(s -> Optional.of("STRING"))); } } diff --git a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java index 1f3b380772..7f83e379cd 100644 --- a/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java @@ -55,7 +55,12 @@ public class JavaFolderSizeUnitTest { @Test public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException { final Path folder = Paths.get(path); - final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum(); + final long size = Files.walk(folder) + .filter(p -> p.toFile() + .isFile()) + .mapToLong(p -> p.toFile() + .length()) + .sum(); assertEquals(EXPECTED_SIZE, size); } @@ -72,8 +77,12 @@ public class JavaFolderSizeUnitTest { public void whenGetFolderSizeUsingGuava_thenCorrect() { final File folder = new File(path); - final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum(); + final Iterable files = com.google.common.io.Files.fileTreeTraverser() + .breadthFirstTraversal(folder); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length) + .sum(); assertEquals(EXPECTED_SIZE, size); } diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java index 26536ba705..1cac428285 100644 --- a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java @@ -1,4 +1,5 @@ package com.baeldung.java8.comparator; + import java.util.Arrays; import java.util.Comparator; @@ -25,44 +26,32 @@ public class Java8ComparatorUnitTest { @Before public void initData() { - employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), - new Employee("Keith", 35, 4000, 3924401) }; - employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), - null, new Employee("Keith", 35, 4000, 3924401) }; + employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) }; + employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), - new Employee("Ace", 22, 2000, 5924001) }; + sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) }; - sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), }; + sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), }; - sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), - new Employee("Keith", 35, 4000, 3924401), }; + sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), }; - sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), - new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; + sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null }; - someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), - new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; + someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; - sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), - new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; + sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) }; } @Test public void whenComparing_thenSortedByName() { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -72,16 +61,16 @@ public class Java8ComparatorUnitTest { return s2.compareTo(s1); }); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } - + @Test public void whenReversed_thenSortedByNameDesc() { - Comparator employeeNameComparator = Comparator.comparing(Employee::getName); - Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); + Comparator employeeNameComparator = Comparator.comparing(Employee::getName); + Comparator employeeNameComparatorReversed = employeeNameComparator.reversed(); Arrays.sort(employees, employeeNameComparatorReversed); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -89,7 +78,7 @@ public class Java8ComparatorUnitTest { public void whenComparingInt_thenSortedByAge() { Comparator employeeAgeComparator = Comparator.comparingInt(Employee::getAge); Arrays.sort(employees, employeeAgeComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByAge)); } @@ -97,7 +86,7 @@ public class Java8ComparatorUnitTest { public void whenComparingLong_thenSortedByMobile() { Comparator employeeMobileComparator = Comparator.comparingLong(Employee::getMobile); Arrays.sort(employees, employeeMobileComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByMobile)); } @@ -105,7 +94,7 @@ public class Java8ComparatorUnitTest { public void whenComparingDouble_thenSortedBySalary() { Comparator employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary); Arrays.sort(employees, employeeSalaryComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesBySalary)); } @@ -113,7 +102,7 @@ public class Java8ComparatorUnitTest { public void whenNaturalOrder_thenSortedByName() { Comparator employeeNameComparator = Comparator. naturalOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByName)); } @@ -121,7 +110,7 @@ public class Java8ComparatorUnitTest { public void whenReverseOrder_thenSortedByNameDesc() { Comparator employeeNameComparator = Comparator. reverseOrder(); Arrays.sort(employees, employeeNameComparator); -// System.out.println(Arrays.toString(employees)); + // System.out.println(Arrays.toString(employees)); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } @@ -130,7 +119,7 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst)); } @@ -139,27 +128,28 @@ public class Java8ComparatorUnitTest { Comparator employeeNameComparator = Comparator.comparing(Employee::getName); Comparator employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast); -// System.out.println(Arrays.toString(employeesArrayWithNulls)); + // System.out.println(Arrays.toString(employeesArrayWithNulls)); assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast)); } @Test public void whenThenComparing_thenSortedByAgeName() { - Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName); + Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge) + .thenComparing(Employee::getName); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName)); } @Test public void whenThenComparing_thenSortedByNameAge() { - Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge); + Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName) + .thenComparingInt(Employee::getAge); Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator); -// System.out.println(Arrays.toString(someMoreEmployees)); + // System.out.println(Arrays.toString(someMoreEmployees)); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge)); } - } diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java index 0fd6f7dfe8..fe10266043 100644 --- a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java @@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest { private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class); - private List integers; @Before diff --git a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index 0085de6327..4cb2551fae 100644 --- a/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -17,7 +17,6 @@ public class OptionalUnitTest { private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class); - // creating Optional @Test public void whenCreatesEmptyOptional_thenCorrect() { @@ -94,9 +93,11 @@ public class OptionalUnitTest { public void whenOptionalFilterWorks_thenCorrect() { Integer year = 2016; Optional yearOptional = Optional.of(year); - boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent(); + boolean is2016 = yearOptional.filter(y -> y == 2016) + .isPresent(); assertTrue(is2016); - boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent(); + boolean is2017 = yearOptional.filter(y -> y == 2017) + .isPresent(); assertFalse(is2017); } @@ -128,7 +129,11 @@ public class OptionalUnitTest { } public boolean priceIsInRange2(Modem modem2) { - return Optional.ofNullable(modem2).map(Modem::getPrice).filter(p -> p >= 10).filter(p -> p <= 15).isPresent(); + return Optional.ofNullable(modem2) + .map(Modem::getPrice) + .filter(p -> p >= 10) + .filter(p -> p <= 15) + .isPresent(); } // Transforming Value With map() @@ -137,7 +142,8 @@ public class OptionalUnitTest { List companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple"); Optional> listOptional = Optional.of(companyNames); - int size = listOptional.map(List::size).orElse(0); + int size = listOptional.map(List::size) + .orElse(0); assertEquals(6, size); } @@ -146,7 +152,8 @@ public class OptionalUnitTest { String name = "baeldung"; Optional nameOptional = Optional.of(name); - int len = nameOptional.map(String::length).orElse(0); + int len = nameOptional.map(String::length) + .orElse(0); assertEquals(8, len); } @@ -154,10 +161,13 @@ public class OptionalUnitTest { public void givenOptional_whenMapWorksWithFilter_thenCorrect() { String password = " password "; Optional passOpt = Optional.of(password); - boolean correctPassword = passOpt.filter(pass -> pass.equals("password")).isPresent(); + boolean correctPassword = passOpt.filter(pass -> pass.equals("password")) + .isPresent(); assertFalse(correctPassword); - correctPassword = passOpt.map(String::trim).filter(pass -> pass.equals("password")).isPresent(); + correctPassword = passOpt.map(String::trim) + .filter(pass -> pass.equals("password")) + .isPresent(); assertTrue(correctPassword); } @@ -172,7 +182,8 @@ public class OptionalUnitTest { String name1 = nameOptional.orElseThrow(IllegalArgumentException::new); assertEquals("john", name1); - String name = personOptional.flatMap(Person::getName).orElseThrow(IllegalArgumentException::new); + String name = personOptional.flatMap(Person::getName) + .orElseThrow(IllegalArgumentException::new); assertEquals("john", name); } @@ -182,7 +193,9 @@ public class OptionalUnitTest { person.setPassword("password"); Optional personOptional = Optional.of(person); - String password = personOptional.flatMap(Person::getPassword).filter(cleanPass -> cleanPass.equals("password")).orElseThrow(IllegalArgumentException::new); + String password = personOptional.flatMap(Person::getPassword) + .filter(cleanPass -> cleanPass.equals("password")) + .orElseThrow(IllegalArgumentException::new); assertEquals("password", password); } @@ -190,7 +203,8 @@ public class OptionalUnitTest { @Test public void whenOrElseWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElse("john"); + String name = Optional.ofNullable(nullName) + .orElse("john"); assertEquals("john", name); } @@ -198,7 +212,8 @@ public class OptionalUnitTest { @Test public void whenOrElseGetWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseGet(() -> "john"); + String name = Optional.ofNullable(nullName) + .orElseGet(() -> "john"); assertEquals("john", name); } @@ -207,11 +222,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseOverlap_thenCorrect() { String text = null; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Default Value", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Default Value", defaultText); } @@ -219,11 +236,13 @@ public class OptionalUnitTest { public void whenOrElseGetAndOrElseDiffer_thenCorrect() { String text = "Text present"; LOG.debug("Using orElseGet:"); - String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); + String defaultText = Optional.ofNullable(text) + .orElseGet(this::getMyDefault); assertEquals("Text present", defaultText); LOG.debug("Using orElse:"); - defaultText = Optional.ofNullable(text).orElse(getMyDefault()); + defaultText = Optional.ofNullable(text) + .orElse(getMyDefault()); assertEquals("Text present", defaultText); } @@ -231,7 +250,8 @@ public class OptionalUnitTest { @Test(expected = IllegalArgumentException.class) public void whenOrElseThrowWorks_thenCorrect() { String nullName = null; - String name = Optional.ofNullable(nullName).orElseThrow(IllegalArgumentException::new); + String name = Optional.ofNullable(nullName) + .orElseThrow(IllegalArgumentException::new); } public String getMyDefault() { diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java new file mode 100644 index 0000000000..ed36951f73 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.javanetworking.uriurl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.apache.commons.io.IOUtils; +import static org.junit.Assert.*; +import org.junit.Test; + +public class URIvsURLUnitTest { + + @Test + public void whenCreatingURIs_thenSameInfo() throws URISyntaxException { + URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment"); + URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment"); + + assertEquals(firstURI.getScheme(), secondURI.getScheme()); + assertEquals(firstURI.getPath(), secondURI.getPath()); + } + + @Test + public void whenCreatingURLs_thenSameInfo() throws MalformedURLException { + URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment"); + URL secondURL = new URL("http", "somehost", 80, "/path/to/file"); + + assertEquals(firstURL.getHost(), secondURL.getHost()); + assertEquals(firstURL.getPath(), secondURL.getPath()); + } + + @Test + public void whenCreatingURI_thenCorrect() { + URI uri = URI.create("urn:isbn:1234567890"); + + assertNotNull(uri); + } + + @Test(expected = MalformedURLException.class) + public void whenCreatingURLs_thenException() throws MalformedURLException { + URL theURL = new URL("otherprotocol://somehost/path/to/file"); + + assertNotNull(theURL); + } + + @Test + public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException { + String aURIString = "http://somehost:80/path?thequery"; + URI uri = new URI(aURIString); + URL url = new URL(aURIString); + + URL toURL = uri.toURL(); + URI toURI = url.toURI(); + + assertNotNull(url); + assertNotNull(uri); + assertEquals(toURL.toString(), toURI.toString()); + } + + @Test(expected = MalformedURLException.class) + public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException { + URI uri = new URI("somescheme://someauthority/path?thequery"); + + URL url = uri.toURL(); + + assertNotNull(url); + } + + @Test + public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException { + URL url = new URL("http://courses.baeldung.com"); + + String contents = IOUtils.toString(url.openStream()); + + assertTrue(contents.contains("")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java new file mode 100644 index 0000000000..c429039e3d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java @@ -0,0 +1,65 @@ +package com.baeldung.javanetworking.uriurl.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.javanetworking.uriurl.URLDemo; + +@FixMethodOrder +public class URIDemoTest { + private final Logger log = LoggerFactory.getLogger(URIDemoTest.class); + String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; + // parsed locator + static String URISCHEME = "https"; + String URISCHEMESPECIFIC; + static String URIHOST = "wordpress.org"; + static String URIAUTHORITY = "wordpress.org:443"; + + static String URIPATH = "/support/topic/page-jumps-within-wordpress/"; + int URIPORT = 443; + static int URIDEFAULTPORT = 443; + static String URIQUERY = "replies=3"; + static String URIFRAGMENT = "post-2278484"; + static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT; + + static URI uri; + URL url; + BufferedReader in = null; + String URIContent = ""; + + @BeforeClass + public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException { + uri = new URI(URICOMPOUND); + } + + // check parsed URL + @Test + public void givenURI_whenURIIsParsed_thenSuccess() { + assertNotNull("URI is null", uri); + assertEquals("URI string is not equal", uri.toString(), URISTRING); + assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME); + assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY); + assertEquals("Host string is not equal", uri.getHost(), URIHOST); + assertEquals("Path string is not equal", uri.getPath(), URIPATH); + assertEquals("Port number is not equal", uri.getPort(), URIPORT); + assertEquals("Query string is not equal", uri.getQuery(), URIQUERY); + assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT); + } +} diff --git a/core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java rename to core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java index 293052e842..47cbf539a5 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/url/test/URLDemoTest.java +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.url.test; +package com.baeldung.javanetworking.uriurl.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -18,11 +18,11 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.baeldung.javanetworking.url.URLDemo; +import com.baeldung.javanetworking.uriurl.URLDemo; @FixMethodOrder public class URLDemoTest { - private final Logger log = LoggerFactory.getLogger(URLDemo.class); + private final Logger log = LoggerFactory.getLogger(URLDemoTest.class); static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; // parsed locator static String URLPROTOCOL = "https"; diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java index 3c8f519082..543c680597 100644 --- a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java @@ -43,6 +43,8 @@ public class FlattenNestedListUnitTest { } private List flattenListOfListsStream(List> list) { - return list.stream().flatMap(Collection::stream).collect(Collectors.toList()); + return list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); } } diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java index 7a23afa12f..5327e5f4f0 100644 --- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java @@ -29,12 +29,9 @@ public class ListOfListsUnitTest { @Test public void givenListOfLists_thenCheckNames() { - assertEquals("Pen 1", ((Pen) listOfLists.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) listOfLists.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName()); } @SuppressWarnings("unchecked") @@ -43,11 +40,9 @@ public class ListOfListsUnitTest { ((ArrayList) listOfLists.get(1)).remove(0); listOfLists.remove(1); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(1) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName()); listOfLists.remove(0); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(0) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName()); } @Test @@ -67,11 +62,8 @@ public class ListOfListsUnitTest { list.add(pencils); list.add(rubbers); - assertEquals("Pen 1", ((Pen) list.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) list.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) list.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName()); } } diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java index 3c2d9904d4..0a0993a0d7 100644 --- a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java +++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java @@ -63,6 +63,6 @@ public class MappedByteBufferUnitTest { private Path getFileURIFromResources(String fileName) throws Exception { ClassLoader classLoader = getClass().getClassLoader(); - return Paths.get(classLoader.getResource(fileName).getPath()); + return Paths.get(classLoader.getResource(fileName).toURI()); } } diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java rename to core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index 8948d1ebf7..fe2747bcee 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -1,190 +1,190 @@ -package com.baeldung.money; - -import org.javamoney.moneta.FastMoney; -import org.javamoney.moneta.Money; -import org.javamoney.moneta.format.CurrencyStyle; -import org.junit.Ignore; -import org.junit.Test; - -import javax.money.CurrencyUnit; -import javax.money.Monetary; -import javax.money.MonetaryAmount; -import javax.money.UnknownCurrencyException; -import javax.money.convert.CurrencyConversion; -import javax.money.convert.MonetaryConversions; -import javax.money.format.AmountFormatQueryBuilder; -import javax.money.format.MonetaryAmountFormat; -import javax.money.format.MonetaryFormats; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class JavaMoneyUnitTest { - - @Test - public void givenCurrencyCode_whenString_thanExist() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - assertNotNull(usd); - assertEquals(usd.getCurrencyCode(), "USD"); - assertEquals(usd.getNumericCode(), 840); - assertEquals(usd.getDefaultFractionDigits(), 2); - } - - @Test(expected = UnknownCurrencyException.class) - public void givenCurrencyCode_whenNoExist_thanThrowsError() { - Monetary.getCurrency("AAA"); - } - - @Test - public void givenAmounts_whenStringified_thanEquals() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200) - .create(); - Money moneyof = Money.of(12, usd); - FastMoney fastmoneyof = FastMoney.of(2, usd); - - assertEquals("USD", usd.toString()); - assertEquals("USD 200", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD 2.00000", fastmoneyof.toString()); - } - - @Test - public void givenCurrencies_whenCompared_thanNotequal() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money oneEuro = Money.of(1, "EUR"); - - assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); - assertTrue(oneDolar.equals(Money.of(1, "USD"))); - } - - @Test(expected = ArithmeticException.class) - public void givenAmount_whenDivided_thanThrowsException() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - oneDolar.divide(3); - fail(); // if no exception - } - - @Test - public void givenAmounts_whenSummed_thanCorrect() { - List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); - - Money sumAmtCHF = (Money) monetaryAmounts - .stream() - .reduce(Money.of(0, "CHF"), MonetaryAmount::add); - - assertEquals("CHF 111.35", sumAmtCHF.toString()); - } - - @Test - public void givenArithmetic_whenStringified_thanEqualsAmount() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - Money moneyof = Money.of(12, usd); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200.50) - .create(); - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money subtractedAmount = Money - .of(1, "USD") - .subtract(fstAmtUSD); - MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); - MonetaryAmount divideAmount = oneDolar.divide(0.25); - - assertEquals("USD", usd.toString()); - assertEquals("USD 1", oneDolar.toString()); - assertEquals("USD 200.5", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD -199.5", subtractedAmount.toString()); - assertEquals("USD 0.25", multiplyAmount.toString()); - assertEquals("USD 4", divideAmount.toString()); - } - - @Test - public void givenAmount_whenRounded_thanEquals() { - MonetaryAmount fstAmtEUR = Monetary - .getDefaultAmountFactory() - .setCurrency("EUR") - .setNumber(1.30473908) - .create(); - MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); - assertEquals("EUR 1.30473908", fstAmtEUR.toString()); - assertEquals("EUR 1.3", roundEUR.toString()); - } - - @Test - @Ignore("Currency providers are not always available") - public void givenAmount_whenConversion_thenNotNull() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); - - MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(convertedAmountUSDtoEUR); - } - - @Test - public void givenLocale_whenFormatted_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); - String usFormatted = formatUSD.format(oneDollar); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(formatUSD); - assertEquals("USD1.00", usFormatted); - } - - @Test - public void givenAmount_whenCustomFormat_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder - .of(Locale.US) - .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 ¤") - .build()); - String customFormatted = customFormat.format(oneDollar); - - assertNotNull(customFormat); - assertEquals("USD 1", oneDollar.toString()); - assertEquals("00001.00 US Dollar", customFormatted); - } -} +package com.baeldung.money; + +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.javamoney.moneta.format.CurrencyStyle; +import org.junit.Ignore; +import org.junit.Test; + +import javax.money.CurrencyUnit; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.money.UnknownCurrencyException; +import javax.money.convert.CurrencyConversion; +import javax.money.convert.MonetaryConversions; +import javax.money.format.AmountFormatQueryBuilder; +import javax.money.format.MonetaryAmountFormat; +import javax.money.format.MonetaryFormats; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class JavaMoneyUnitManualTest { + + @Test + public void givenCurrencyCode_whenString_thanExist() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + assertNotNull(usd); + assertEquals(usd.getCurrencyCode(), "USD"); + assertEquals(usd.getNumericCode(), 840); + assertEquals(usd.getDefaultFractionDigits(), 2); + } + + @Test(expected = UnknownCurrencyException.class) + public void givenCurrencyCode_whenNoExist_thanThrowsError() { + Monetary.getCurrency("AAA"); + } + + @Test + public void givenAmounts_whenStringified_thanEquals() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200) + .create(); + Money moneyof = Money.of(12, usd); + FastMoney fastmoneyof = FastMoney.of(2, usd); + + assertEquals("USD", usd.toString()); + assertEquals("USD 200", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD 2.00000", fastmoneyof.toString()); + } + + @Test + public void givenCurrencies_whenCompared_thanNotequal() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money oneEuro = Money.of(1, "EUR"); + + assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); + assertTrue(oneDolar.equals(Money.of(1, "USD"))); + } + + @Test(expected = ArithmeticException.class) + public void givenAmount_whenDivided_thanThrowsException() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + oneDolar.divide(3); + fail(); // if no exception + } + + @Test + public void givenAmounts_whenSummed_thanCorrect() { + List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); + + Money sumAmtCHF = (Money) monetaryAmounts + .stream() + .reduce(Money.of(0, "CHF"), MonetaryAmount::add); + + assertEquals("CHF 111.35", sumAmtCHF.toString()); + } + + @Test + public void givenArithmetic_whenStringified_thanEqualsAmount() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + Money moneyof = Money.of(12, usd); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200.50) + .create(); + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money subtractedAmount = Money + .of(1, "USD") + .subtract(fstAmtUSD); + MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); + MonetaryAmount divideAmount = oneDolar.divide(0.25); + + assertEquals("USD", usd.toString()); + assertEquals("USD 1", oneDolar.toString()); + assertEquals("USD 200.5", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD -199.5", subtractedAmount.toString()); + assertEquals("USD 0.25", multiplyAmount.toString()); + assertEquals("USD 4", divideAmount.toString()); + } + + @Test + public void givenAmount_whenRounded_thanEquals() { + MonetaryAmount fstAmtEUR = Monetary + .getDefaultAmountFactory() + .setCurrency("EUR") + .setNumber(1.30473908) + .create(); + MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); + assertEquals("EUR 1.30473908", fstAmtEUR.toString()); + assertEquals("EUR 1.3", roundEUR.toString()); + } + + @Test + @Ignore("Currency providers are not always available") + public void givenAmount_whenConversion_thenNotNull() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); + + MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(convertedAmountUSDtoEUR); + } + + @Test + public void givenLocale_whenFormatted_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); + String usFormatted = formatUSD.format(oneDollar); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(formatUSD); + assertEquals("USD1.00", usFormatted); + } + + @Test + public void givenAmount_whenCustomFormat_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder + .of(Locale.US) + .set(CurrencyStyle.NAME) + .set("pattern", "00000.00 �") + .build()); + String customFormatted = customFormat.format(oneDollar); + + assertNotNull(customFormat); + assertEquals("USD 1", oneDollar.toString()); + assertEquals("00001.00 US Dollar", customFormatted); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java rename to core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java index aff851ae4b..968c01d24e 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/networking/udp/UDPIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.udp; +package com.baeldung.networking.udp; import org.junit.After; import org.junit.Before; diff --git a/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java new file mode 100644 index 0000000000..c4f1e1f42c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.networking.udp.broadcast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class BroadcastIntegrationTest { + private BroadcastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new BroadcastingEchoServer().start(); + } + + client = new BroadcastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java new file mode 100644 index 0000000000..404f6c4e85 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.networking.udp.multicast; + +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class MulticastIntegrationTest { + private MulticastingClient client; + + @Test + public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception { + int expectedServers = 4; + initializeForExpectedServers(expectedServers); + + int serversDiscovered = client.discoverServers("hello server"); + assertEquals(expectedServers, serversDiscovered); + } + + private void initializeForExpectedServers(int expectedServers) throws Exception { + for (int i = 0; i < expectedServers; i++) { + new MulticastEchoServer().start(); + } + + client = new MulticastingClient(expectedServers); + } + + @After + public void tearDown() throws IOException { + stopEchoServer(); + client.close(); + } + + private void stopEchoServer() throws IOException { + client.discoverServers("end"); + } +} diff --git a/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java b/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java new file mode 100644 index 0000000000..01b874622e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/numberofdigits/NumberOfDigitsIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.numberofdigits; + +import org.junit.Assert; +import org.junit.Assume; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +@RunWith(Theories.class) +public class NumberOfDigitsIntegrationTest { + + @DataPoints + public static int[][] lowestIntegers() + { + return new int[][]{ + {1, 1}, + {2, 10}, + {3, 100}, + {4, 1000}, + {5, 10000}, + {6, 100000}, + {7, 1000000}, + {8, 10000000}, + {9, 100000000}, + {10, 1000000000} + }; + } + + @DataPoints + public static int[][] highestIntegers() + { + return new int[][]{ + {1, 9}, + {2, 99}, + {3, 999}, + {4, 9999}, + {5, 99999}, + {6, 999999}, + {7, 9999999}, + {8, 99999999}, + {9, 999999999}, + {10, Integer.MAX_VALUE} + }; + } + + @DataPoints + public static int[][] randomIntegers() + { + return new int[][]{ + {1, 1}, + {2, 14}, + {3, 549}, + {4, 1136}, + {5, 25340}, + {6, 134321}, + {7, 1435432}, + {8, 54234129}, + {9, 113683912}, + {10, 1534031982} + }; + } + + @Theory + public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.stringBasedSolution(entry[1])); + } + + @Theory + public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.logarithmicApproach(entry[1])); + } + + @Theory + public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.repeatedMultiplication(entry[1])); + } + + @Theory + public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.shiftOperators(entry[1])); + } + + @Theory + public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.dividingWithPowersOf2(entry[1])); + } + + @Theory + public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) { + Assume.assumeTrue(entry[0] > 0 && entry[1] > 0); + Assert.assertEquals(entry[0], NumberOfDigits.divideAndConquer(entry[1])); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java index 2bf6d142bb..70c6e88c49 100644 --- a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java @@ -14,7 +14,8 @@ public class EchoIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new EchoServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java index 06b37d8539..4367ed26a2 100644 --- a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java @@ -17,7 +17,8 @@ public class GreetServerIntegrationTest { @BeforeClass public static void start() throws InterruptedException { - Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT)); + Executors.newSingleThreadExecutor() + .submit(() -> new GreetServer().start(PORT)); Thread.sleep(500); } diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java new file mode 100644 index 0000000000..69b0b6d3ef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java @@ -0,0 +1,65 @@ +package com.baeldung.stream; + +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.IntStream; + +import org.junit.Test; + +import com.baeldung.stream.mycollectors.MyImmutableListCollector; +import com.google.common.collect.ImmutableList; + +public class StreamToImmutableTest { + + @Test + public void whenUsingCollectingToImmutableSet_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); + + System.out.println(result.getClass()); + } + + @Test + public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); + List result = givenList.stream() + .collect(collectingAndThen(toList(), Collections::unmodifiableList)); + + System.out.println(result.getClass()); + } + + @Test + public void whenCollectToImmutableList_thenSuccess() { + List list = IntStream.range(0, 9) + .boxed() + .collect(ImmutableList.toImmutableList()); + + System.out.println(list.getClass()); + } + + @Test + public void whenCollectToMyImmutableListCollector_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList()); + + System.out.println(result.getClass()); + } + + @Test + public void whenPassingSupplier_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); + + System.out.println(result.getClass()); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java new file mode 100644 index 0000000000..cf6b3601c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java @@ -0,0 +1,22 @@ +package com.baeldung.stream.mycollectors; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collector; + +public class MyImmutableListCollector { + + public static > Collector> toImmutableList(Supplier supplier) { + return Collector.of(supplier, List::add, (left, right) -> { + left.addAll(right); + return left; + }, Collections::unmodifiableList); + } + + public static Collector, List> toImmutableList() { + return toImmutableList(ArrayList::new); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java new file mode 100644 index 0000000000..916a3c79ff --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.string; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class CharSequenceVsStringUnitTest { + + @Test + public void givenUsingString_whenInstantiatingString_thenWrong() { + CharSequence firstString = "bealdung"; + String secondString = "baeldung"; + + assertNotEquals(firstString, secondString); + } + + @Test + public void givenIdenticalCharSequences_whenCastToString_thenEqual() { + CharSequence charSequence1 = "baeldung_1"; + CharSequence charSequence2 = "baeldung_2"; + + assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) < 0); + } + + @Test + public void givenString_whenAppended_thenUnmodified() { + String test = "a"; + int firstAddressOfTest = System.identityHashCode(test); + test += "b"; + int secondAddressOfTest = System.identityHashCode(test); + + assertNotEquals(firstAddressOfTest, secondAddressOfTest); + } + + @Test + public void givenStringBuilder_whenAppended_thenModified() { + StringBuilder test = new StringBuilder(); + test.append("a"); + int firstAddressOfTest = System.identityHashCode(test); + test.append("b"); + int secondAddressOfTest = System.identityHashCode(test); + + assertEquals(firstAddressOfTest, secondAddressOfTest); + } +} diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java new file mode 100644 index 0000000000..7b5f781620 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -0,0 +1,44 @@ +package com.baeldung.temporaladjusters; + +import com.baeldung.temporaladjuster.CustomTemporalAdjuster; +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjuster; + +import static org.junit.Assert.assertEquals; + +public class CustomTemporalAdjusterTest { + + private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); + + @Test + public void whenAdjustAndImplementInterface_thenNextWorkingDay() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); + LocalDate nextWorkingDay = localDate.with(temporalAdjuster); + + assertEquals("2017-07-10", nextWorkingDay.toString()); + } + + @Test + public void whenAdjust_thenNextWorkingDay() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + LocalDate date = localDate.with(NEXT_WORKING_DAY); + + assertEquals("2017-07-10", date.toString()); + } + + @Test + public void whenAdjust_thenFourteenDaysAfterDate() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14)); + LocalDate result = localDate.with(temporalAdjuster); + + String fourteenDaysAfterDate = "2017-07-22"; + + assertEquals(fourteenDaysAfterDate, result.toString()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java new file mode 100644 index 0000000000..d06da5a782 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java @@ -0,0 +1,22 @@ +package com.baeldung.temporaladjusters; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.temporal.TemporalAdjusters; + +import org.junit.Assert; +import org.junit.Test; + +public class TemporalAdjustersTest { + + @Test + public void whenAdjust_thenNextSunday() { + LocalDate localDate = LocalDate.of(2017, 07, 8); + LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); + + String expected = "2017-07-09"; + + Assert.assertEquals(expected, nextSunday.toString()); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java index 3ab8e1de91..5da68aa746 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java @@ -96,9 +96,12 @@ public class JavaIoUnitTest { // utils private final void logMemory() { - logger.info("Max Memory: {} Mb", Runtime.getRuntime().maxMemory() / 1048576); - logger.info("Total Memory: {} Mb", Runtime.getRuntime().totalMemory() / 1048576); - logger.info("Free Memory: {} Mb", Runtime.getRuntime().freeMemory() / 1048576); + logger.info("Max Memory: {} Mb", Runtime.getRuntime() + .maxMemory() / 1048576); + logger.info("Total Memory: {} Mb", Runtime.getRuntime() + .totalMemory() / 1048576); + logger.info("Free Memory: {} Mb", Runtime.getRuntime() + .freeMemory() / 1048576); } } diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index a11659547e..f17531e744 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -13,7 +13,6 @@ public class JavaRandomUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); - // tests - random long @Test @@ -25,7 +24,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { - final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); + final long generatedLong = new RandomDataGenerator().getRandomGenerator() + .nextLong(); LOG.debug("{}", generatedLong); } @@ -68,7 +68,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { - final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); + final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator() + .nextInt(); LOG.debug("{}", generatedInteger); } @@ -93,7 +94,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { - final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float generatedFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); LOG.debug("{}", generatedFloat); } @@ -111,7 +113,8 @@ public class JavaRandomUnitTest { public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { final float leftLimit = 1F; final float rightLimit = 10F; - final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float randomFloat = new RandomDataGenerator().getRandomGenerator() + .nextFloat(); final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); LOG.debug("{}", generatedFloat); @@ -128,7 +131,8 @@ public class JavaRandomUnitTest { @Test public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { - final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + final double generatedDouble = new RandomDataGenerator().getRandomGenerator() + .nextDouble(); LOG.debug("{}", generatedDouble); } diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java index 7a03070e82..826106a09e 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java @@ -15,7 +15,6 @@ public class JavaTimerLongRunningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); - // tests @Test @@ -23,7 +22,8 @@ public class JavaTimerLongRunningUnitTest { final TimerTask timerTask = new TimerTask() { @Override public void run() { - LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); + LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread() + .getName()); } }; final Timer timer = new Timer("Timer"); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 5af286dbca..1c16a5d435 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; +import java.util.Locale; import java.util.Scanner; import org.junit.Test; @@ -105,6 +106,7 @@ public class JavaScannerUnitTest { public void whenScanString_thenCorrect() throws IOException { final String input = "Hello 1 F 3.5"; final Scanner scanner = new Scanner(input); + scanner.useLocale(Locale.US); assertEquals("Hello", scanner.next()); assertEquals(1, scanner.nextInt()); diff --git a/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java b/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java new file mode 100644 index 0000000000..3fc26bcb51 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/lists/ListToSTring.java @@ -0,0 +1,31 @@ +package org.baeldung.java.lists; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +public class ListToSTring { + + @Test + public void whenListToString_thenPrintDefault() { + List intLIst = Arrays.asList(1, 2, 3); + System.out.println(intLIst); + } + + @Test + public void whenCollectorsJoining_thenPrintCustom() { + List intList = Arrays.asList(1, 2, 3); + System.out.println(intList.stream() + .map(n -> String.valueOf(n)) + .collect(Collectors.joining("-", "{", "}"))); + } + + @Test + public void whenStringUtilsJoin_thenPrintCustom() { + List intList = Arrays.asList(1, 2, 3); + System.out.println(StringUtils.join(intList, "|")); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java index 477092bfcb..99af49c8d3 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/Employee.java @@ -38,7 +38,8 @@ public class Employee implements Comparable { @Override public boolean equals(Object obj) { - return ((Employee) obj).getName().equals(getName()); + return ((Employee) obj).getName() + .equals(getName()); } @Override @@ -49,7 +50,13 @@ public class Employee implements Comparable { @Override public String toString() { - return new StringBuffer().append("(").append(getName()).append(getAge()).append(",").append(getSalary()).append(")").toString(); + return new StringBuffer().append("(") + .append(getName()) + .append(getAge()) + .append(",") + .append(getSalary()) + .append(")") + .toString(); } } diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java index 277e037615..ca9c9b4b5d 100644 --- a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java @@ -113,7 +113,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.keySet().toArray(), sortedKeys)); + assertTrue(Arrays.equals(sortedMap.keySet() + .toArray(), sortedKeys)); } @Test @@ -127,7 +128,8 @@ public class JavaSortingUnitTest { sortedMap.put(entry.getKey(), entry.getValue()); } - assertTrue(Arrays.equals(sortedMap.values().toArray(), sortedValues)); + assertTrue(Arrays.equals(sortedMap.values() + .toArray(), sortedValues)); } @Test diff --git a/ejb/README.md b/ejb/README.md index 08392bc80d..3b729318d4 100644 --- a/ejb/README.md +++ b/ejb/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) +- [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans) diff --git a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties index a01a675e44..67533b7825 100755 --- a/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties +++ b/ejb/ejb-client/src/main/resources/jboss-ejb-client.properties @@ -1,8 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false remote.connections=default remote.connection.default.host=127.0.0.1 remote.connection.default.port=8080 remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false -remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false -remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER} -remote.connection.default.username=testUser -remote.connection.default.password=admin1234! +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java new file mode 100644 index 0000000000..b65c21100d --- /dev/null +++ b/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java @@ -0,0 +1,42 @@ +package com.baeldung.ejbclient.application; + +import com.baeldung.ejbmodule.TextProcessorBean; +import com.baeldung.ejbmodule.TextProcessorRemote; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.util.Properties; + +public class TextApplication { + + public static void main(String[] args) throws NamingException { + TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:"); + System.out.print(textProcessor.processText("sample text")); + } + + private static class EJBFactory { + + private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException { + return lookupTextProcessorBean(namespace); + } + + private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException { + Context ctx = createInitialContext(); + final String appName = ""; + final String moduleName = "EJBModule"; + final String distinctName = ""; + final String beanName = TextProcessorBean.class.getSimpleName(); + final String viewClassName = TextProcessorRemote.class.getName(); + return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName); + } + + private static Context createInitialContext() throws NamingException { + Properties jndiProperties = new Properties(); + jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); + jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080"); + jndiProperties.put("jboss.naming.client.ejb.context", true); + return new InitialContext(jndiProperties); + } + } +} diff --git a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties new file mode 100644 index 0000000000..67533b7825 --- /dev/null +++ b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties @@ -0,0 +1,8 @@ +endpoint.name=client-endpoint +remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false +remote.connections=default +remote.connection.default.host=127.0.0.1 +remote.connection.default.port=8080 +remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false +remote.connection.default.username=myusername +remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java new file mode 100644 index 0000000000..947c72d0b0 --- /dev/null +++ b/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.ejbclient.application; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.naming.NamingException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import static org.junit.Assert.*; + +public class TextApplicationTest { + + private static ByteArrayOutputStream outContent; + + @BeforeClass + public static void setUpPrintStreamInstance() { + outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + } + + @AfterClass + public static void tearDownByteArrayOutputStream() { + outContent = null; + } + + @Test + public void givenInputString_whenCompareTtoStringPrintedToConsole_thenSuccessful() throws NamingException { + TextApplication.main(new String[]{}); + assertEquals("SAMPLE TEXT", outContent.toString()); + } +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java new file mode 100644 index 0000000000..dc0db5fc53 --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java @@ -0,0 +1,10 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Stateless; + +@Stateless +public class TextProcessorBean implements TextProcessorRemote { + public String processText(String text) { + return text.toUpperCase(); + } +} diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java new file mode 100644 index 0000000000..680d8f4e10 --- /dev/null +++ b/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java @@ -0,0 +1,9 @@ +package com.baeldung.ejbmodule; + +import javax.ejb.Remote; + +@Remote +public interface TextProcessorRemote { + + String processText(String text); +} \ No newline at end of file diff --git a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java new file mode 100644 index 0000000000..d8693420d4 --- /dev/null +++ b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java @@ -0,0 +1,12 @@ +package com.baeldung.ejbmodule; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class TextProcessorBeanTest { + @Test + public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() { + TextProcessorBean textProcessor = new TextProcessorBean(); + assertEquals("TEST", textProcessor.processText("test")); + } +} \ No newline at end of file diff --git a/feign/README.md b/feign/README.md index 149f7320d9..4d6964a73a 100644 --- a/feign/README.md +++ b/feign/README.md @@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign. [1]: https://github.com/eugenp/spring-hypermedia-api -###Relevant Articles: +### Relevant Articles: - [Intro to Feign](http://www.baeldung.com/intro-to-feign) diff --git a/feign/pom.xml b/feign/pom.xml index 9c3868c82f..78e1bbcf4c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,12 +1,9 @@ - + 4.0.0 com.baeldung.feign feign-client - 1.0.0-SNAPSHOT com.baeldung diff --git a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java index 56cf4071b4..31d377622d 100644 --- a/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java +++ b/feign/src/main/java/com/baeldung/feign/BookControllerFeignClientBuilder.java @@ -14,6 +14,12 @@ public class BookControllerFeignClientBuilder { private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); private static T createClient(Class type, String uri) { - return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri); + return Feign.builder() + .client(new OkHttpClient()) + .encoder(new GsonEncoder()) + .decoder(new GsonDecoder()) + .logger(new Slf4jLogger(type)) + .logLevel(Logger.Level.FULL) + .target(type, uri); } } diff --git a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java index a17dbf7a2e..bee440bd9e 100644 --- a/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java +++ b/feign/src/test/java/com/baeldung/feign/clients/BookClientLiveTest.java @@ -34,25 +34,31 @@ public class BookClientLiveTest { @Test public void givenBookClient_shouldRunSuccessfully() throws Exception { - List books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); + List books = bookClient.findAll() + .stream() + .map(BookResource::getBook) + .collect(Collectors.toList()); assertTrue(books.size() > 2); log.info("{}", books); } @Test public void givenBookClient_shouldFindOneBook() throws Exception { - Book book = bookClient.findByIsbn("0151072558").getBook(); + Book book = bookClient.findByIsbn("0151072558") + .getBook(); assertThat(book.getAuthor(), containsString("Orwell")); log.info("{}", book); } @Test public void givenBookClient_shouldPostBook() throws Exception { - String isbn = UUID.randomUUID().toString(); + String isbn = UUID.randomUUID() + .toString(); Book book = new Book(isbn, "Me", "It's me!", null, null); bookClient.create(book); - book = bookClient.findByIsbn(isbn).getBook(); + book = bookClient.findByIsbn(isbn) + .getBook(); assertThat(book.getAuthor(), is("Me")); log.info("{}", book); } diff --git a/grpc/pom.xml b/grpc/pom.xml new file mode 100644 index 0000000000..074075b5cc --- /dev/null +++ b/grpc/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + + grpc + grpc-demo + 0.0.1-SNAPSHOT + jar + + grpc-demo + http://maven.apache.org + + + UTF-8 + 1.5.0 + + + + + io.grpc + grpc-netty + ${io.grpc.version} + + + io.grpc + grpc-protobuf + ${io.grpc.version} + + + io.grpc + grpc-stub + ${io.grpc.version} + + + junit + junit + 4.12 + test + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + + com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} + + grpc-java + + io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} + + + + + + compile + compile-custom + + + + + + + diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java new file mode 100644 index 0000000000..1a1809387f --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java @@ -0,0 +1,28 @@ +package org.baeldung.grpc.client; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class GrpcClient { + public static void main(String[] args) throws InterruptedException { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080) + .usePlaintext(true) + .build(); + + HelloServiceGrpc.HelloServiceBlockingStub stub + = HelloServiceGrpc.newBlockingStub(channel); + + HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder() + .setFirstName("Baeldung") + .setLastName("gRPC") + .build()); + + System.out.println("Response received from server:\n" + helloResponse); + + channel.shutdown(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java new file mode 100644 index 0000000000..8a2b94e53b --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java @@ -0,0 +1,18 @@ +package org.baeldung.grpc.server; + +import java.io.IOException; + +import io.grpc.Server; +import io.grpc.ServerBuilder; + +public class GrpcServer { + public static void main(String[] args) throws IOException, InterruptedException { + Server server = ServerBuilder.forPort(8080) + .addService(new HelloServiceImpl()).build(); + + System.out.println("Starting server..."); + server.start(); + System.out.println("Server started!"); + server.awaitTermination(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java new file mode 100644 index 0000000000..b08ad02c97 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java @@ -0,0 +1,29 @@ +package org.baeldung.grpc.server; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase; + +import io.grpc.stub.StreamObserver; + +public class HelloServiceImpl extends HelloServiceImplBase { + + @Override + public void hello( + HelloRequest request, StreamObserver responseObserver) { + System.out.println("Request received from client:\n" + request); + + String greeting = new StringBuilder().append("Hello, ") + .append(request.getFirstName()) + .append(" ") + .append(request.getLastName()) + .toString(); + + HelloResponse response = HelloResponse.newBuilder() + .setGreeting(greeting) + .build(); + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } +} diff --git a/grpc/src/main/proto/HelloService.proto b/grpc/src/main/proto/HelloService.proto new file mode 100644 index 0000000000..4f53191ab9 --- /dev/null +++ b/grpc/src/main/proto/HelloService.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +option java_multiple_files = true; +package org.baeldung.grpc; + +message HelloRequest { + string firstName = 1; + string lastName = 2; +} + +message HelloResponse { + string greeting = 1; +} + +service HelloService { + rpc hello(HelloRequest) returns (HelloResponse); +} diff --git a/guava/README.md b/guava/README.md index 56d282560b..7ab70cb01f 100644 --- a/guava/README.md +++ b/guava/README.md @@ -28,3 +28,4 @@ - [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) - [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) +- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) diff --git a/guava/src/main/java/org/baeldung/guava/CustomEvent.java b/guava/src/main/java/org/baeldung/guava/CustomEvent.java index 2d5c3382d4..8534d7da1c 100644 --- a/guava/src/main/java/org/baeldung/guava/CustomEvent.java +++ b/guava/src/main/java/org/baeldung/guava/CustomEvent.java @@ -3,11 +3,11 @@ package org.baeldung.guava; public class CustomEvent { private String action; - public CustomEvent(String action) { + CustomEvent(String action) { this.action = action; } - public String getAction() { + String getAction() { return action; } diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java index 438fcade63..60beebeea5 100644 --- a/guava/src/main/java/org/baeldung/guava/EventListener.java +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -28,11 +28,11 @@ public class EventListener { eventsHandled++; } - public int getEventsHandled() { + int getEventsHandled() { return eventsHandled; } - public void resetEventsHandled() { + void resetEventsHandled() { eventsHandled = 0; } } diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java new file mode 100644 index 0000000000..d7c25b7c8d --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java @@ -0,0 +1,54 @@ +package org.baeldung.guava; + + +import com.google.common.hash.BloomFilter; +import com.google.common.hash.Funnels; +import org.junit.Test; + +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BloomFilterTest { + + @Test + public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 500, + 0.01); + + //when + filter.put(1); + filter.put(2); + filter.put(3); + + //then + // the probability that it returns true, but is actually false is 1% + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + + assertThat(filter.mightContain(100)).isFalse(); + } + + @Test + public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 5, + 0.01); + + //when + IntStream.range(0, 100_000).forEach(filter::put); + + + //then + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + assertThat(filter.mightContain(1_000_000)).isTrue(); + } +} diff --git a/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java new file mode 100644 index 0000000000..914de01a6d --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java @@ -0,0 +1,82 @@ +package org.baeldung.guava; + + +import com.google.common.util.concurrent.RateLimiter; +import org.junit.Test; + +import java.time.ZonedDateTime; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RateLimiterLongRunningUnitTest { + + @Test + public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() { + //given + RateLimiter rateLimiter = RateLimiter.create(100); + + //when + long startTime = ZonedDateTime.now().getSecond(); + IntStream.range(0, 1000).forEach(i -> { + rateLimiter.acquire(); + doSomeLimitedOperation(); + }); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds >= 10); + } + + @Test + public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() { + //given + RateLimiter rateLimiter = RateLimiter.create(2); + + //when + long startTime = ZonedDateTime.now().getSecond(); + rateLimiter.acquire(1); + doSomeLimitedOperation(); + rateLimiter.acquire(1); + doSomeLimitedOperation(); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds <= 1); + } + + @Test + public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() { + //given + RateLimiter rateLimiter = RateLimiter.create(100); + + //when + long startTime = ZonedDateTime.now().getSecond(); + rateLimiter.acquire(100); + doSomeLimitedOperation(); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds <= 1); + } + + @Test + public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() { + //given + RateLimiter rateLimiter = RateLimiter.create(1); + + //when + rateLimiter.acquire(); + boolean result = rateLimiter.tryAcquire(2, 10, TimeUnit.MILLISECONDS); + + //then + assertThat(result).isFalse(); + + } + + private void doSomeLimitedOperation() { + //some computing + } + +} diff --git a/guava21/pom.xml b/guava21/pom.xml index d6e556e4a0..930def2a67 100644 --- a/guava21/pom.xml +++ b/guava21/pom.xml @@ -4,8 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.guava - tutorial + guava21 1.0-SNAPSHOT @@ -15,12 +14,17 @@ - com.google.guava guava 21.0 + + + org.jooq + jool + 0.9.12 + diff --git a/guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java new file mode 100644 index 0000000000..866e09c6a0 --- /dev/null +++ b/guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java @@ -0,0 +1,85 @@ +package com.baeldung.guava.zip; + +import com.google.common.collect.Streams; +import org.jooq.lambda.Seq; +import org.jooq.lambda.tuple.Tuple2; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class ZipCollectionTest { + + private List names; + private List ages; + private List expectedOutput; + + @Before + public void setUp() throws Exception { + names = Arrays.asList("John", "Jane", "Jack", "Dennis"); + ages = Arrays.asList(24, 25, 27); + expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27"); + } + + @Test + public void zipCollectionUsingGuava21() { + List output = Streams + .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingIntStream() { + List output = IntStream + .range(0, Math.min(names.size(), ages.size())) + .mapToObj(i -> names.get(i) + ":" + ages.get(i)) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingJool() { + Seq output = Seq + .of("John", "Jane", "Jack") + .zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y); + + assertEquals(output.toList(), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolTuple() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zip(Seq.of(24, 25, 27)); + + Tuple2 element1 = new Tuple2("John", 24); + Tuple2 element2 = new Tuple2("Jane", 25); + Tuple2 element3 = new Tuple2("Dennis", 27); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolWithIndex() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zipWithIndex(); + + Tuple2 element1 = new Tuple2<>("John", 0L); + Tuple2 element2 = new Tuple2<>("Jane", 1L); + Tuple2 element3 = new Tuple2<>("Dennis", 2L); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + +} \ No newline at end of file diff --git a/guava21/src/test/java/AtomicLongMapIntegrationTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java similarity index 97% rename from guava21/src/test/java/AtomicLongMapIntegrationTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java index 9024329a56..273683710c 100644 --- a/guava21/src/test/java/AtomicLongMapIntegrationTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import com.google.common.util.concurrent.AtomicLongMap; import org.junit.Test; diff --git a/guava21/src/test/java/ComparatorsUnitTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java similarity index 98% rename from guava21/src/test/java/ComparatorsUnitTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java index 3d1f2e9e81..0183e6cf3a 100644 --- a/guava21/src/test/java/ComparatorsUnitTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import com.google.common.collect.Comparators; import org.junit.Assert; import org.junit.Test; diff --git a/guava21/src/test/java/GuavaStreamsUnitTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java similarity index 50% rename from guava21/src/test/java/GuavaStreamsUnitTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java index 96b4a2ffdb..3d3163cba6 100644 --- a/guava21/src/test/java/GuavaStreamsUnitTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java @@ -1,21 +1,33 @@ +package com.baeldung.guava.tutorial; + import com.google.common.collect.Streams; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.*; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; +import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; +import static com.baeldung.guava.tutorial.StreamUtility.assertStreamEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + public class GuavaStreamsUnitTest { - List numbers; + private List numbers; @Before public void setUp() { - numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); + numbers = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList()); } @Test @@ -24,17 +36,17 @@ public class GuavaStreamsUnitTest { Stream streamFromCollection = Streams.stream(numbers); //Assert.assertNotNull(streamFromCollection); - StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream()); + assertStreamEquals(streamFromCollection, numbers.stream()); } @Test public void createStreamsWithIterable() { - Iterable numbersIterable = (Iterable) numbers; + Iterable numbersIterable = numbers; Stream streamFromIterable = Streams.stream(numbersIterable); - Assert.assertNotNull(streamFromIterable); - StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream()); + assertNotNull(streamFromIterable); + assertStreamEquals(streamFromIterable, numbers.stream()); } @Test @@ -43,8 +55,8 @@ public class GuavaStreamsUnitTest { Stream streamFromIterator = Streams.stream(numbersIterator); - Assert.assertNotNull(streamFromIterator); - StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream()); + assertNotNull(streamFromIterator); + assertStreamEquals(streamFromIterator, numbers.stream()); } @Test @@ -52,8 +64,8 @@ public class GuavaStreamsUnitTest { Stream streamFromOptional = Streams.stream(Optional.of(1)); - Assert.assertNotNull(streamFromOptional); - Assert.assertEquals(streamFromOptional.count(), 1); + assertNotNull(streamFromOptional); + assertEquals(streamFromOptional.count(), 1); } @Test @@ -61,8 +73,8 @@ public class GuavaStreamsUnitTest { LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1)); - Assert.assertNotNull(streamFromOptionalLong); - Assert.assertEquals(streamFromOptionalLong.count(), 1); + assertNotNull(streamFromOptionalLong); + assertEquals(streamFromOptionalLong.count(), 1); } @Test @@ -71,7 +83,7 @@ public class GuavaStreamsUnitTest { IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1)); //Assert.assertNotNull(streamFromOptionalInt); - Assert.assertEquals(streamFromOptionalInt.count(), 1); + assertEquals(streamFromOptionalInt.count(), 1); } @Test @@ -80,63 +92,54 @@ public class GuavaStreamsUnitTest { DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0)); //Assert.assertNotNull(streamFromOptionalDouble); - Assert.assertEquals(streamFromOptionalDouble.count(), 1); + assertEquals(streamFromOptionalDouble.count(), 1); } @Test public void concatStreamsOfSameType() { - Stream oddNumbers = Arrays - .asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19) - .stream(); - Stream evenNumbers = Arrays - .asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) - .stream(); + List oddNumbers = Arrays + .asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19); + List evenNumbers = Arrays + .asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20); - Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers); + Stream combinedStreams = Streams.concat(oddNumbers.stream(), evenNumbers.stream()); //Assert.assertNotNull(combinedStreams); - StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers)); + assertStreamEquals(combinedStreams, Stream.concat(oddNumbers.stream(), evenNumbers.stream())); } @Test public void concatStreamsOfTypeLongStream() { - LongStream firstTwenty = LongStream.range(1, 20); - LongStream nextTwenty = LongStream.range(21, 40); + LongStream combinedStreams = Streams.concat(LongStream.range(1, 21), LongStream.range(21, 40)); - LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty); - - Assert.assertNotNull(combinedStreams); - StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty)); + assertNotNull(combinedStreams); + assertStreamEquals(combinedStreams, LongStream.range(1, 40)); } @Test public void concatStreamsOfTypeIntStream() { - IntStream firstTwenty = IntStream.range(1, 20); - IntStream nextTwenty = IntStream.range(21, 40); + IntStream combinedStreams = Streams.concat(IntStream.range(1, 20), IntStream.range(21, 40)); - IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty); - - Assert.assertNotNull(combinedStreams); - StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty)); + assertNotNull(combinedStreams); + assertStreamEquals(combinedStreams, IntStream.concat(IntStream.range(1, 20), IntStream.range(21, 40))); } @Test public void findLastOfStream() { Optional lastElement = Streams.findLast(numbers.stream()); - Assert.assertNotNull(lastElement.get()); - Assert.assertEquals(lastElement.get(), numbers.get(20)); + assertEquals(lastElement.get(), numbers.get(19)); } @Test public void mapWithIndexTest() { - Stream stringSream = Stream.of("a", "b", "c"); + Stream stringStream = Stream.of("a", "b", "c"); - Stream mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index); + Stream mappedStream = Streams.mapWithIndex(stringStream, (str, index) -> str + ":" + index); //Assert.assertNotNull(mappedStream); - Assert.assertEquals(mappedStream + assertEquals(mappedStream .findFirst() .get(), "a:0"); @@ -144,12 +147,12 @@ public class GuavaStreamsUnitTest { @Test public void streamsZipTest() { - Stream stringSream = Stream.of("a", "b", "c"); - Stream intStream = Stream.of(1, 2, 3); + Stream stringSream = Stream.of("a", "b", "c"); + Stream intStream = Stream.of(1, 2, 3); Stream mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index); //Assert.assertNotNull(mappedStream); - Assert.assertEquals(mappedStream + assertEquals(mappedStream .findFirst() .get(), "a:1"); diff --git a/guava21/src/test/java/InternBuilderUnitTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java similarity index 91% rename from guava21/src/test/java/InternBuilderUnitTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java index 183e3eeb43..13d8f5f3b7 100644 --- a/guava21/src/test/java/InternBuilderUnitTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import com.google.common.collect.Interner; import com.google.common.collect.Interners; import org.junit.Assert; diff --git a/guava21/src/test/java/MonitorUnitTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java similarity index 97% rename from guava21/src/test/java/MonitorUnitTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java index e29d4a1eeb..a3a9a4f838 100644 --- a/guava21/src/test/java/MonitorUnitTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import com.google.common.util.concurrent.Monitor; import org.junit.Assert; import org.junit.Test; diff --git a/guava21/src/test/java/MoreCollectorsUnitTest.java b/guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java similarity index 95% rename from guava21/src/test/java/MoreCollectorsUnitTest.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java index 5950997788..acd03022d2 100644 --- a/guava21/src/test/java/MoreCollectorsUnitTest.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import com.google.common.collect.MoreCollectors; import org.junit.Assert; import org.junit.Test; diff --git a/guava21/src/test/java/StreamUtility.java b/guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java similarity index 97% rename from guava21/src/test/java/StreamUtility.java rename to guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java index 1eb866fb88..b730fbf558 100644 --- a/guava21/src/test/java/StreamUtility.java +++ b/guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java @@ -1,3 +1,5 @@ +package com.baeldung.guava.tutorial; + import org.junit.Assert; import java.util.Iterator; diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml new file mode 100644 index 0000000000..9d88c94197 --- /dev/null +++ b/guest/logback-example/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + com.stackify + logback-example + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + junit + junit + 4.12 + + + + org.codehaus.janino + janino + 3.0.7 + + + + + + + + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java new file mode 100644 index 0000000000..c0eb414588 --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/logging/IgnoreLoggerFilter.java @@ -0,0 +1,28 @@ +package com.stackify.logging; + +import org.slf4j.Marker; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.turbo.TurboFilter; +import ch.qos.logback.core.spi.FilterReply; + +public class IgnoreLoggerFilter extends TurboFilter { + + private String loggerName; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (loggerName == null) { + return FilterReply.NEUTRAL; + } else if (loggerName.equals(logger.getName())) { + return FilterReply.DENY; + } else + return FilterReply.NEUTRAL; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/models/Employee.java b/guest/logback-example/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 0000000000..1d040b372b --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,43 @@ +package com.stackify.models; + +public class Employee { + + private String email; + private String name; + + private double salary; + + public Employee() { + } + + public Employee(String email, String name, double salary) { + this.email = email; + this.name = name; + this.salary = salary; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 0000000000..1795101f40 --- /dev/null +++ b/guest/logback-example/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,11 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + + public double calculateBonus(Employee user) { + return 0.1 * user.getSalary(); + } + +} diff --git a/guest/logback-example/src/main/resources/application.properties b/guest/logback-example/src/main/resources/application.properties new file mode 100644 index 0000000000..601f964ff3 --- /dev/null +++ b/guest/logback-example/src/main/resources/application.properties @@ -0,0 +1 @@ +env=dev \ No newline at end of file diff --git a/guest/logback-example/src/main/resources/logback.xml b/guest/logback-example/src/main/resources/logback.xml new file mode 100644 index 0000000000..d8ec24c7c3 --- /dev/null +++ b/guest/logback-example/src/main/resources/logback.xml @@ -0,0 +1,151 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.out + + + + + + + + + log-%d{yyyy-MM-dd}.log + 30 + 3GB + + + 3MB + + + %d [%thread] %-5level %logger{50} - %msg%n + + + + + + userRole + ANONYMOUS + + + + ${userRole}.log + + %d [%thread] %level %mdc %logger{50} - %msg%n + + + + + + + + + %d %green([%thread]) %highlight(%level) %logger{50} - %msg%n + + + + + + + %thread%level%logger%msg + + + log.html + + + + + + ERROR + ACCEPT + DENY + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + System.err + + + + + WARN + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + return (level > DEBUG && message.toLowerCase().contains("employee")); + + DENY + NEUTRAL + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + 2 + + + + ignoredColorLogger + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java new file mode 100644 index 0000000000..187b27e1df --- /dev/null +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java @@ -0,0 +1,74 @@ +package com.stackify.services; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import com.stackify.models.Employee; + +import ch.qos.logback.classic.Level; + +public class EmployeeServiceTest { + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private EmployeeService employeeService = new EmployeeService(); + + @Test + public void testAppenders() { + Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.info("Testing rolling file logger"); + + MDC.put("userRole", "ADMIN"); + Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger"); + siftingLogger.info("Admin Action"); + } + + @Test + public void testLayouts() { + Logger htmlLogger = LoggerFactory.getLogger("htmlLogger"); + htmlLogger.error("Employee Information Update Failed"); + htmlLogger.info("New Account Created"); + + Logger colorLogger = LoggerFactory.getLogger("colorLogger"); + colorLogger.error("Employee Information Update Failed"); + colorLogger.info("New Account Created"); + } + + @Test + public void testLogLevel() { + ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger"); + rollingFileLogger.setLevel(Level.DEBUG); + rollingFileLogger.debug("Testing Log Level"); + } + + @Test + public void testParameter() { + Employee employee = new Employee("john@gmail.com", "John", 2000); + if (logger.isDebugEnabled()) { + logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); + } + logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); + } + + @Test + public void testFilters() { + Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger"); + levelFilterLogger.error("Employee Information Update Failed"); + Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger"); + thresholdFilterLogger.trace("Employee record inserted"); + Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger"); + evaluatorFilterLogger.debug("Employee account deactivated"); + } + + @Test + public void testIgnoredLogger() { + Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger"); + colorLogger.info("Ignored Log Message"); + } + + @Test + public void testConditionalConfiguration() { + logger.trace("Employee record updated"); + } +} diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml new file mode 100644 index 0000000000..72a10213c4 --- /dev/null +++ b/guest/thread-pools/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + com.stackify + thread-pools + 0.0.1-SNAPSHOT + + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + \ No newline at end of file diff --git a/guest/thread-pools/src/main/java/com/stackify/models/Employee.java b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java new file mode 100644 index 0000000000..65661f38d5 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/models/Employee.java @@ -0,0 +1,28 @@ +package com.stackify.models; + +public class Employee { + private String name; + private double salary; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java new file mode 100644 index 0000000000..824f87a625 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/services/EmployeeService.java @@ -0,0 +1,9 @@ +package com.stackify.services; + +import com.stackify.models.Employee; + +public class EmployeeService { + public double calculateBonus(Employee employee) { + return 0.1 * employee.getSalary(); + } +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java new file mode 100644 index 0000000000..2dd83d9b20 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/FactorialTask.java @@ -0,0 +1,64 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; +import java.util.stream.IntStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FactorialTask extends RecursiveTask { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + private static final long serialVersionUID = 1L; + + private int start = 1; + private int n; + + private static final int THRESHOLD = 20; + + public FactorialTask(int n) { + this.n = n; + } + + public FactorialTask(int start, int n) { + logger.info("New FactorialTask Created"); + this.start = start; + this.n = n; + } + + @Override + protected BigInteger compute() { + if ((n - start) >= THRESHOLD) { + return ForkJoinTask.invokeAll(createSubtasks()) + .stream() + .map(ForkJoinTask::join) + .reduce(BigInteger.ONE, BigInteger::multiply); + } else { + return calculate(start, n); + } + } + + private Collection createSubtasks() { + List dividedTasks = new ArrayList<>(); + + int mid = (start + n) / 2; + + dividedTasks.add(new FactorialTask(start, mid)); + dividedTasks.add(new FactorialTask(mid + 1, n)); + return dividedTasks; + } + + private BigInteger calculate(int start, int n) { + logger.info("Calculate factorial from " + start + " to " + n); + return IntStream.rangeClosed(start, n) + .mapToObj(BigInteger::valueOf) + .reduce(BigInteger.ONE, BigInteger::multiply); + } + +} diff --git a/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java new file mode 100644 index 0000000000..cc9048eee7 --- /dev/null +++ b/guest/thread-pools/src/main/java/com/stackify/threadpools/ThreadsApplication.java @@ -0,0 +1,102 @@ +package com.stackify.threadpools; + +import java.math.BigInteger; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.stackify.models.Employee; +import com.stackify.services.EmployeeService; + +public class ThreadsApplication { + + private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + + public static void main(String[] args) { + testExecutor(); + testExecutorService(); + testScheduledExecutorService(); + testThreadPoolExecutor(); + testForkJoinPool(); + } + + private static EmployeeService employeeService = new EmployeeService(); + + public static void testExecutor() { + Executor executor = Executors.newSingleThreadExecutor(); + executor.execute(() -> System.out.println("Single thread pool test")); + } + + public static void testExecutorService() { + + Employee employee = new Employee("John", 2000); + + ExecutorService executor = Executors.newFixedThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + Future future = executor.submit(callableTask); + + try { + if (future.isDone()) { + double result = future.get(); + System.out.println("Bonus is:" + result); + } + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.shutdown(); + } + + public static void testScheduledExecutorService() { + Employee employee = new Employee("John", 2000); + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); + + Callable callableTask = () -> { + return employeeService.calculateBonus(employee); + }; + + Future futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS); + + try { + System.out.println("Bonus:" + futureScheduled.get()); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + + executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS); + } + + public static void testThreadPoolExecutor() { + ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); + ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + + ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue()); + executor.setMaximumPoolSize(8); + + ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); + } + + public static void testForkJoinPool() { + ForkJoinPool pool = ForkJoinPool.commonPool(); + logger.info("Thread Pool Created"); + BigInteger result = pool.invoke(new FactorialTask(100)); + System.out.println(result.toString()); + } +} diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 562b3e9bcd..b7567e0c4b 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -147,7 +147,7 @@ 2.5.1 4.4.5 - 4.5.2 + 4.5.3 1.6.1 diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index f2086f2633..d39697c0a9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest { @Test public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); @@ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest { private final HttpContext context; private final HttpGet request; - public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { + GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { this.client = client; context = HttpClientContext.create(); this.request = request; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java index ebd67512e4..51c3817da5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java @@ -1,11 +1,7 @@ package org.baeldung.httpclient; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.collect.Lists; import org.apache.http.Header; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -20,7 +16,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.List; public class HttpClientHeadersLiveTest { @@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - headers - deprecated diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 954236a56f..9912e73c2b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -1,22 +1,7 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; @@ -30,6 +15,20 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + public class HttpClientMultipartLiveTest { // No longer available @@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest { @Before public final void before() { client = HttpClientBuilder.create() - .build(); + .build(); post = new HttpPost(SERVER); } @@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw e; } - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @@ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest { response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { + public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + ZIPFILENAME); + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + IMAGEFILENAME); + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest { // UTIL - final String getContent() throws IOException { + private String getContent() throws IOException { rd = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); + .getContent())); String body = ""; - String content = ""; + StringBuilder content = new StringBuilder(); while ((body = rd.readLine()) != null) { - content += body + "\n"; + content.append(body).append("\n"); } - return content.trim(); + return content.toString().trim(); } - final String getContentTypeHeader() throws IOException { + private String getContentTypeHeader() throws IOException { return post.getEntity() - .getContentType() - .toString(); + .getContentType() + .toString(); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index ada5667f0b..39ed8f09ef 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -1,20 +1,10 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; @@ -29,17 +19,26 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-rest to be running */ public class HttpClientPostingLiveTest { - private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; + private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; private static final String DEFAULT_PASS = "test"; @Test - public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL); @@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { + public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); @@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } @Test - public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); @@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -133,12 +132,7 @@ public class HttpClientPostingLiveTest { builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); final HttpEntity multipart = builder.build(); - final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { - @Override - public void progress(final float percentage) { - assertFalse(Float.compare(percentage, 100) > 0); - } - }; + final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0); httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java index 3cb02dc767..a501367a6b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; @@ -21,6 +13,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientRedirectLiveTest { private CloseableHttpClient instance; @@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClients.custom().disableRedirectHandling().build(); final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); @@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().disableRedirectHandling().build(); response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); @@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest { // redirect with POST @Test - public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); } @Test - public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { /** Redirectable methods. */ - private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; + private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME}; @Override protected boolean isRedirectable(final String method) { - for (final String m : REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; + return Arrays.stream(REDIRECT_METHODS) + .anyMatch(m -> m.equalsIgnoreCase(method)); } }).build(); @@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); @@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java index 7e7dbe2146..74255e416c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientTimeoutLiveTest { private CloseableHttpResponse response; @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException { final int timeout = 2; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); @@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException { final int timeout = 2; final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); @@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException { final int timeout = 5; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); @@ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest { * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) */ @Test(expected = HttpHostConnectException.class) - public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException { + public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { final int timeout = 3; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 5dfecb85aa..4eadfe24d5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,14 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; - import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; @@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.junit.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java index f0b7e0e559..cd00d8711a 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java @@ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper; public class ProgressEntityWrapper extends HttpEntityWrapper { private final ProgressListener listener; - public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { + ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { super(entity); this.listener = listener; } @@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); } - public static interface ProgressListener { + public interface ProgressListener { void progress(float percentage); } @@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { private long transferred; private long totalBytes; - public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { + CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { super(out); this.listener = listener; transferred = 0; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java new file mode 100644 index 0000000000..fd38b95cbe --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java @@ -0,0 +1,26 @@ +package org.baeldung.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; + +import java.io.IOException; + +public final class ResponseUtil { + private ResponseUtil() { + } + + public static void closeResponse(CloseableHttpResponse response) throws IOException { + if (response == null) { + return; + } + + try { + final HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.getContent().close(); + } + } finally { + response.close(); + } + } +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index b5a76241d1..77d5a298c1 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -24,7 +24,14 @@ import org.junit.Test; import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; public class HttpClientAdvancedConfigurationIntegrationTest { @@ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) - .withHeader("User-Agent", equalTo(userAgent)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("User-Agent", equalTo(userAgent)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); @@ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) - .withHeader("Content-Type", equalTo("application/xml")) - .withRequestBody(equalTo(xmlBody)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo(xmlBody)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8089/person"); @@ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { //given proxyMock.stubFor(get(urlMatching(".*")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .build(); + .setRoutePlanner(routePlanner) + .build(); //when final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); @@ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given proxyMock.stubFor(get(urlMatching("/private")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); @@ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { // Client credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), - new UsernamePasswordCredentials("username_admin", "secret_password")); + new UsernamePasswordCredentials("username_admin", "secret_password")); // Create AuthCache instance @@ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .setDefaultCredentialsProvider(credentialsProvider) - .build(); + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); //when diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java index 2a101ec816..fee9dc4343 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -16,10 +8,17 @@ import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + public class HttpClientBasicLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java index 7eb078b18b..fe275be082 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java @@ -1,22 +1,20 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + public class HttpClientBasicPostLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - non-GET @Test - public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequest_thenNoExceptions() throws IOException { instance.execute(new HttpPost(SAMPLE_URL)); } @Test - public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); instance.execute(request); } @Test - public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { + public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 878d220f67..78097227e7 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.io.InputStream; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.not; @@ -37,19 +37,7 @@ public class HttpClientLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index 40216a70a5..d945d075f2 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,9 +1,5 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; @@ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.Test; +import java.io.IOException; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest { System.out.println(response.getStatusLine()); - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - // EntityUtils.consume(entity); - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index e04cd32d65..0f8ebefe6c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -1,11 +1,5 @@ package org.baeldung.httpclient.conn; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HttpClientConnection; @@ -36,6 +30,12 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + public class HttpClientConnectionManagementLiveTest { private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER7 = "http://www.baeldung.com/"; @@ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // Example 3.2. TESTER VERSION - /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + /*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 4.2 Tester Version - /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { + /*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); @@ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 6.2 TESTER VERSION - /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { + /*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setMaxTotal(5); @@ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest { @Test @Ignore("Very Long Running") // 8.2 TESTER VERSION - /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { + /*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java index 2a1c419e41..ffe4155a78 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; - public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { + IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread { } } - public final void shutdown() { + private void shutdown() { shutdown = true; synchronized (this) { notifyAll(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index 071b964710..3794943f02 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public int leasedConn; + private int leasedConn; - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; leasedConn = 0; } - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { this.client = client; this.get = get; } // API - public final int getLeasedConn() { + final int getLeasedConn() { return leasedConn; } @@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread { } EntityUtils.consume(response.getEntity()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 62cd466596..9cc6480e74 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = Preconditions.checkNotNull(connManager); @@ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java index a185e99639..8fc79baed9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java @@ -1,12 +1,7 @@ package org.baeldung.httpclient.rare; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.http.Header; @@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils; import org.junit.Before; import org.junit.Test; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; public class HttpClientUnshortenLiveTest { @@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest { // API - final String expand(final String urlArg) throws IOException { + private String expand(final String urlArg) throws IOException { String originalUrl = urlArg; String newUrl = expandSingleLevel(originalUrl); while (!originalUrl.equals(newUrl)) { @@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest { return newUrl; } - final Pair expandSingleLevelSafe(final String url) throws IOException { + private Pair expandSingleLevelSafe(final String url) throws IOException { HttpHead request = null; HttpEntity httpEntity = null; InputStream entityContentStream = null; @@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 301 && statusCode != 302) { - return new ImmutablePair(statusCode, url); + return new ImmutablePair<>(statusCode, url); } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); final String newUrl = headers[0].getValue(); - return new ImmutablePair(statusCode, newUrl); + return new ImmutablePair<>(statusCode, newUrl); } catch (final IllegalArgumentException uriEx) { - return new ImmutablePair(500, url); + return new ImmutablePair<>(500, url); } finally { if (request != null) { request.releaseConnection(); @@ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest { } } - final String expandSingleLevel(final String url) throws IOException { + private String expandSingleLevel(final String url) throws IOException { HttpHead request = null; try { @@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest { } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); - final String newUrl = headers[0].getValue(); - return newUrl; + return headers[0].getValue(); } catch (final IllegalArgumentException uriEx) { return url; } finally { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java index e98dd4d14f..7a75729ea5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java @@ -1,21 +1,12 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; - import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); @@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); @@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); @@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest { // UTILS - private final CredentialsProvider provider() { + private CredentialsProvider provider() { final CredentialsProvider provider = new BasicCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); provider.setCredentials(AuthScope.ANY, credentials); return provider; } - private final HttpContext context() { + private HttpContext context() { final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); @@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest { return context; } - private final String authorizationHeader(final String username, final String password) { + private String authorizationHeader(final String username, final String password) { final String auth = username + ":" + password; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); - final String authHeader = "Basic " + new String(encodedAuth); - return authHeader; + return "Basic " + new String(encodedAuth); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java index 7da9ad04e4..ba27aca08d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientCookieLiveTest { private CloseableHttpClient instance; @@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { instance = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet("http://www.github.com"); request.setHeader("Cookie", "JSESSIONID=1234"); @@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); diff --git a/jackson/pom.xml b/jackson/pom.xml index 1a538670c6..f970b6a68c 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -129,7 +129,7 @@ - 2.8.7 + 2.9.0 19.0 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 index 0330498089..db8b594509 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Author.java @@ -9,7 +9,8 @@ public class Author extends Person { List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java index 3add362007..9ba91e9170 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jacksoninject/Person.java @@ -11,7 +11,7 @@ public class Person { private String firstName; private String lastName; - public Person(){ + public Person() { } 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 index 34fbd16c1c..d48c95b255 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsoncreator/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.deserialization.jsoncreator; - import com.baeldung.jackson.domain.Person; import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonCreator; @@ -14,9 +13,7 @@ public class Author extends Person { List items = new ArrayList<>(); @JsonCreator - public Author( - @JsonProperty("christianName") String firstName, - @JsonProperty("surname") String lastName) { + public Author(@JsonProperty("christianName") String firstName, @JsonProperty("surname") String lastName) { super(firstName, lastName); } 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 8e93ab5ce7..dc0d0ee623 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 @@ -13,7 +13,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book() {} + public Book() { + } public Book(String title, Author author) { super(title, author); diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java index c9d6ae39fa..93bbfd0069 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java @@ -11,8 +11,7 @@ import java.util.Date; public class CustomDateDeserializer extends StdDeserializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateDeserializer() { this(null); @@ -23,8 +22,7 @@ public class CustomDateDeserializer extends StdDeserializer { } @Override - public Date deserialize(JsonParser jsonparser, DeserializationContext context) - throws IOException { + public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException { String date = jsonparser.getText(); try { return formatter.parse(date); 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 index ab4689dec8..fc27a586ac 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsondeserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index c63b63f515..3f9ae70a88 100644 --- a/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/jsonsetter/Author.java @@ -18,7 +18,8 @@ public class Author extends Person { private List items = new ArrayList<>(); - public Author(){} + public Author() { + } public Author(String firstName, String lastName) { super(firstName, lastName); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java index 6e486ffbd3..a5963e33ba 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Book.java @@ -15,7 +15,7 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){ + public Book() { } public Book(String title, Author author) { diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java index 15049ded09..672b0bc250 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Course.java @@ -10,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java index fc861d2f3c..d9d1350a8e 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Item.java @@ -17,7 +17,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 2f66a1acfe..785efff755 100644 --- a/jackson/src/main/java/com/baeldung/jackson/domain/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/domain/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java index 54ebff8a56..107d75eb0d 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/ClassWithAMap.java @@ -9,16 +9,16 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class ClassWithAMap { - @JsonProperty("map") - @JsonDeserialize(keyUsing = MyPairDeserializer.class) - private final Map map; + @JsonProperty("map") + @JsonDeserialize(keyUsing = MyPairDeserializer.class) + private final Map map; - @JsonCreator - public ClassWithAMap(Map map) { - this.map = map; - } + @JsonCreator + public ClassWithAMap(Map map) { + this.map = map; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java index ebe41890fe..ca5960e0cf 100644 --- a/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java +++ b/jackson/src/main/java/com/baeldung/jackson/entities/MyPair.java @@ -4,77 +4,77 @@ import com.fasterxml.jackson.annotation.JsonValue; public class MyPair { - private String first; - private String second; + private String first; + private String second; - public MyPair(String first, String second) { - this.first = first; - this.second = second; - } + public MyPair(String first, String second) { + this.first = first; + this.second = second; + } - public MyPair(String both) { - String[] pairs = both.split("and"); - this.first = pairs[0].trim(); - this.second = pairs[1].trim(); - } + public MyPair(String both) { + String[] pairs = both.split("and"); + this.first = pairs[0].trim(); + this.second = pairs[1].trim(); + } - @Override - @JsonValue - public String toString() { - return first + " and " + second; - } + @Override + @JsonValue + public String toString() { + return first + " and " + second; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((first == null) ? 0 : first.hashCode()); + result = prime * result + ((second == null) ? 0 : second.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof MyPair)) { - return false; - } - MyPair other = (MyPair) obj; - if (first == null) { - if (other.first != null) { - return false; - } - } else if (!first.equals(other.first)) { - return false; - } - if (second == null) { - if (other.second != null) { - return false; - } - } else if (!second.equals(other.second)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MyPair)) { + return false; + } + MyPair other = (MyPair) obj; + if (first == null) { + if (other.first != null) { + return false; + } + } else if (!first.equals(other.first)) { + return false; + } + if (second == null) { + if (other.second != null) { + return false; + } + } else if (!second.equals(other.second)) { + return false; + } + return true; + } - public String getFirst() { - return first; - } + public String getFirst() { + return first; + } - public void setFirst(String first) { - this.first = first; - } + public void setFirst(String first) { + this.first = first; + } - public String getSecond() { - return second; - } + public String getSecond() { + return second; + } - public void setSecond(String second) { - this.second = second; - } + public void setSecond(String second) { + this.second = second; + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/format/User.java b/jackson/src/main/java/com/baeldung/jackson/format/User.java index 101ef09a4a..e655deb93b 100755 --- a/jackson/src/main/java/com/baeldung/jackson/format/User.java +++ b/jackson/src/main/java/com/baeldung/jackson/format/User.java @@ -13,28 +13,25 @@ public class User extends Person { private String firstName; private String lastName; - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") private Date createdDate; - public User(String firstName,String lastName) { - super(firstName, lastName); - this.createdDate = new Date(); + public User(String firstName, String lastName) { + super(firstName, lastName); + this.createdDate = new Date(); } public Date getCreatedDate() { return createdDate; } - @JsonFormat(shape = JsonFormat.Shape.STRING, - pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", - locale = "en_GB") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB") public Date getCurrentDate() { - return new Date(); + return new Date(); } @JsonFormat(shape = JsonFormat.Shape.NUMBER) public Date getDateNum() { - return new Date(); + return new Date(); } } 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 index 8c18522627..0037d83148 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignore/Person.java @@ -17,7 +17,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); 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 index e6d62eee3d..70b4dd9842 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/inclusion/jsonignoreproperties/Course.java @@ -12,10 +12,12 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIgnoreProperties({"medium"}) +@JsonIgnoreProperties({ "medium" }) public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java index 11aa8ddb1a..db0412b09b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdAddedToUser.java @@ -12,10 +12,7 @@ public class ItemIdAddedToUser extends Event { private final Long quantity; @JsonCreator - public ItemIdAddedToUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; diff --git a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java index 682394ddf3..ab3b9bf34f 100644 --- a/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java +++ b/jackson/src/main/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUser.java @@ -10,10 +10,7 @@ public class ItemIdRemovedFromUser extends Event { private final Long quantity; @JsonCreator - public ItemIdRemovedFromUser(@JsonProperty("id") String id, - @JsonProperty("timestamp") Long timestamp, - @JsonProperty("itemId") String itemId, - @JsonProperty("quantity") Long quantity) { + public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { super(id, timestamp); this.itemId = itemId; this.quantity = quantity; 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 index 8825677e86..a44492b9f7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Course.java @@ -13,7 +13,9 @@ import java.util.List; @CustomCourseAnnotation public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); 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 index 37b0bf357e..d7f72ca6ec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/CustomCourseAnnotation.java @@ -14,7 +14,7 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"title", "price", "id", "duration", "authors", "level"}) -@JsonIgnoreProperties({"prerequisite"}) +@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 index 930c4afb58..6625283dec 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/custom/Item.java @@ -20,7 +20,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index 8df3aec051..0638e32925 100644 --- a/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/miscellaneous/disable/Author.java @@ -16,7 +16,7 @@ import java.util.List; * @version 1.0 */ @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"lastName", "items", "firstName", "id"}) +@JsonPropertyOrder({ "lastName", "items", "firstName", "id" }) public class Author extends Person { @JsonIgnore diff --git a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java index 1eab9f5d02..1813148b2b 100644 --- a/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java +++ b/jackson/src/main/java/com/baeldung/jackson/polymorphism/Order.java @@ -18,12 +18,8 @@ public class Order { 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") - }) + @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; diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java index 32a6358003..2340de5957 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/ActorJacksonSerializer.java @@ -24,8 +24,11 @@ public class ActorJacksonSerializer extends StdSerializer { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("imdbId", actor.getImdbId()); jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); - jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography().size() : null); - jsonGenerator.writeStringField("filmography", actor.getFilmography().stream().collect(Collectors.joining("-"))); + jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography() + .size() : null); + jsonGenerator.writeStringField("filmography", actor.getFilmography() + .stream() + .collect(Collectors.joining("-"))); jsonGenerator.writeEndObject(); } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java index 0aa6db98d0..43bdc1c500 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairDeserializer.java @@ -9,10 +9,9 @@ import com.fasterxml.jackson.databind.KeyDeserializer; public class MyPairDeserializer extends KeyDeserializer { - @Override - public MyPair deserializeKey(String key, DeserializationContext ctxt) - throws IOException, JsonProcessingException { + @Override + public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { - return new MyPair(key); - } + return new MyPair(key); + } } \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java index 68afb6c193..fee1cafe16 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/MyPairSerializer.java @@ -12,14 +12,12 @@ import com.fasterxml.jackson.databind.SerializerProvider; public class MyPairSerializer extends JsonSerializer { - private final ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); - @Override - public void serialize(MyPair value, JsonGenerator gen, - SerializerProvider serializers) throws IOException, - JsonProcessingException { - StringWriter writer = new StringWriter(); - mapper.writeValue(writer, value); - gen.writeFieldName(writer.toString()); - } + @Override + public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { + StringWriter writer = new StringWriter(); + mapper.writeValue(writer, value); + gen.writeFieldName(writer.toString()); + } } \ No newline at end of file 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 index 13453edeb2..8d89fefce7 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsongetter/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsongetter; - import com.baeldung.jackson.domain.Item; import com.baeldung.jackson.domain.Person; import com.fasterxml.jackson.annotation.JsonGetter; 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 index c5214f3305..dadf893cf9 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonpropertyorder/Author.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.serialization.jsonpropertyorder; - import com.baeldung.jackson.domain.Item; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -13,7 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonPropertyOrder({"items", "firstName", "lastName", "id"}) +@JsonPropertyOrder({ "items", "firstName", "lastName", "id" }) public class Author extends Person { List items = new ArrayList<>(); 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 index e682f7c394..0ecc4e72ce 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Book.java @@ -19,7 +19,8 @@ public class Book extends Item { private Date published; private BigDecimal pages; - public Book(){} + public Book() { + } public Book(String title, Author author) { super(title, author); 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 index 8e6d20cfe0..131f4f3695 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/CustomDateSerializer.java @@ -17,8 +17,7 @@ import java.util.Date; */ public class CustomDateSerializer extends StdSerializer { - private static SimpleDateFormat formatter = - new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); + private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); public CustomDateSerializer() { this(null); @@ -29,8 +28,7 @@ public class CustomDateSerializer extends StdSerializer { } @Override - public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) - throws IOException, JsonProcessingException { + 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 index ed6ac25184..56cfa85793 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonserialize/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index eb7cb097e5..a3fdc2d8eb 100644 --- a/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java +++ b/jackson/src/main/java/com/baeldung/jackson/serialization/jsonvalue/Course.java @@ -14,7 +14,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java index c4e0a2ecdb..647c451659 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java @@ -47,9 +47,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, not(containsString("version"))); assertThat(jsonString, not(containsString("1.0"))); } @@ -59,9 +60,10 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0"); + ObjectWriter writer = mapper.writerFor(BeanWithAppend.class) + .withAttribute("version", "1.0"); String jsonString = writer.writeValueAsString(bean); - + assertThat(jsonString, containsString("version")); assertThat(jsonString, containsString("1.0")); } @@ -71,7 +73,7 @@ public class ExtraAnnotationUnitTest { ObjectMapper mapper = new ObjectMapper(); NamingBean bean = new NamingBean(3, "Naming Bean"); String jsonString = mapper.writeValueAsString(bean); - + assertThat(jsonString, containsString("bean_name")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java index 495bb7de43..0a8736d9a5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java +++ b/jackson/src/test/java/com/baeldung/jackson/annotation/extra/IdentityReferenceBeans.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; - public class IdentityReferenceBeans { @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public static class BeanWithoutIdentityReference { @@ -32,7 +31,7 @@ public class IdentityReferenceBeans { this.name = name; } } - + @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityReference(alwaysAsId = true) public static class BeanWithIdentityReference { diff --git a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java index 75e0a4ecb7..c6babdee01 100644 --- a/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/bidirection/CustomListSerializer.java @@ -20,6 +20,7 @@ public class CustomListSerializer extends StdSerializer public CustomListSerializer(final Class> t) { super(t); } + @Override public void serialize(final List items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { final List ids = new ArrayList(); diff --git a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java index dbcf42488e..ac7d772f0f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/date/CustomLocalDateTimeSerializer.java @@ -11,7 +11,6 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class CustomLocalDateTimeSerializer extends StdSerializer { - private static final long serialVersionUID = -7449444168934819290L; private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java index e9c89b8c78..bbc3f31a6c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializer.java @@ -28,9 +28,11 @@ public class ItemDeserializer extends StdDeserializer { */ @Override public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue(); return new Item(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java index 2036780e99..eaba9a7173 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/ItemDeserializerOnClass.java @@ -28,9 +28,11 @@ public class ItemDeserializerOnClass extends StdDeserializer */ @Override public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec().readTree(jp); + final JsonNode node = jp.getCodec() + .readTree(jp); final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName").asText(); + final String itemName = node.get("itemName") + .asText(); final int userId = (Integer) ((IntNode) node.get("owner")).numberValue(); return new ItemWithSerializer(id, itemName, new User(userId, null)); diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java index 4d5db699a0..1c3e95241a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/JacksonMapDeserializeUnitTest.java @@ -16,54 +16,49 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonMapDeserializeUnitTest { - private Map map; - private Map cmap; - final ObjectMapper mapper = new ObjectMapper(); + private Map map; + private Map cmap; + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"key\": \"value\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"key\": \"value\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - final Map map = mapper.readValue(jsonInput, typeRef); + final Map map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("value", map.get("key")); - } + Assert.assertEquals("value", map.get("key")); + } - @Test - public void whenObjectStringMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; + final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + TypeReference> typeRef = new TypeReference>() { + }; - map = mapper.readValue(jsonInput, typeRef); + map = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); + Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); - ClassWithAMap classWithMap = mapper.readValue(jsonInput, - ClassWithAMap.class); + ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class); - Assert.assertEquals("Comedy", - classWithMap.getMap().get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals("Comedy", classWithMap.getMap() + .get(new MyPair("Abbott", "Costello"))); + } - @Test - public void whenObjectObjectMapDeserialize_thenCorrect() - throws JsonParseException, JsonMappingException, IOException { + @Test + public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; - TypeReference> typeRef = new TypeReference>() { - }; + final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; + TypeReference> typeRef = new TypeReference>() { + }; - cmap = mapper.readValue(jsonInput, typeRef); + cmap = mapper.readValue(jsonInput, typeRef); - Assert.assertEquals(new MyPair("Comedy", "1940s"), - cmap.get(new MyPair("Abbott", "Costello"))); - } + Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello"))); + } } 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 index 81bb14c533..96dbff6f3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jacksoninject/JacksonInjectUnitTest.java @@ -27,7 +27,9 @@ public class JacksonInjectUnitTest { // act InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id); - Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson); + Author author = new ObjectMapper().reader(inject) + .forType(Author.class) + .readValue(authorJson); // assert assertThat(author.getId()).isEqualTo(id); 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 index 7c338696e7..2e1f94bc3c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonanysetter/JsonAnySetterUnitTest.java @@ -23,15 +23,28 @@ public class JsonAnySetterUnitTest { 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); + 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")); + 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 index cc6b2a28aa..cc245dab66 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -20,14 +20,11 @@ public class JsonCreatorUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { // arrange - String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + String authorJson = "{" + " \"christianName\": \"Alex\"," + " \"surname\": \"Theedom\"" + "}"; // act - final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); + final Author author = new ObjectMapper().readerFor(Author.class) + .readValue(authorJson); // assert assertThat(from(authorJson).getString("christianName")).isEqualTo(author.getFirstName()); 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 index dca2252431..1bcde998d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsondeserialize/JsonDeserializeUnitTest.java @@ -24,7 +24,8 @@ public class JsonDeserializeUnitTest { 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); + Book book = new ObjectMapper().readerFor(Book.class) + .readValue(bookJson); // assert SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 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 index 42e105cd52..4379fe376c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/jsonsetter/JsonSetterUnitTest.java @@ -23,10 +23,13 @@ public class JsonSetterUnitTest { String json = "{\"firstName\":\"Alex\",\"lastName\":\"Theedom\",\"publications\":[{\"title\":\"Professional Java EE Design Patterns\"}]}"; // act - Author author = new ObjectMapper().readerFor(Author.class).readValue(json); + Author author = new ObjectMapper().readerFor(Author.class) + .readValue(json); // assert - assertThat(from(json).getList("publications").size()).isEqualTo(author.getItems().size()); + 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/dynamicIgnore/Address.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java index c2d2e84d45..daca85f66a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Address.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Address implements Hidable { private String city; private String country; diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java index edca786432..a32e6844a6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Hidable.java @@ -2,7 +2,6 @@ package com.baeldung.jackson.dynamicIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - @JsonIgnoreProperties("hidden") public interface Hidable { boolean isHidden(); diff --git a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java index 366f611edf..daa62b4be6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/dynamicIgnore/Person.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.dynamicIgnore; - public class Person implements Hidable { private String name; private Address address; @@ -13,7 +12,6 @@ public class Person implements Hidable { this.hidden = hidden; } - public String getName() { return name; } @@ -29,6 +27,7 @@ public class Person implements Hidable { public void setAddress(final Address address) { this.address = address; } + @Override public boolean isHidden() { return hidden; diff --git a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java index 7ce03ff625..cf166fdc36 100755 --- a/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java @@ -22,18 +22,16 @@ public class JsonFormatUnitTest { @Test public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException { - User user = new User("Jay", "Sridhar"); + User user = new User("Jay", "Sridhar"); - String result = new ObjectMapper().writeValueAsString(user); + String result = new ObjectMapper().writeValueAsString(user); - // Expected to match: "2016-12-19@09:34:42.628+0000" - assertThat(from(result).getString("createdDate")) - .matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); + // Expected to match: "2016-12-19@09:34:42.628+0000" + assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); - // Expected to be close to current time - long now = new Date().getTime(); - assertThat(from(result).getLong("dateNum")) - .isCloseTo(now, withPercentage(10.0)); + // Expected to be close to current time + long now = new Date().getTime(); + assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0)); } } 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 index 3eeec8dcee..6fcc57faa7 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonfilter/JsonFilterUnitTest.java @@ -23,11 +23,11 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); - FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + FilterProvider filters = new SimpleFilterProvider().addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act - String result = new ObjectMapper().writer(filters).writeValueAsString(author); + String result = new ObjectMapper().writer(filters) + .writeValueAsString(author); // assert assertThat(from(result).getList("items")).isNull(); 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 index cacd11c804..e2eb4aa48a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/Book.java @@ -17,9 +17,7 @@ public class Book extends Item { private String ISBN; - @JsonFormat( - shape = JsonFormat.Shape.STRING, - pattern = "dd-MM-yyyy HH:mm:ss") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss") private Date published; private BigDecimal 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 index 0fcfe94cf8..1fe217cef6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonformat/JsonFormatUnitTest.java @@ -31,10 +31,7 @@ public class JsonFormatUnitTest { 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 book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.setPublished(date); // act 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 index ebe1a69c4e..1f36b95b2a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Author.java @@ -12,9 +12,7 @@ import java.util.List; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Author extends Person { private List items = new ArrayList<>(); 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 index 3db6d3dddb..80dd9c275e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonidentityinfo; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); 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 index f252da4b1b..bad6562122 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Item.java @@ -13,9 +13,7 @@ import java.util.UUID; * @author Alex Theedom www.readlearncode.com * @version 1.0 */ -@JsonIdentityInfo( - generator = ObjectIdGenerators.PropertyGenerator.class, - property = "id") +@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Item { private UUID id; @@ -23,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index 8a5b4b75e1..ea80814124 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonidentityinfo/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); 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 index 1deae26b21..d7ee430d51 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/Item.java @@ -19,7 +19,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index 94046f8a56..0b88e7fc47 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonproperty/JsonPropertyUnitTest.java @@ -21,10 +21,7 @@ public class JsonPropertyUnitTest { public void whenSerializingUsingJsonProperty_thenCorrect() throws JsonProcessingException { // arrange - Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") - ); + Book book = new Book("Design Patterns: Elements of Reusable Object-oriented Software", new Author("The", "GoF")); book.configureBinding("Hardback"); // act @@ -62,12 +59,12 @@ public class JsonPropertyUnitTest { 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); + 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 index 491f706db4..5130e037d5 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonunwrapped/JsonUnwrappedUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.jsonunwrapped; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; 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 index 8ac10cac8b..ab609008ce 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/jsonview/JsonViewUnitTest.java @@ -22,7 +22,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -49,7 +50,8 @@ public class JsonViewUnitTest { Order order = new Order(120); // act - String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(order); + String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(order); // assert assertThat(from(result).getUUID("id")).isNotNull(); @@ -68,5 +70,4 @@ public class JsonViewUnitTest { } - } \ No newline at end of file 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 index 9d99d632e7..251d25a517 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Course.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.general.reference; - import java.util.List; /** @@ -11,7 +10,9 @@ import java.util.List; */ public class Course extends Item { - public enum Medium {CLASSROOM, ONLINE} + public enum Medium { + CLASSROOM, ONLINE + } public enum Level { BEGINNER("Beginner", 1), INTERMEDIATE("Intermediate", 2), ADVANCED("Advanced", 3); 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 index 08bada3646..5dd66a8ca3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Item.java @@ -21,7 +21,8 @@ public class Item { private List authors = new ArrayList<>(); private float price; - public Item(){} + public Item() { + } public Item(String title, Author author) { this.id = UUID.randomUUID(); 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 index 5bb20f7aff..95c0b35b8b 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/Person.java @@ -14,7 +14,8 @@ public class Person { private String firstName; private String lastName; - public Person(){} + public Person() { + } public Person(String firstName, String lastName) { this.id = UUID.randomUUID(); 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 index c0aece9636..7a52a69656 100644 --- a/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/general/reference/ReferenceUnitTest.java @@ -36,7 +36,7 @@ public class ReferenceUnitTest { /* Without references defined it throws StackOverflowError. Authors excluded. - + { "id": "9c45d9b3-4888-4c24-8b74-65ef35627cd7", "firstName": "Alex", 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 index ef9d6e0e29..a3e29776a9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsonautodetect/JsonAutoDetectUnitTest.java @@ -37,7 +37,7 @@ public class JsonAutoDetectUnitTest { }, "internalAudit": 1234567890 } - + Without @JsonAutoDetect { "id": "c94774d9-de8f-4244-85d5-624bd3a4567a", 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 index f85dd66764..ca4c4b751a 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inclusion/jsoninclude/JsonIncludeUnitTest.java @@ -28,7 +28,6 @@ public class JsonIncludeUnitTest { assertThat(from(result).getString("firstName")).isEqualTo("Alex"); assertThat(result).doesNotContain("lastName"); - /* { "id": "e8bb4802-6e0c-4fa5-9f68-c233272399cd", diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java index a0ba23fb71..0f312ec37e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java @@ -12,29 +12,29 @@ import static org.junit.Assert.assertTrue; public class ItemIdRemovedFromUserUnitTest { @Test public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException { - //given + // given Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); String eventJson = objectMapper.writeValueAsString(event); - //when + // when Event result = new ObjectMapper().readValue(eventJson, Event.class); - //then + // then assertTrue(result instanceof ItemIdRemovedFromUser); assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId()); } @Test public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException { - //given + // given Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L); ObjectMapper objectMapper = new ObjectMapper(); - //when + // when String eventJson = objectMapper.writeValueAsString(event); - //then + // then assertFalse(eventJson.contains("id")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java index a8c1e94e9b..b5b81fa4a3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/SubTypeHandlingUnitTest.java @@ -21,12 +21,12 @@ public class SubTypeHandlingUnitTest { assertEquals("Mercedes-Benz", truck.getMake()); assertEquals("S500", truck.getModel()); } - + @Test - public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException{ + public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); - + SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0); SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0); diff --git a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java index b436eda6e0..02297b9ee8 100644 --- a/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/inheritance/TypeInfoInclusionUnitTest.java @@ -30,8 +30,10 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoStructure.Truck.class)); } @Test @@ -51,7 +53,9 @@ public class TypeInfoInclusionUnitTest { String jsonDataString = mapper.writeValueAsString(serializedFleet); TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class); - assertThat(deserializedFleet.getVehicles().get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); - assertThat(deserializedFleet.getVehicles().get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); + assertThat(deserializedFleet.getVehicles() + .get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); + assertThat(deserializedFleet.getVehicles() + .get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java index 14f9024d0b..a472c7af15 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/ExampleStructure.java @@ -10,7 +10,8 @@ public class ExampleStructure { private static ObjectMapper mapper = new ObjectMapper(); static JsonNode getExampleRoot() throws IOException { - InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json"); + InputStream exampleInput = ExampleStructure.class.getClassLoader() + .getResourceAsStream("node_example.json"); JsonNode rootNode = mapper.readTree(exampleInput); return rootNode; } diff --git a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java index 3539f388f9..73328f465e 100644 --- a/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/node/NodeOperationUnitTest.java @@ -28,8 +28,10 @@ public class NodeOperationUnitTest { final JsonNode node = mapper.valueToTree(fromValue); - assertEquals(2016, node.get("id").intValue()); - assertEquals("baeldung.com", node.get("name").textValue()); + assertEquals(2016, node.get("id") + .intValue()); + assertEquals("baeldung.com", node.get("name") + .textValue()); } @Test @@ -72,12 +74,21 @@ public class NodeOperationUnitTest { public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException { final JsonNode rootNode = ExampleStructure.getExampleRoot(); final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address"); - addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States"); + addedNode.put("city", "Seattle") + .put("state", "Washington") + .put("country", "United States"); - assertFalse(rootNode.path("address").isMissingNode()); - assertEquals("Seattle", rootNode.path("address").path("city").textValue()); - assertEquals("Washington", rootNode.path("address").path("state").textValue()); - assertEquals("United States", rootNode.path("address").path("country").textValue()); + assertFalse(rootNode.path("address") + .isMissingNode()); + assertEquals("Seattle", rootNode.path("address") + .path("city") + .textValue()); + assertEquals("Washington", rootNode.path("address") + .path("state") + .textValue()); + assertEquals("United States", rootNode.path("address") + .path("country") + .textValue()); } @Test @@ -88,8 +99,12 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).set("name", newNode); - assertFalse(rootNode.path("name").path("nick").isMissingNode()); - assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue()); + assertFalse(rootNode.path("name") + .path("nick") + .isMissingNode()); + assertEquals("cowtowncoder", rootNode.path("name") + .path("nick") + .textValue()); } @Test @@ -97,7 +112,8 @@ public class NodeOperationUnitTest { final JsonNode rootNode = ExampleStructure.getExampleRoot(); ((ObjectNode) rootNode).remove("company"); - assertTrue(rootNode.path("company").isMissingNode()); + assertTrue(rootNode.path("company") + .isMissingNode()); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java index a3d0b377c6..10b22b8365 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarDeserializer.java @@ -25,8 +25,6 @@ public class CustomCarDeserializer extends StdDeserializer { super(vc); } - - @Override public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { final Car car = new Car(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java index 37bae829b7..9db09c5081 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/CustomCarSerializer.java @@ -8,8 +8,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -public class CustomCarSerializer extends StdSerializer -{ +public class CustomCarSerializer extends StdSerializer { private static final long serialVersionUID = 1396140685442227917L; @@ -22,8 +21,7 @@ public class CustomCarSerializer extends StdSerializer } @Override - public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException - { + public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("model: ", car.getType()); jsonGenerator.writeEndObject(); diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java index e6da19f440..2745e4f767 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java @@ -40,7 +40,8 @@ public class JavaReadWriteJsonExampleUnitTest { final ObjectMapper objectMapper = new ObjectMapper(); final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON); assertNotNull(jsonNode); - assertThat(jsonNode.get("color").asText(), containsString("Black")); + assertThat(jsonNode.get("color") + .asText(), containsString("Black")); } @Test diff --git a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java index 4ffec72a61..fcfee98123 100644 --- a/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -public class SerializationDeserializationFeatureUnitTest { +public class SerializationDeserializationFeatureUnitTest { final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }"; final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; diff --git a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java index 5d2ba69767..e922cf9976 100644 --- a/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/polymorphism/PolymorphismUnitTest.java @@ -53,12 +53,14 @@ public class PolymorphismUnitTest { String orderJson = "{\"type\":{\"ordertype\":\"internal\",\"id\":100,\"name\":\"directors\"}}"; // act - Order order = new ObjectMapper().readerFor(Order.class).readValue(orderJson); + Order order = new ObjectMapper().readerFor(Order.class) + .readValue(orderJson); - // assert + // 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); + assertThat(order.getType() + .getClass()).isEqualTo(Order.InternalType.class); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java index a68af20f15..a75e8ef831 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/JacksonPrettyPrintUnitTest.java @@ -33,7 +33,8 @@ public class JacksonPrettyPrintUnitTest { final ObjectMapper mapper = new ObjectMapper(); try { final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class); - System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); + System.out.println(mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(json)); } catch (final IOException e) { e.printStackTrace(); } @@ -42,7 +43,8 @@ public class JacksonPrettyPrintUnitTest { static String readFile(final String path, final Charset encoding) throws IOException { final byte[] encoded = Files.readAllBytes(Paths.get(path)); - return encoding.decode(ByteBuffer.wrap(encoded)).toString(); + return encoding.decode(ByteBuffer.wrap(encoded)) + .toString(); } } diff --git a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java index a600577cb0..6f22e2fa01 100644 --- a/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/sandbox/SandboxUnitTest.java @@ -17,7 +17,10 @@ public class SandboxUnitTest { testElement.setX(10); testElement.setY("adasd"); final ObjectMapper om = new ObjectMapper(); - om.setVisibilityChecker(om.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)); + om.setVisibility(om.getSerializationConfig() + .getDefaultVisibilityChecker() + .withFieldVisibility(JsonAutoDetect.Visibility.ANY) + .withGetterVisibility(JsonAutoDetect.Visibility.NONE)); final String serialized = om.writeValueAsString(testElement); System.err.println(serialized); diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java index 4935d35791..e67336f6f3 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonMapSerializeUnitTest.java @@ -14,57 +14,53 @@ import com.fasterxml.jackson.databind.ser.std.MapSerializer; public class JacksonMapSerializeUnitTest { - @JsonSerialize(keyUsing = MyPairSerializer.class) - private Map map; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private Map map; - @JsonSerialize(keyUsing = MapSerializer.class) - private Map cmap; + @JsonSerialize(keyUsing = MapSerializer.class) + private Map cmap; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapKey; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapKey; - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapValue; + @JsonSerialize(keyUsing = MyPairSerializer.class) + private MyPair mapValue; - final ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); - @Test - public void whenSimpleMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException { - Map map = new HashMap<>(); - map.put("key", "value"); + Map map = new HashMap<>(); + map.put("key", "value"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"key\":\"value\"}", jsonResult); - } + Assert.assertEquals("{\"key\":\"value\"}", jsonResult); + } - @Test - public void whenCustomObjectStringMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException { - map = new HashMap<>(); - MyPair key = new MyPair("Abbott", "Costello"); - map.put(key, "Comedy"); + map = new HashMap<>(); + MyPair key = new MyPair("Abbott", "Costello"); + map.put(key, "Comedy"); - final String jsonResult = mapper.writeValueAsString(map); + final String jsonResult = mapper.writeValueAsString(map); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); + } - @Test - public void whenCustomObjectObjectMapSerialize_thenCorrect() - throws JsonProcessingException { + @Test + public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException { - cmap = new HashMap<>(); - mapKey = new MyPair("Abbott", "Costello"); - mapValue = new MyPair("Comedy", "1940's"); - cmap.put(mapKey, mapValue); + cmap = new HashMap<>(); + mapKey = new MyPair("Abbott", "Costello"); + mapValue = new MyPair("Comedy", "1940's"); + cmap.put(mapKey, mapValue); - final String jsonResult = mapper.writeValueAsString(cmap); + final String jsonResult = mapper.writeValueAsString(cmap); - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", - jsonResult); - } + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult); + } } diff --git a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java index fa6364ff92..a003c5b526 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/JacksonSerializeUnitTest.java @@ -48,10 +48,13 @@ public class JacksonSerializeUnitTest { module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); final ObjectMapper mapper = new ObjectMapper(); - final String jsonResult = mapper.registerModule(module).writer(new DefaultPrettyPrinter()).writeValueAsString(movieWithNullValue); + final String jsonResult = mapper.registerModule(module) + .writer(new DefaultPrettyPrinter()) + .writeValueAsString(movieWithNullValue); final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(json); + final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) + .writeValueAsString(json); Assert.assertEquals(jsonResult, expectedOutput); } 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 index 0671441d9a..f0f0913aee 100644 --- a/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/serialization/jsonrawvalue/JsonRawValueUnitTest.java @@ -28,7 +28,6 @@ public class JsonRawValueUnitTest { // assert assertThat(result.contains(customerConfig)); - /* { "firstName": "Alex", diff --git a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java index 2f8cf52afb..ff22682f37 100644 --- a/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/streaming/JacksonStreamingAPIUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.jackson.streaming; - import com.fasterxml.jackson.core.*; import org.junit.Test; @@ -18,12 +17,12 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException { - //given + // given ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8); - //when + // when jGenerator.writeStartObject(); jGenerator.writeStringField("name", "Tom"); jGenerator.writeNumberField("age", 25); @@ -35,14 +34,14 @@ public class JacksonStreamingAPIUnitTest { jGenerator.writeEndObject(); jGenerator.close(); - //then + // then String json = new String(stream.toByteArray(), "UTF-8"); assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"); } @Test public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -51,7 +50,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -78,7 +77,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertEquals(parsedName, "Tom"); assertEquals(parsedAge, (Integer) 25); assertEquals(addresses, Arrays.asList("Poland", "5th avenue")); @@ -87,7 +86,7 @@ public class JacksonStreamingAPIUnitTest { @Test public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException { - //given + // given String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; JsonFactory jfactory = new JsonFactory(); JsonParser jParser = jfactory.createParser(json); @@ -96,7 +95,7 @@ public class JacksonStreamingAPIUnitTest { Integer parsedAge = null; List addresses = new LinkedList<>(); - //when + // when while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); @@ -110,7 +109,7 @@ public class JacksonStreamingAPIUnitTest { } jParser.close(); - //then + // then assertNull(parsedName); assertEquals(parsedAge, (Integer) 25); assertTrue(addresses.isEmpty()); 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 e544ab670a..935777bad1 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonAnnotationUnitTest.java @@ -124,7 +124,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { final String json = "{\"id\":1,\"theName\":\"My bean\"}"; - final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json); + final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class) + .readValue(json); assertEquals("My bean", bean.name); } @@ -133,7 +134,9 @@ public class JacksonAnnotationUnitTest { final String json = "{\"name\":\"My bean\"}"; final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); - final BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json); + final BeanWithInject bean = new ObjectMapper().reader(inject) + .forType(BeanWithInject.class) + .readValue(json); assertEquals("My bean", bean.name); assertEquals(1, bean.id); } @@ -142,16 +145,19 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}"; - final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json); + final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class) + .readValue(json); assertEquals("My bean", bean.name); - assertEquals("val2", bean.getProperties().get("attr2")); + assertEquals("val2", bean.getProperties() + .get("attr2")); } @Test public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"My bean\"}"; - final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json); + final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(json); assertEquals("My bean", bean.getTheName()); } @@ -161,7 +167,8 @@ public class JacksonAnnotationUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -232,7 +239,8 @@ public class JacksonAnnotationUnitTest { public void whenDeserializingPolymorphic_thenCorrect() throws IOException { final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}"; - final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json); + final Zoo zoo = new ObjectMapper().readerFor(Zoo.class) + .readValue(json); assertEquals("lacy", zoo.animal.name); assertEquals(Zoo.Cat.class, zoo.animal.getClass()); @@ -247,7 +255,8 @@ public class JacksonAnnotationUnitTest { assertThat(result, containsString("My bean")); assertThat(result, containsString("1")); - final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(result); + final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class) + .readValue(result); assertEquals("My bean", resultBean.getTheName()); } @@ -278,7 +287,8 @@ public class JacksonAnnotationUnitTest { public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException { final Item item = new Item(2, "book", "John"); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -317,7 +327,8 @@ public class JacksonAnnotationUnitTest { final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); - final String result = new ObjectMapper().writer(filters).writeValueAsString(bean); + final String result = new ObjectMapper().writer(filters) + .writeValueAsString(bean); assertThat(result, containsString("My bean")); assertThat(result, not(containsString("id"))); diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java index 523b42a96c..e55ca55ac9 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonBidirectionRelationUnitTest.java @@ -93,7 +93,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class).readValue(json); + final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); @@ -104,7 +105,8 @@ public class JacksonBidirectionRelationUnitTest { public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException { final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class).readValue(json); + final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class) + .readValue(json); assertEquals(2, item.id); assertEquals("book", item.itemName); assertEquals("John", item.owner.name); @@ -116,7 +118,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - final String result = new ObjectMapper().writerWithView(Views.Public.class).writeValueAsString(item); + final String result = new ObjectMapper().writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("John")); @@ -129,7 +132,8 @@ public class JacksonBidirectionRelationUnitTest { final ItemWithView item = new ItemWithView(2, "book", user); user.addItem(item); - new ObjectMapper().writerWithView(Views.Internal.class).writeValueAsString(item); + new ObjectMapper().writerWithView(Views.Internal.class) + .writeValueAsString(item); } } \ No newline at end of file diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java index cd166386e6..0de3a1de82 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonCollectionDeserializationUnitTest.java @@ -66,7 +66,8 @@ public class JacksonCollectionDeserializationUnitTest { final String jsonArray = mapper.writeValueAsString(listOfDtos); // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - final CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, MyDto.class); + final CollectionType javaType = mapper.getTypeFactory() + .constructCollectionType(List.class, MyDto.class); final List asList = mapper.readValue(jsonArray, javaType); assertThat(asList.get(0), instanceOf(MyDto.class)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java index f713494ac8..390030d0d4 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java @@ -130,7 +130,8 @@ public class JacksonDateUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); - final Event event = mapper.readerFor(Event.class).readValue(json); + final Event event = mapper.readerFor(Event.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } @@ -141,7 +142,8 @@ public class JacksonDateUnitTest { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); final ObjectMapper mapper = new ObjectMapper(); - final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class).readValue(json); + final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class) + .readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java index 45d957b90b..035ff8ca9c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java @@ -1,19 +1,23 @@ package com.baeldung.jackson.test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; import com.baeldung.jackson.deserialization.ItemDeserializer; import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.MyDto; import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown; -import org.junit.Test; - import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; @@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -165,4 +170,35 @@ public class JacksonDeserializationUnitTest { assertThat(readValue, notNullValue()); } + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(not(restored))); + } + + @Test + public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } + } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java index 4549a752eb..cd2c2925d6 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonExceptionsUnitTest.java @@ -34,7 +34,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(Zoo.class).readValue(json); + mapper.reader() + .forType(Zoo.class) + .readValue(json); } @Test @@ -42,7 +44,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"animal\":{\"name\":\"lacy\"}}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(ZooConfigured.class).readValue(json); + mapper.reader() + .forType(ZooConfigured.class) + .readValue(json); } // JsonMappingException: No serializer found for class @@ -51,7 +55,8 @@ public class JacksonExceptionsUnitTest { final UserWithPrivateFields user = new UserWithPrivateFields(1, "John"); final ObjectMapper mapper = new ObjectMapper(); - mapper.writer().writeValueAsString(user); + mapper.writer() + .writeValueAsString(user); } @Test @@ -61,7 +66,8 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - final String result = mapper.writer().writeValueAsString(user); + final String result = mapper.writer() + .writeValueAsString(user); assertThat(result, containsString("John")); } @@ -71,7 +77,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(User.class).readValue(json); + mapper.reader() + .forType(User.class) + .readValue(json); } @Test @@ -79,7 +87,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\"}"; final ObjectMapper mapper = new ObjectMapper(); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -91,7 +101,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -101,7 +113,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - final UserWithRoot user = mapper.reader().forType(UserWithRoot.class).readValue(json); + final UserWithRoot user = mapper.reader() + .forType(UserWithRoot.class) + .readValue(json); assertEquals("John", user.name); } @@ -111,7 +125,9 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -119,8 +135,10 @@ public class JacksonExceptionsUnitTest { final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; final ObjectMapper mapper = new ObjectMapper(); - final List users = mapper.reader().forType(new TypeReference>() { - }).readValue(json); + final List users = mapper.reader() + .forType(new TypeReference>() { + }) + .readValue(json); assertEquals(2, users.size()); } @@ -131,7 +149,9 @@ public class JacksonExceptionsUnitTest { final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -141,7 +161,9 @@ public class JacksonExceptionsUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } @@ -151,7 +173,9 @@ public class JacksonExceptionsUnitTest { final String json = "{'id':1,'name':'John'}"; final ObjectMapper mapper = new ObjectMapper(); - mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); } @Test @@ -162,7 +186,9 @@ public class JacksonExceptionsUnitTest { factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); final ObjectMapper mapper = new ObjectMapper(factory); - final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json); + final com.baeldung.jackson.dtos.User user = mapper.reader() + .forType(com.baeldung.jackson.dtos.User.class) + .readValue(json); assertEquals("John", user.name); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java index dd2690876c..7930195ab0 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonJsonViewUnitTest.java @@ -28,7 +28,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("1"))); @@ -39,7 +40,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -52,7 +54,8 @@ public class JacksonJsonViewUnitTest { final Item item = new Item(2, "book", "John"); final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Internal.class).writeValueAsString(item); + final String result = mapper.writerWithView(Views.Internal.class) + .writeValueAsString(item); assertThat(result, containsString("book")); assertThat(result, containsString("2")); @@ -66,7 +69,9 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); - final User user = mapper.readerWithView(Views.Public.class).forType(User.class).readValue(json); + final User user = mapper.readerWithView(Views.Public.class) + .forType(User.class) + .readValue(json); assertEquals(1, user.getId()); assertEquals("John", user.getName()); } @@ -79,7 +84,8 @@ public class JacksonJsonViewUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(serializerFactory); - final String result = mapper.writerWithView(Views.Public.class).writeValueAsString(user); + final String result = mapper.writerWithView(Views.Public.class) + .writeValueAsString(user); assertThat(result, containsString("JOHN")); assertThat(result, containsString("1")); } diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 71499b8a24..4230420132 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.FilterProvider; @@ -110,7 +109,8 @@ public class JacksonSerializationIgnoreUnitTest { final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); dtoObject.setIntValue(12); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -124,7 +124,8 @@ public class JacksonSerializationIgnoreUnitTest { @Override public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception { if (include(writer)) { - if (!writer.getName().equals("intValue")) { + if (!writer.getName() + .equals("intValue")) { writer.serializeAsField(pojo, jgen, provider); return; } @@ -154,7 +155,8 @@ public class JacksonSerializationIgnoreUnitTest { dtoObject.setIntValue(-1); final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject); + final String dtoAsString = mapper.writer(filters) + .writeValueAsString(dtoObject); assertThat(dtoAsString, not(containsString("intValue"))); assertThat(dtoAsString, containsString("booleanValue")); @@ -194,7 +196,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + // mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject1 = new MyDto(); @@ -229,7 +232,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObjectString1"); @@ -251,7 +255,8 @@ public class JacksonSerializationIgnoreUnitTest { @Test public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer()); + mapper.getSerializerProvider() + .setNullKeySerializer(new MyDtoNullKeySerializer()); final MyDto dtoObject1 = new MyDto(); dtoObject1.setStringValue("dtoObject1String"); diff --git a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java index 529c05ddcc..52bb65033f 100644 --- a/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java +++ b/jackson/src/test/java/com/baeldung/jackson/try1/RestLoaderRequestDeserializer.java @@ -25,8 +25,10 @@ public class RestLoaderRequestDeserializer extends StdDeserializer clazz = Class.forName(className); diff --git a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java index b5e3449c68..adb0fe0413 100644 --- a/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/xml/XMLSerializeDeserializeUnitTest.java @@ -35,8 +35,7 @@ public class XMLSerializeDeserializeUnitTest { @Test public void whenJavaGotFromXmlStr_thenCorrect() throws IOException { XmlMapper xmlMapper = new XmlMapper(); - SimpleBean value = xmlMapper.readValue( - "12", SimpleBean.class); + SimpleBean value = xmlMapper.readValue("12", SimpleBean.class); assertTrue(value.getX() == 1 && value.getY() == 2); } diff --git a/java-difference-date/README.md b/java-difference-date/README.md new file mode 100644 index 0000000000..2a024c27a2 --- /dev/null +++ b/java-difference-date/README.md @@ -0,0 +1,5 @@ +## Relevant articles: + +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) \ No newline at end of file diff --git a/java-difference-date/pom.xml b/java-difference-date/pom.xml new file mode 100644 index 0000000000..388753de90 --- /dev/null +++ b/java-difference-date/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + com.baeldung + java-difference-date + 0.0.1-SNAPSHOT + jar + + java-difference-date + Difference between two dates in java + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + joda-time + joda-time + ${joda-time.version} + + + com.darwinsys + hirondelle-date4j + ${hirondelle-date4j.version} + + + junit + junit + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + 1.8 + 4.12 + 2.9.9 + 1.5.1 + + diff --git a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java b/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java new file mode 100644 index 0000000000..4203f7ef38 --- /dev/null +++ b/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java @@ -0,0 +1,61 @@ +package com.baeldung; + +import org.joda.time.DateTime; +import org.junit.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; + +public class DateDiffTest { + @Test + public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); + Date firstDate = sdf.parse("06/24/2017"); + Date secondDate = sdf.parse("06/30/2017"); + + long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime()); + long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { + ZonedDateTime now = ZonedDateTime.now(); + ZonedDateTime sixDaysBehind = now.minusDays(6); + + Duration duration = Duration.between(now, sixDaysBehind); + long diff = Math.abs(duration.toDays()); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { + DateTime now = DateTime.now(); + DateTime sixDaysBehind = now.minusDays(6); + + org.joda.time.Duration duration = new org.joda.time.Duration(now, sixDaysBehind); + long diff = Math.abs(duration.getStandardDays()); + + assertEquals(diff, 6); + } + + @Test + public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix() { + hirondelle.date4j.DateTime now = hirondelle.date4j.DateTime.now(TimeZone.getDefault()); + hirondelle.date4j.DateTime sixDaysBehind = now.minusDays(6); + + long diff = Math.abs(now.numDaysFrom(sixDaysBehind)); + + assertEquals(diff, 6); + } +} \ No newline at end of file diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index 1934102c68..7407666309 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -39,7 +39,7 @@ 3.1.0 - 4.5.2 + 4.5.3
\ No newline at end of file diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java index dca725ae32..120a555c5b 100644 --- a/javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java +++ b/javax-servlets/src/test/java/com/baeldung/servlets/FormServletLiveTest.java @@ -1,24 +1,24 @@ package com.baeldung.servlets; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + public class FormServletLiveTest { @Test public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception { - HttpClient client = new DefaultHttpClient(); + HttpClient client = HttpClientBuilder.create().build(); HttpPost method = new HttpPost("http://localhost:8080/calculateServlet"); List nvps = new ArrayList<>(); diff --git a/jee7/.gitignore b/jee7/.gitignore new file mode 100644 index 0000000000..067348b3f4 --- /dev/null +++ b/jee7/.gitignore @@ -0,0 +1,5 @@ + +/classes/ +/.idea/ +/target/ +/jee7.iml diff --git a/jee7/pom.xml b/jee7/pom.xml index b5e0d80b6c..6858a05d17 100644 --- a/jee7/pom.xml +++ b/jee7/pom.xml @@ -6,8 +6,10 @@ com.baeldung jee7 1.0-SNAPSHOT + war JavaEE 7 Arquillian Archetype Sample + com.baeldung parent-modules @@ -174,6 +176,7 @@ maven-war-plugin ${maven-war-plugin.version} + webapp false diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee7/src/main/webapp/WEB-INF/spring/security.xml new file mode 100644 index 0000000000..777cd9461f --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/spring/security.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml index 11bd87cf99..1bcbb96e24 100644 --- a/jee7/src/main/webapp/WEB-INF/web.xml +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -32,6 +32,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + index.jsf welcome.jsf diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 0000000000..93fef9713d --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,11 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Index Page + + + Non-secured Index Page +
+
Login + + \ No newline at end of file diff --git a/jee7/src/main/webapp/secure.jsp b/jee7/src/main/webapp/secure.jsp new file mode 100644 index 0000000000..0cadd2cd4f --- /dev/null +++ b/jee7/src/main/webapp/secure.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> + + + + + Home Page + + +

Home Page

+ +

+ Hello
+ Roles: +

+ +
+ + +
+ + \ No newline at end of file diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java index bf88b8aff1..4462c012e3 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/JWTCsrfTokenRepository.java @@ -16,7 +16,8 @@ import java.util.UUID; public class JWTCsrfTokenRepository implements CsrfTokenRepository { - private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN"); + private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName() + .concat(".CSRF_TOKEN"); private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class); private byte[] secret; @@ -27,10 +28,12 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { @Override public CsrfToken generateToken(HttpServletRequest request) { - String id = UUID.randomUUID().toString().replace("-", ""); + String id = UUID.randomUUID() + .toString() + .replace("-", ""); Date now = new Date(); - Date exp = new Date(System.currentTimeMillis() + (1000*30)); // 30 seconds + Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds String token = Jwts.builder() .setId(id) @@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository { if (session != null) { session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); } - } - else { + } else { HttpSession session = request.getSession(); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index 94e2c6ddc5..687a827448 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -30,23 +30,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { SecretService secretService; // ordered so we can use binary search below - private String[] ignoreCsrfAntMatchers = { - "/dynamic-builder-compress", - "/dynamic-builder-general", - "/dynamic-builder-specific", - "/set-secrets" - }; + private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; @Override protected void configure(HttpSecurity http) throws Exception { - http - .addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) + http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() - .csrfTokenRepository(jwtCsrfTokenRepository) - .ignoringAntMatchers(ignoreCsrfAntMatchers) - .and().authorizeRequests() - .antMatchers("/**") - .permitAll(); + .csrfTokenRepository(jwtCsrfTokenRepository) + .ignoringAntMatchers(ignoreCsrfAntMatchers) + .and() + .authorizeRequests() + .antMatchers("/**") + .permitAll(); } private class JwtCsrfValidatorFilter extends OncePerRequestFilter { @@ -58,13 +53,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); if ( - // only care if it's a POST - "POST".equals(request.getMethod()) && - // ignore if the request path is in our list + // only care if it's a POST + "POST".equals(request.getMethod()) && + // ignore if the request path is in our list Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && // make sure we have a token - token != null - ) { + token != null) { // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired try { Jwts.parser() diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java index e1e195c6ab..3e2309d43c 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/BaseController.java @@ -11,12 +11,13 @@ import org.springframework.web.bind.annotation.ResponseStatus; public class BaseController { @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler({SignatureException.class, MalformedJwtException.class, JwtException.class}) + @ExceptionHandler({ SignatureException.class, MalformedJwtException.class, JwtException.class }) public JwtResponse exception(Exception e) { JwtResponse response = new JwtResponse(); response.setStatus(JwtResponse.Status.ERROR); response.setMessage(e.getMessage()); - response.setExceptionType(e.getClass().getName()); + response.setExceptionType(e.getClass() + .getName()); return response; } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java index c03c63dd80..3d157827d1 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java @@ -27,25 +27,19 @@ public class DynamicJWTController extends BaseController { @RequestMapping(value = "/dynamic-builder-general", method = POST) public JwtResponse dynamicBuilderGeneric(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @RequestMapping(value = "/dynamic-builder-compress", method = POST) public JwtResponse dynamicBuildercompress(@RequestBody Map claims) throws UnsupportedEncodingException { - String jws = Jwts.builder() + String jws = Jwts.builder() .setClaims(claims) .compressWith(CompressionCodecs.DEFLATE) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @@ -56,36 +50,36 @@ public class DynamicJWTController extends BaseController { claims.forEach((key, value) -> { switch (key) { - case "iss": - ensureType(key, value, String.class); - builder.setIssuer((String) value); - break; - case "sub": - ensureType(key, value, String.class); - builder.setSubject((String) value); - break; - case "aud": - ensureType(key, value, String.class); - builder.setAudience((String) value); - break; - case "exp": - ensureType(key, value, Long.class); - builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "nbf": - ensureType(key, value, Long.class); - builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "iat": - ensureType(key, value, Long.class); - builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); - break; - case "jti": - ensureType(key, value, String.class); - builder.setId((String) value); - break; - default: - builder.claim(key, value); + case "iss": + ensureType(key, value, String.class); + builder.setIssuer((String) value); + break; + case "sub": + ensureType(key, value, String.class); + builder.setSubject((String) value); + break; + case "aud": + ensureType(key, value, String.class); + builder.setAudience((String) value); + break; + case "exp": + ensureType(key, value, Long.class); + builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "nbf": + ensureType(key, value, Long.class); + builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "iat": + ensureType(key, value, Long.class); + builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString())))); + break; + case "jti": + ensureType(key, value, String.class); + builder.setId((String) value); + break; + default: + builder.claim(key, value); } }); @@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController { } private void ensureType(String registeredClaim, Object value, Class expectedType) { - boolean isCorrectType = - expectedType.isInstance(value) || - expectedType == Long.class && value instanceof Integer; + boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer; if (!isCorrectType) { - String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + - registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); + String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass() + .getCanonicalName(); throw new JwtException(msg); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java index 57cd14385e..00bc1fb386 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/HomeController.java @@ -11,22 +11,16 @@ public class HomeController { @RequestMapping("/") public String home(HttpServletRequest req) { String requestUrl = getUrl(req); - return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + - " http " + requestUrl + "/\n\tThis usage message\n\n" + - " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + - " http POST " + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + - " http POST " + requestUrl + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + - " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + - " http " + requestUrl + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + - " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + - " http " + requestUrl + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + - " http POST " + requestUrl + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; + return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST " + + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl + + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=\n\tParse passed in JWT\n\n" + " http " + requestUrl + + "/parser-enforce?jwt=\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl + + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl + + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application."; } private String getUrl(HttpServletRequest req) { - return req.getScheme() + "://" + - req.getServerName() + - ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); + return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort()); } } diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java index 83f5336978..efafa4b1b7 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java @@ -30,12 +30,9 @@ public class StaticJWTController extends BaseController { .setSubject("msilverman") .claim("name", "Micah Silverman") .claim("scope", "admins") - .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) + .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) - .signWith( - SignatureAlgorithm.HS256, - secretService.getHS256SecretBytes() - ) + .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java index 491f003289..a18cad7e71 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/model/JwtResponse.java @@ -16,7 +16,8 @@ public class JwtResponse { SUCCESS, ERROR } - public JwtResponse() {} + public JwtResponse() { + } public JwtResponse(String jwt) { this.jwt = jwt; diff --git a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java index 4311afa592..0165d10c83 100644 --- a/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java +++ b/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java @@ -61,7 +61,6 @@ public class SecretService { return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); } - public Map refreshSecrets() { SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); diff --git a/jmh/pom.xml b/jmh/pom.xml index 8ecfaa9651..ef5c3f1bbf 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -1,52 +1,60 @@ - 4.0.0 - com.baeldung - jmh - jar - 1.0-SNAPSHOT - jmh - http://maven.apache.org + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + jmh + jar + 1.0-SNAPSHOT + jmh + http://maven.apache.org - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + 1.6 + 1.6 + - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - junit - junit - 3.8.1 - test - - + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + junit + junit + 3.8.1 + test + - - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.baeldung.Application - - - - - - + + com.google.guava + guava + 21.0 + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.BenchmarkRunner + + + + + + \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/Application.java b/jmh/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 28e70740e0..0000000000 --- a/jmh/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import java.io.IOException; - -import org.openjdk.jmh.Main; -import org.openjdk.jmh.runner.RunnerException; - -public class Application { - - public static void main(String[] args) throws RunnerException, IOException { - Main.main(args); - } - -} diff --git a/jmh/src/main/java/com/baeldung/BenchMark.java b/jmh/src/main/java/com/baeldung/BenchMark.java index f2b984d211..b0e1caf4dc 100644 --- a/jmh/src/main/java/com/baeldung/BenchMark.java +++ b/jmh/src/main/java/com/baeldung/BenchMark.java @@ -1,12 +1,48 @@ package com.baeldung; -import org.openjdk.jmh.annotations.Benchmark; +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hasher; +import com.google.common.hash.Hashing; +import org.openjdk.jmh.annotations.*; + +import java.nio.charset.Charset; public class BenchMark { - @Benchmark - public void init() { - - } + @State(Scope.Benchmark) + public static class ExecutionPlan { + + @Param({ "100", "200", "300", "500", "1000" }) + public int iterations; + + public Hasher murmur3; + + public String password = "4v3rys3kur3p455w0rd"; + + @Setup(Level.Invocation) + public void setUp() { + murmur3 = Hashing.murmur3_128().newHasher(); + } + } + + @Fork(value = 1, warmups = 1) + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Warmup(iterations = 5) + public void benchMurmur3_128(ExecutionPlan plan) { + + for (int i = plan.iterations; i > 0; i--) { + plan.murmur3.putString(plan.password, Charset.defaultCharset()); + } + + plan.murmur3.hash(); + } + + @Benchmark + @Fork(value = 1, warmups = 1) + @BenchmarkMode(Mode.Throughput) + public void init() { + // Do nothing + } } diff --git a/jmh/src/main/java/com/baeldung/BenchmarkRunner.java b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java new file mode 100644 index 0000000000..ed6a5bb617 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java @@ -0,0 +1,9 @@ +package com.baeldung; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + +} diff --git a/jmh/src/test/java/com/baeldung/AppTest.java b/jmh/src/test/java/com/baeldung/AppTest.java deleted file mode 100644 index c9f61455bd..0000000000 --- a/jmh/src/test/java/com/baeldung/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/jooby/conf/application.conf b/jooby/conf/application.conf new file mode 100644 index 0000000000..2f89e0eb6b --- /dev/null +++ b/jooby/conf/application.conf @@ -0,0 +1,2 @@ +#application.secret = 2o128940921eo298e21 +#db = /url/to/the/datastore \ No newline at end of file diff --git a/jooby/conf/logback.xml b/jooby/conf/logback.xml new file mode 100644 index 0000000000..50733ee6d6 --- /dev/null +++ b/jooby/conf/logback.xml @@ -0,0 +1,42 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + log/jooby.log + + log/jooby.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + log/access.log + + log/access.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %msg%n + + + + + + + + + + + diff --git a/jooby/pom.xml b/jooby/pom.xml new file mode 100644 index 0000000000..1935c646ee --- /dev/null +++ b/jooby/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + jooby + com.baeldung.jooby + 1.0 + jooby + + + org.jooby + modules + 1.1.3 + + + + 1.1.3 + com.baeldung.jooby.App + + + + + org.jooby + jooby-netty + + + org.jooby + jooby-jedis + 1.1.3 + + + ch.qos.logback + logback-classic + + + junit + junit + test + + + io.rest-assured + rest-assured + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + diff --git a/jooby/public/form.html b/jooby/public/form.html new file mode 100644 index 0000000000..a23620812a --- /dev/null +++ b/jooby/public/form.html @@ -0,0 +1,17 @@ + + + + +Insert title here + + +
+ + + + + + +
+ + \ No newline at end of file diff --git a/jooby/public/welcome.html b/jooby/public/welcome.html new file mode 100644 index 0000000000..cd21fb1988 --- /dev/null +++ b/jooby/public/welcome.html @@ -0,0 +1,10 @@ + + + + +Insert title here + + +i m welcomed + + \ No newline at end of file diff --git a/jooby/src/etc/stork.yml b/jooby/src/etc/stork.yml new file mode 100644 index 0000000000..f2f2790cd1 --- /dev/null +++ b/jooby/src/etc/stork.yml @@ -0,0 +1,41 @@ +# Name of application (make sure it has no spaces) +name: "${project.artifactId}" + +# Display name of application (can have spaces) +display_name: "${project.name}" + +# Type of launcher (CONSOLE or DAEMON) +type: DAEMON + +# Java class to run +main_class: "${application.class}" + +domain: "${project.groupId}" + +short_description: "${project.artifactId}" + +# Platform launchers to generate (WINDOWS, LINUX, MAC_OSX) +# Linux launcher is suitable for Bourne shells (e.g. Linux/BSD) +platforms: [ LINUX ] + +# Working directory for app +# RETAIN will not change the working directory +# APP_HOME will change the working directory to the home of the app +# (where it was intalled) before running the main class +working_dir_mode: RETAIN + +# Minimum version of java required (system will be searched for acceptable jvm) +min_java_version: "1.8" + +# Min/max fixed memory (measured in MB) +min_java_memory: 512 +max_java_memory: 512 + +# Min/max memory by percentage of system +#min_java_memory_pct: 10 +#max_java_memory_pct: 20 + +# Try to create a symbolic link to java executable in /run with +# the name of "-java" so that commands like "ps" will make it +# easier to find your app +symlink_java: true diff --git a/jooby/src/main/java/com/baeldung/jooby/App.java b/jooby/src/main/java/com/baeldung/jooby/App.java new file mode 100644 index 0000000000..94a24048c2 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/App.java @@ -0,0 +1,95 @@ +package com.baeldung.jooby; + +import org.jooby.Jooby; +import org.jooby.Mutant; +import org.jooby.Session; +import org.jooby.jedis.Redis; +import org.jooby.jedis.RedisSessionStore; + +import com.baeldung.jooby.bean.Employee; + +public class App extends Jooby { + + { + port(8080); + securePort(8443); + } + + { + get("/", () -> "Hello World!"); + } + + { + get("/user/{id}", req -> "Hello user : " + req.param("id").value()); + get("/user/:id", req -> "Hello user: " + req.param("id").value()); + get("/uid:{id}", req -> "Hello User with id : uid" + req.param("id").value()); + } + + { + onStart(() -> { + System.out.println("starting app"); + }); + + onStop(() -> { + System.out.println("stopping app"); + }); + + onStarted(() -> { + System.out.println("app started"); + }); + } + + { + get("/login", () -> "Hello from Baeldung"); + } + + { + post("/save", req -> { + Mutant token = req.param("token"); + return token.intValue(); + }); + } + + { + { + assets("/employee", "form.html"); + } + + post("/submitForm", req -> { + Employee employee = req.params(Employee.class); + // TODO + return "empoyee data saved successfullly"; + }); + } + + { + get("/filter", (req, resp, chain) -> { + // TODO + // resp.send(...); + chain.next(req, resp); + }); + get("/filter", (req, resp) -> { + resp.send("filter response"); + }); + } + + { +// cookieSession(); + +// use(new Redis()); +// +// session(RedisSessionStore.class); + + get("/session", req -> { + Session session = req.session(); + session.set("token", "value"); + return session.get("token").value(); + }); + } + + public static void main(final String[] args) { + + run(App::new, args); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java new file mode 100644 index 0000000000..2c4a1038b5 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java @@ -0,0 +1,16 @@ +package com.baeldung.jooby.bean; + +public class Employee { + + String id; + String name; + String email; + + public Employee(String id, String name, String email) { + super(); + this.id = id; + this.name = name; + this.email = email; + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java new file mode 100644 index 0000000000..a2c51bae70 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java @@ -0,0 +1,22 @@ +package com.baeldung.jooby.mvc; + +import org.jooby.Result; +import org.jooby.Results; +import org.jooby.mvc.GET; +import org.jooby.mvc.Path; + +@Path("/hello") +public class GetController { + + @GET + public String hello() { + return "Hello Baeldung"; + } + + @GET + @Path("/home") + public Result home() { + return Results.html("welcome").put("model", new Object()); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java new file mode 100644 index 0000000000..df00e47da5 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java @@ -0,0 +1,14 @@ +package com.baeldung.jooby.mvc; + +import org.jooby.mvc.POST; +import org.jooby.mvc.Path; + +@Path("/submit") +public class PostController { + + @POST + public String hello() { + return "Submit Baeldung"; + } + +} diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppTest.java new file mode 100644 index 0000000000..af2626c046 --- /dev/null +++ b/jooby/src/test/java/com/baeldung/jooby/AppTest.java @@ -0,0 +1,29 @@ +package com.baeldung.jooby; + +import static io.restassured.RestAssured.get; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; + +import org.jooby.test.JoobyRule; +import org.jooby.test.MockRouter; +import org.junit.ClassRule; +import org.junit.Test; + +public class AppTest { + + @ClassRule + public static JoobyRule app = new JoobyRule(new App()); + + @Test + public void given_defaultUrl_expect_fixedString() { + get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200) + .contentType("text/html;charset=UTF-8"); + } + + @Test + public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable { + String result = new MockRouter(new App()).get("/"); + assertEquals("Hello World!", result); + } + +} diff --git a/jooq/README.md b/jooq/README.md deleted file mode 100644 index 2f09cab46b..0000000000 --- a/jooq/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to jOOL](http://www.baeldung.com/jool) diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java index c93d59fe30..c0fb5485aa 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java @@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest { public void findCarsByYearNamedProcedure() { final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @Test public void findCarsByYearNoNamed() { - final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015); - storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); + final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class) + .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN) + .setParameter(1, 2015); + storedProcedure.getResultList() + .forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); } @AfterClass diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java index 16d9f80d89..abc1399f88 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -27,18 +27,22 @@ public class ELSampleBean { @PostConstruct public void init() { pageCounter = randomIntGen.nextInt(); - FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { - @Override - public void contextCreated(ELContextEvent evt) { - evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); - } - }); + FacesContext.getCurrentInstance() + .getApplication() + .addELContextListener(new ELContextListener() { + @Override + public void contextCreated(ELContextEvent evt) { + evt.getELContext() + .getImportHandler() + .importClass("com.baeldung.springintegration.controllers.ELSampleBean"); + } + }); } public void save() { } - + public static String constantField() { return constantField; } @@ -48,7 +52,8 @@ public class ELSampleBean { } public Long multiplyValue(LambdaExpression expr) { - Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); + Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance() + .getELContext(), pageCounter); return theResult; } diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java index 56cbdd7b88..d135fba2b7 100644 --- a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java +++ b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java @@ -1,6 +1,5 @@ package com.baeldung.springintegration.dao; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; @@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO { public UserManagementDAOImpl() { } - } diff --git a/json-path/pom.xml b/json-path/pom.xml index e81bc1dcf9..8384ba68ed 100644 --- a/json-path/pom.xml +++ b/json-path/pom.xml @@ -23,6 +23,6 @@ - 2.2.0 + 2.4.0 \ No newline at end of file diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java index cb5c695cd8..7728d2dad6 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/OperationIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.jsonpath.introduction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; - +import com.jayway.jsonpath.Criteria; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.Filter; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Predicate; import org.junit.Test; import java.io.InputStream; @@ -12,15 +12,17 @@ import java.util.List; import java.util.Map; import java.util.Scanner; -import com.jayway.jsonpath.Criteria; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.Filter; -import com.jayway.jsonpath.JsonPath; -import com.jayway.jsonpath.Predicate; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class OperationIntegrationTest { - InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); - String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_api.json"); + private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { @@ -39,26 +41,27 @@ public class OperationIntegrationTest { @Test public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { - Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); + Filter expensiveFilter = Filter.filter(Criteria.where("price") + .gt(20.00)); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensiveFilter); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { - Predicate expensivePredicate = new Predicate() { - public boolean apply(PredicateContext context) { - String value = context.item(Map.class).get("price").toString(); - return Float.valueOf(value) > 20.00; - } - }; - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); + Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class) + .get("price") + .toString()) > 20.00; + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?]", expensivePredicate); predicateUsageAssertionHelper(expensive); } @Test public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { - List> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]"); + List> expensive = JsonPath.parse(jsonDataSourceString) + .read("$['book'][?(@['price'] > $['price range']['medium'])]"); predicateUsageAssertionHelper(expensive); } diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java index 868acac8d0..067e5cf8ce 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java @@ -1,9 +1,9 @@ package com.baeldung.jsonpath.introduction; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.CoreMatchers.containsString; - +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.Option; import org.junit.Test; import java.io.InputStream; @@ -13,18 +13,21 @@ import java.util.List; import java.util.Map; import java.util.Scanner; -import com.jayway.jsonpath.Configuration; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.JsonPath; -import com.jayway.jsonpath.Option; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class ServiceTest { - InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json"); - String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); + private InputStream jsonInputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("intro_service.json"); + private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z") + .next(); @Test public void givenId_whenRequestingRecordData_thenSucceed() { - Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]"); + Object dataObject = JsonPath.parse(jsonString) + .read("$[?(@.id == 2)]"); String dataString = dataObject.toString(); assertThat(dataString, containsString("2")); @@ -34,8 +37,10 @@ public class ServiceTest { @Test public void givenStarring_whenRequestingMovieTitle_thenSucceed() { - List> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]"); - String title = (String) dataList.get(0).get("title"); + List> dataList = JsonPath.parse(jsonString) + .read("$[?('Eva Green' in @['starring'])]"); + String title = (String) dataList.get(0) + .get("title"); assertEquals("Casino Royale", title); } @@ -60,8 +65,12 @@ public class ServiceTest { Arrays.sort(revenueArray); int highestRevenue = revenueArray[revenueArray.length - 1]; - Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); - List pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]"); + Configuration pathConfiguration = Configuration.builder() + .options(Option.AS_PATH_LIST) + .build(); + List pathList = JsonPath.using(pathConfiguration) + .parse(jsonString) + .read("$[?(@['box office'] == " + highestRevenue + ")]"); Map dataRecord = context.read(pathList.get(0)); String title = dataRecord.get("title"); @@ -84,7 +93,8 @@ public class ServiceTest { long latestTime = dateArray[dateArray.length - 1]; List> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); - String title = (String) finalDataList.get(0).get("title"); + String title = (String) finalDataList.get(0) + .get("title"); assertEquals("Spectre", title); } diff --git a/json/src/test/java/fast_json/FastJsonUnitTest.java b/json/src/test/java/fast_json/FastJsonUnitTest.java index e37f443387..6fcf1e398a 100644 --- a/json/src/test/java/fast_json/FastJsonUnitTest.java +++ b/json/src/test/java/fast_json/FastJsonUnitTest.java @@ -32,11 +32,7 @@ public class FastJsonUnitTest { @Test public void whenJavaList_thanConvertToJsonCorrect() { String personJsonFormat = JSON.toJSONString(listOfPersons); - assertEquals( - personJsonFormat, - "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" - + "\"24/07/2016\"}]"); + assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]"); } @Test @@ -44,8 +40,10 @@ public class FastJsonUnitTest { String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); Person newPerson = JSON.parseObject(personJsonFormat, Person.class); assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute - assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); - assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); + assertEquals(newPerson.getFirstName(), listOfPersons.get(0) + .getFirstName()); + assertEquals(newPerson.getLastName(), listOfPersons.get(0) + .getLastName()); } @Test @@ -58,18 +56,13 @@ public class FastJsonUnitTest { jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonArray.add(jsonObject); } - assertEquals( - jsonArray.toString(), - "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" - + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," - + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); + assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]"); } @Test public void givenContextFilter_whenJavaObject_thanJsonCorrect() { ContextValueFilter valueFilter = new ContextValueFilter() { - public Object process(BeanContext context, Object object, - String name, Object value) { + public Object process(BeanContext context, Object object, String name, Object value) { if (name.equals("DATE OF BIRTH")) { return "NOT TO DISCLOSE"; } @@ -87,18 +80,16 @@ public class FastJsonUnitTest { public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { NameFilter formatName = new NameFilter() { public String process(Object object, String name, Object value) { - return name.toLowerCase().replace(" ", "_"); + return name.toLowerCase() + .replace(" ", "_"); } }; - SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); - String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, - "yyyy-MM-dd"); - assertEquals( - jsonOutput, - "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," - + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" - + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); + SerializeConfig.getGlobalInstance() + .addFilter(Person.class, formatName); + String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd"); + assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]"); // resetting custom serializer - SerializeConfig.getGlobalInstance().put(Person.class, null); + SerializeConfig.getGlobalInstance() + .put(Person.class, null); } } diff --git a/json/src/test/java/fast_json/Person.java b/json/src/test/java/fast_json/Person.java index 0eac58cdfd..3d772348a4 100644 --- a/json/src/test/java/fast_json/Person.java +++ b/json/src/test/java/fast_json/Person.java @@ -32,10 +32,9 @@ public class Person { @Override public String toString() { - return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" - + firstName + ", dateOfBirth=" + dateOfBirth + "]"; + return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]"; } - + public int getAge() { return age; } diff --git a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java index dadd57b0ed..ee39f2550f 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/JsoupParserIntegrationTest.java @@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest { @Before public void setUp() throws IOException { - doc = Jsoup.connect("https://spring.io/blog").get(); + doc = Jsoup.connect("https://spring.io/blog") + .get(); } @Test public void loadDocument404() throws IOException { try { - doc = Jsoup.connect("https://spring.io/will-not-be-found").get(); + doc = Jsoup.connect("https://spring.io/will-not-be-found") + .get(); } catch (HttpStatusException ex) { assertEquals(404, ex.getStatusCode()); } @@ -35,13 +37,13 @@ public class JsoupParserIntegrationTest { @Test public void loadDocumentCustomized() throws IOException { doc = Jsoup.connect("https://spring.io/blog") - .userAgent("Mozilla") - .timeout(5000) - .cookie("cookiename", "val234") - .cookie("anothercookie", "ilovejsoup") - .referrer("http://google.com") - .header("headersecurity", "xyz123") - .get(); + .userAgent("Mozilla") + .timeout(5000) + .cookie("cookiename", "val234") + .cookie("anothercookie", "ilovejsoup") + .referrer("http://google.com") + .header("headersecurity", "xyz123") + .get(); } @Test @@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest { @Test public void examplesExtracting() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); - Element sectionDiv = firstArticle.select("section div").first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String sectionDivText = sectionDiv.text(); String articleHtml = firstArticle.html(); String outerHtml = firstArticle.outerHtml(); @@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest { @Test public void examplesModifying() { - Element firstArticle = doc.select("article").first(); - Element timeElement = firstArticle.select("time").first(); - Element sectionDiv = firstArticle.select("section div").first(); + Element firstArticle = doc.select("article") + .first(); + Element timeElement = firstArticle.select("time") + .first(); + Element sectionDiv = firstArticle.select("section div") + .first(); String dateTimeOfFirstArticle = timeElement.attr("datetime"); timeElement.attr("datetime", "2016-12-16 15:19:54.3"); sectionDiv.text("foo bar"); - firstArticle.select("h2").html("
"); + firstArticle.select("h2") + .html("
"); - Element link = new Element(Tag.valueOf("a"), "") - .text("Checkout this amazing website!") - .attr("href", "http://baeldung.com") - .attr("target", "_blank"); + Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!") + .attr("href", "http://baeldung.com") + .attr("target", "_blank"); firstArticle.appendChild(link); - doc.select("li.navbar-link").remove(); - firstArticle.select("img").remove(); + doc.select("li.navbar-link") + .remove(); + firstArticle.select("img") + .remove(); - assertTrue(doc.html().contains("http://baeldung.com")); + assertTrue(doc.html() + .contains("http://baeldung.com")); } } diff --git a/junit5/README.md b/junit5/README.md index c1ff0eab63..49cd8e61a4 100644 --- a/junit5/README.md +++ b/junit5/README.md @@ -4,3 +4,4 @@ - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) +- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) diff --git a/junit5/pom.xml b/junit5/pom.xml index 6cc1405de8..1fa4818447 100644 --- a/junit5/pom.xml +++ b/junit5/pom.xml @@ -3,13 +3,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung + junit5 1.0-SNAPSHOT junit5 Intro to JUnit 5 - + com.baeldung parent-modules @@ -19,16 +19,24 @@ UTF-8 1.8 - 5.0.0-M4 - 1.0.0-M4 - 4.12.0-M4 - 4.12 + 5.0.0-RC2 + 1.0.0-RC2 + 4.12.0-RC2 + 2.8.2 + 1.4.196 3.6.0 2.19.1 + 4.12 + + + src/test/resources + true + + maven-compiler-plugin @@ -49,44 +57,60 @@ + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + com.baeldung.TestLauncher + + - - - junit - junit - ${junit4.version} - test - - - - org.junit.jupiter - junit-jupiter-api - ${junit.jupiter.version} - test - - org.junit.jupiter junit-jupiter-engine ${junit.jupiter.version} test - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + org.apache.logging.log4j + log4j-core + ${log4j2.version} + + + com.h2database + h2 + ${h2.version} + + + junit + junit + ${junit4.version} + test + + + \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java index 504931b3d7..6fefd4e06d 100644 --- a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssertionUnitTest.java @@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test; public class AssertionUnitTest { - @Test - public void testConvertToDoubleThrowException() { - String age = "eighteen"; - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); + @Test + public void testConvertToDoubleThrowException() { + String age = "eighteen"; + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); - assertThrows(NumberFormatException.class, () -> { - convertToInt(age); - }); - } - - private static Integer convertToInt(String str) { - if (str == null) { - return null; - } - return Integer.valueOf(str); - } + assertThrows(NumberFormatException.class, () -> { + convertToInt(age); + }); + } + + private static Integer convertToInt(String str) { + if (str == null) { + return null; + } + return Integer.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java index afeee642eb..7d67d93486 100644 --- a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java @@ -24,9 +24,6 @@ public class AssumptionUnitTest { @Test void assumptionThat() { String someString = "Just a string"; - assumingThat( - someString.equals("Just a string"), - () -> assertEquals(2 + 2, 4) - ); + assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4)); } } diff --git a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java index fd6bb3e0a8..b684f3603f 100644 --- a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java +++ b/junit5/src/test/java/com/baeldung/DynamicTestsExample.java @@ -24,40 +24,33 @@ public class DynamicTestsExample { @TestFactory Collection dynamicTestsWithCollection() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterable dynamicTestsWithIterable() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))); } - + @TestFactory Iterator dynamicTestsWithIterator() { - return Arrays.asList( - DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), - DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) - .iterator(); + return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2)))) + .iterator(); } - + @TestFactory Stream dynamicTestsFromIntStream() { - return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj( - n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); + return IntStream.iterate(0, n -> n + 2) + .limit(10) + .mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); } - + @TestFactory Stream dynamicTestsFromStream() { // sample input and output - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); // input generator that generates inputs using inputList Iterator inputGenerator = inputList.iterator(); @@ -75,57 +68,56 @@ public class DynamicTestsExample { // combine everything and return a Stream of DynamicTest return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor); } - + @TestFactory Stream dynamicTestsFromStreamInJava8() { - + DomainNameResolver resolver = new DomainNameResolver(); - - List inputList = - Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); - List outputList = - Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); - - return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { - int id = inputList.indexOf(dom); - assertEquals(outputList.get(id), resolver.resolveDomain(dom)); - })); - + + List inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); + List outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"); + + return inputList.stream() + .map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { + int id = inputList.indexOf(dom); + assertEquals(outputList.get(id), resolver.resolveDomain(dom)); + })); + } @TestFactory Stream dynamicTestsForEmployeeWorkflows() { - List inputList = - Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); - + List inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John")); + EmployeeDao dao = new EmployeeDao(); - Stream saveEmployeeStream = inputList.stream().map(emp -> - DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { - Employee returned = dao.save(emp.getId()); - assertEquals(returned.getId(), emp.getId()); - })); - - Stream saveEmployeeWithFirstNameStream - = inputList.stream().filter(emp -> !emp.getFirstName().isEmpty()) + Stream saveEmployeeStream = inputList.stream() + .map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { + Employee returned = dao.save(emp.getId()); + assertEquals(returned.getId(), emp.getId()); + })); + + Stream saveEmployeeWithFirstNameStream = inputList.stream() + .filter(emp -> !emp.getFirstName() + .isEmpty()) .map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> { - Employee returned = dao.save(emp.getId(), emp.getFirstName()); - assertEquals(returned.getId(), emp.getId()); - assertEquals(returned.getFirstName(), emp.getFirstName()); - })); - + Employee returned = dao.save(emp.getId(), emp.getFirstName()); + assertEquals(returned.getId(), emp.getId()); + assertEquals(returned.getFirstName(), emp.getFirstName()); + })); + return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream); } - + class DomainNameResolver { - + private Map ipByDomainName = new HashMap<>(); - + DomainNameResolver() { this.ipByDomainName.put("www.somedomain.com", "154.174.10.56"); this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132"); this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156"); } - + public String resolveDomain(String domainName) { return ipByDomainName.get(domainName); } diff --git a/junit5/src/test/java/com/baeldung/EmployeesTest.java b/junit5/src/test/java/com/baeldung/EmployeesTest.java new file mode 100644 index 0000000000..71bb52284b --- /dev/null +++ b/junit5/src/test/java/com/baeldung/EmployeesTest.java @@ -0,0 +1,50 @@ +package com.baeldung; + +import java.sql.SQLException; + +import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import com.baeldung.extensions.EmployeeDaoParameterResolver; +import com.baeldung.extensions.EmployeeDatabaseSetupExtension; +import com.baeldung.extensions.EnvironmentExtension; +import com.baeldung.extensions.IgnoreFileNotFoundExceptionExtension; +import com.baeldung.extensions.LoggingExtension; +import com.baeldung.helpers.Employee; +import com.baeldung.helpers.EmployeeJdbcDao; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith({ EnvironmentExtension.class, EmployeeDatabaseSetupExtension.class, EmployeeDaoParameterResolver.class }) +@ExtendWith(LoggingExtension.class) +@ExtendWith(IgnoreFileNotFoundExceptionExtension.class) +public class EmployeesTest { + + private EmployeeJdbcDao employeeDao; + + private Logger logger; + + public EmployeesTest(EmployeeJdbcDao employeeDao) { + this.employeeDao = employeeDao; + } + + @Test + public void whenAddEmployee_thenGetEmployee() throws SQLException { + Employee emp = new Employee(1, "john"); + employeeDao.add(emp); + assertEquals(1, employeeDao.findAll() + .size()); + } + + @Test + public void whenGetEmployees_thenEmptyList() throws SQLException { + assertEquals(0, employeeDao.findAll() + .size()); + } + + public void setLogger(Logger logger) { + this.logger = logger; + } + +} diff --git a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java index 6ec1a4b7bd..bd57f5b3cb 100644 --- a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java +++ b/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java @@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test; public class ExceptionUnitTest { - @Test - void shouldThrowException() { - Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { - throw new UnsupportedOperationException("Not supported"); - }); - assertEquals(exception.getMessage(), "Not supported"); - } + @Test + void shouldThrowException() { + Throwable exception = assertThrows(UnsupportedOperationException.class, () -> { + throw new UnsupportedOperationException("Not supported"); + }); + assertEquals(exception.getMessage(), "Not supported"); + } - @Test - void assertThrowsException() { - String str = null; - assertThrows(IllegalArgumentException.class, () -> { - Integer.valueOf(str); - }); - } + @Test + void assertThrowsException() { + String str = null; + assertThrows(IllegalArgumentException.class, () -> { + Integer.valueOf(str); + }); + } } diff --git a/junit5/src/test/java/com/baeldung/FirstUnitTest.java b/junit5/src/test/java/com/baeldung/FirstUnitTest.java index 78c563cf82..c47a70e52f 100644 --- a/junit5/src/test/java/com/baeldung/FirstUnitTest.java +++ b/junit5/src/test/java/com/baeldung/FirstUnitTest.java @@ -13,21 +13,16 @@ class FirstUnitTest { @Test void lambdaExpressions() { List numbers = Arrays.asList(1, 2, 3); - assertTrue(numbers - .stream() - .mapToInt(i -> i) - .sum() > 5, "Sum should be greater than 5"); + assertTrue(numbers.stream() + .mapToInt(i -> i) + .sum() > 5, "Sum should be greater than 5"); } @Disabled("test to show MultipleFailuresError") @Test void groupAssertions() { - int[] numbers = {0, 1, 2, 3, 4}; - assertAll("numbers", - () -> assertEquals(numbers[0], 1), - () -> assertEquals(numbers[3], 3), - () -> assertEquals(numbers[4], 1) - ); + int[] numbers = { 0, 1, 2, 3, 4 }; + assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1)); } @Test diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java index a4dfd610a1..311c62f425 100644 --- a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java +++ b/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test; //@RunWith(JUnitPlatform.class) public class JUnit5NewFeaturesUnitTest { - private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); + private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); - @BeforeAll - static void setup() { - log.info("@BeforeAll - executes once before all test methods in this class"); - } + @BeforeAll + static void setup() { + log.info("@BeforeAll - executes once before all test methods in this class"); + } - @BeforeEach - void init() { - log.info("@BeforeEach - executes before each test method in this class"); - } + @BeforeEach + void init() { + log.info("@BeforeEach - executes before each test method in this class"); + } - @DisplayName("Single test successful") - @Test - void testSingleSuccessTest() { - log.info("Success"); + @DisplayName("Single test successful") + @Test + void testSingleSuccessTest() { + log.info("Success"); - } + } - @Test - @Disabled("Not implemented yet.") - void testShowSomething() { - } + @Test + @Disabled("Not implemented yet.") + void testShowSomething() { + } - @AfterEach - void tearDown() { - log.info("@AfterEach - executed after each test method."); - } + @AfterEach + void tearDown() { + log.info("@AfterEach - executed after each test method."); + } - @AfterAll - static void done() { - log.info("@AfterAll - executed after all test methods."); - } + @AfterAll + static void done() { + log.info("@AfterAll - executed after all test methods."); + } } diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/junit5/src/test/java/com/baeldung/LiveTest.java index e0e267da0b..c23eeb5afa 100644 --- a/junit5/src/test/java/com/baeldung/LiveTest.java +++ b/junit5/src/test/java/com/baeldung/LiveTest.java @@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory; public class LiveTest { - private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); - private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); + private List in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No")); + private List out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie")); - @TestFactory - public Stream translateDynamicTestsFromStream() { + @TestFactory + public Stream translateDynamicTestsFromStream() { - return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { - int id = in.indexOf(word); - assertEquals(out.get(id), translate(word)); - })); - } + return in.stream() + .map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { + int id = in.indexOf(word); + assertEquals(out.get(id), translate(word)); + })); + } - private String translate(String word) { - if ("Hello".equalsIgnoreCase(word)) { - return "Cześć"; - } else if ("Yes".equalsIgnoreCase(word)) { - return "Tak"; - } else if ("No".equalsIgnoreCase(word)) { - return "Nie"; - } - return "Error"; - } + private String translate(String word) { + if ("Hello".equalsIgnoreCase(word)) { + return "Cześć"; + } else if ("Yes".equalsIgnoreCase(word)) { + return "Tak"; + } else if ("No".equalsIgnoreCase(word)) { + return "Nie"; + } + return "Error"; + } } diff --git a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java index 8674e01e5d..749d7064bc 100644 --- a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java +++ b/junit5/src/test/java/com/baeldung/RepeatedTestExample.java @@ -14,36 +14,36 @@ public class RepeatedTestExample { void beforeEachTest() { System.out.println("Before Each Test"); } - + @AfterEach void afterEachTest() { System.out.println("After Each Test"); System.out.println("====================="); } - + @RepeatedTest(3) void repeatedTest(TestInfo testInfo) { System.out.println("Executing repeated test"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME) void repeatedTestWithLongName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME) void repeatedTestWithShortName() { System.out.println("Executing repeated test with long name"); assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}") void repeatedTestWithCustomDisplayName() { assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2"); } - + @RepeatedTest(3) void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) { System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition()); diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/junit5/src/test/java/com/baeldung/StringUtils.java index c1852113bc..227f131876 100644 --- a/junit5/src/test/java/com/baeldung/StringUtils.java +++ b/junit5/src/test/java/com/baeldung/StringUtils.java @@ -2,10 +2,10 @@ package com.baeldung; public final class StringUtils { - public static Double convertToDouble(String str) { - if (str == null) { - return null; - } - return Double.valueOf(str); - } + public static Double convertToDouble(String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } } diff --git a/junit5/src/test/java/com/baeldung/TestLauncher.java b/junit5/src/test/java/com/baeldung/TestLauncher.java new file mode 100644 index 0000000000..f9766d2bd9 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/TestLauncher.java @@ -0,0 +1,39 @@ +package com.baeldung; + +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; +import org.junit.platform.launcher.listeners.SummaryGeneratingListener; + +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; + +import java.io.PrintWriter; + +import org.junit.platform.launcher.Launcher; + +public class TestLauncher { + public static void main(String[] args) { + + //@formatter:off + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(selectClass("com.baeldung.EmployeesTest")) + .configurationParameter("junit.conditions.deactivate", "com.baeldung.extensions.*") + .configurationParameter("junit.extensions.autodetection.enabled", "true") + .build(); + + //@formatter:on + + TestPlan plan = LauncherFactory.create() + .discover(request); + Launcher launcher = LauncherFactory.create(); + SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener(); + launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener }); + launcher.execute(request); + + summaryGeneratingListener.getSummary() + .printTo(new PrintWriter(System.out)); + + } +} diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java new file mode 100644 index 0000000000..4e6931a65d --- /dev/null +++ b/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java @@ -0,0 +1,25 @@ +package com.baeldung.extensions; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +import com.baeldung.helpers.EmployeeJdbcDao; +import com.baeldung.helpers.JdbcConnectionUtil; + +public class EmployeeDaoParameterResolver implements ParameterResolver { + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return parameterContext.getParameter() + .getType() + .equals(EmployeeJdbcDao.class); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return new EmployeeJdbcDao(JdbcConnectionUtil.getConnection()); + } + +} diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java b/junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java new file mode 100644 index 0000000000..69e420b28a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java @@ -0,0 +1,46 @@ +package com.baeldung.extensions; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Savepoint; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import com.baeldung.helpers.EmployeeJdbcDao; +import com.baeldung.helpers.JdbcConnectionUtil; + +public class EmployeeDatabaseSetupExtension implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback { + + private Connection con = JdbcConnectionUtil.getConnection(); + private EmployeeJdbcDao employeeDao = new EmployeeJdbcDao(con); + private Savepoint savepoint; + + @Override + public void afterAll(ExtensionContext context) throws SQLException { + if (con != null) { + con.close(); + } + } + + @Override + public void beforeAll(ExtensionContext context) throws SQLException { + employeeDao.createTable(); + + } + + @Override + public void afterEach(ExtensionContext context) throws SQLException { + con.rollback(savepoint); + } + + @Override + public void beforeEach(ExtensionContext context) throws SQLException { + con.setAutoCommit(false); + savepoint = con.setSavepoint("before"); + } + +} diff --git a/junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java b/junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java new file mode 100644 index 0000000000..e2c335799b --- /dev/null +++ b/junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java @@ -0,0 +1,27 @@ +package com.baeldung.extensions; + +import java.io.IOException; +import java.util.Properties; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +public class EnvironmentExtension implements ExecutionCondition { + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + Properties props = new Properties(); + + try { + props.load(EnvironmentExtension.class.getResourceAsStream("application.properties")); + String env = props.getProperty("env"); + if ("qa".equalsIgnoreCase(env)) { + return ConditionEvaluationResult.disabled("Test disabled on QA environment"); + } + } catch (IOException e) { + e.printStackTrace(); + } + return ConditionEvaluationResult.enabled("Test enabled on QA environment"); + } +} diff --git a/junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java b/junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java new file mode 100644 index 0000000000..7216c68c1a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java @@ -0,0 +1,23 @@ +package com.baeldung.extensions; + +import java.io.FileNotFoundException; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; + +public class IgnoreFileNotFoundExceptionExtension implements TestExecutionExceptionHandler { + + Logger logger = LogManager.getLogger(IgnoreFileNotFoundExceptionExtension.class); + + @Override + public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { + + if (throwable instanceof FileNotFoundException) { + logger.error("File not found:" + throwable.getMessage()); + return; + } + throw throwable; + } +} diff --git a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java new file mode 100644 index 0000000000..930018d576 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java @@ -0,0 +1,18 @@ +package com.baeldung.extensions; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestInstancePostProcessor; + +public class LoggingExtension implements TestInstancePostProcessor { + + @Override + public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { + Logger logger = LogManager.getLogger(testInstance.getClass()); + testInstance.getClass() + .getMethod("setLogger", Logger.class) + .invoke(testInstance, logger); + } + +} diff --git a/junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java b/junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java new file mode 100644 index 0000000000..7600f763cd --- /dev/null +++ b/junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java @@ -0,0 +1,51 @@ +package com.baeldung.helpers; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class EmployeeJdbcDao { + + private Connection con; + + public EmployeeJdbcDao(Connection con) { + this.con = con; + } + + public void createTable() throws SQLException { + String createQuery = "CREATE TABLE employees(id long primary key, firstName varchar(50))"; + PreparedStatement pstmt = con.prepareStatement(createQuery); + + pstmt.execute(); + } + + public void add(Employee emp) throws SQLException { + String insertQuery = "INSERT INTO employees(id, firstName) VALUES(?,?)"; + PreparedStatement pstmt = con.prepareStatement(insertQuery); + pstmt.setLong(1, emp.getId()); + pstmt.setString(2, emp.getFirstName()); + + pstmt.executeUpdate(); + + } + + public List findAll() throws SQLException { + List employees = new ArrayList<>(); + String query = "SELECT * FROM employees"; + PreparedStatement pstmt = con.prepareStatement(query); + + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + Employee emp = new Employee(rs.getLong("id"), rs.getString("firstName")); + employees.add(emp); + } + + return employees; + } +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java b/junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java new file mode 100644 index 0000000000..f380f9674c --- /dev/null +++ b/junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java @@ -0,0 +1,32 @@ +package com.baeldung.helpers; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +public class JdbcConnectionUtil { + + private static Connection con; + + public static Connection getConnection() { + if (con == null) { + try { + Properties props = new Properties(); + props.load(JdbcConnectionUtil.class.getResourceAsStream("jdbc.properties")); + Class.forName(props.getProperty("jdbc.driver")); + con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password")); + return con; + } catch (IOException exc) { + exc.printStackTrace(); + } catch (ClassNotFoundException exc) { + exc.printStackTrace(); + } catch (SQLException exc) { + exc.printStackTrace(); + } + return null; + } + return con; + } +} diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java index 642b7371de..3cfe4c59f5 100644 --- a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java +++ b/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java @@ -30,9 +30,10 @@ public class AssertionsExampleTest { List list = Arrays.asList(1, 2, 3); Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) - .intValue(), 1), - () -> Assertions.assertEquals(list.get(1) - .intValue(), 2), + .intValue(), 1), () -> Assertions.assertEquals( + list.get(1) + .intValue(), + 2), () -> Assertions.assertEquals(list.get(2) .intValue(), 3)); } diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java index 104d311bc0..db5d3e2573 100644 --- a/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java +++ b/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java @@ -2,17 +2,17 @@ package com.baeldung.migration.junit5.extensions; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.TestExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext; public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback { @Override - public void beforeEach(TestExtensionContext context) throws Exception { + public void beforeEach(ExtensionContext context) throws Exception { System.out.println("Starting test ... " + context.getDisplayName()); } @Override - public void afterEach(TestExtensionContext context) throws Exception { + public void afterEach(ExtensionContext context) throws Exception { System.out.println("... test finished. " + context.getDisplayName()); } diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java new file mode 100644 index 0000000000..73ae2e08b7 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java @@ -0,0 +1,59 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class InvalidPersonParameterResolver implements ParameterResolver { + + /** + * The "bad" (invalid) data for testing purposes has to go somewhere, right? + */ + public static Person[] INVALID_PERSONS = { new Person().setId(1L) + .setLastName("Ad_ams") + .setFirstName("Jill,"), + new Person().setId(2L) + .setLastName(",Baker") + .setFirstName(""), + new Person().setId(3L) + .setLastName(null) + .setFirstName(null), + new Person().setId(4L) + .setLastName("Daniel&") + .setFirstName("{Joseph}"), + new Person().setId(5L) + .setLastName("") + .setFirstName("English, Jane"), + new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = true; + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/junit5/src/test/java/com/baeldung/param/Person.java new file mode 100644 index 0000000000..7095036bd4 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.param; + +/** + * Very simple Person entity. + * Use the Fluent-style interface to set properties. + * + * @author J Steven Perry + * + */ +public class Person { + + private Long id; + private String lastName; + private String firstName; + + public Long getId() { + return id; + } + + public Person setId(Long id) { + this.id = id; + return this; + } + + public String getLastName() { + return lastName; + } + + public Person setLastName(String lastName) { + this.lastName = lastName; + return this; + } + + public String getFirstName() { + return firstName; + } + + public Person setFirstName(String firstName) { + this.firstName = firstName; + return this; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/junit5/src/test/java/com/baeldung/param/PersonValidator.java new file mode 100644 index 0000000000..fbf596be8a --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidator.java @@ -0,0 +1,132 @@ +package com.baeldung.param; + +import java.util.Arrays; + +/** + * Somewhat contrived validation class to illustrate unit test + * concepts. + * + * @author J Steven Perry + * + */ +public class PersonValidator { + + /** + * Contrived checked exception to illustrate one possible + * way to handle validation errors (via a checked exception). + * + * @author J Steven Perry + * + */ + public static class ValidationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -134518049431883102L; + + // Probably should implement some more constructors, but don't want + /// to tarnish the lesson... + + /** + * The one and only way to create this checked exception. + * + * @param message + * The message accompanying the exception. Should be meaningful. + */ + public ValidationException(String message) { + super(message); + + } + + } + + private static final String[] ILLEGAL_NAME_CHARACTERS = { ",", "_", "{", "}", "!" }; + + /** + * Validate the first name of the specified Person object. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateFirstName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName() + .isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!"); + } + return ret; + } + + /** + * Validate the last name of the specified Person object. Looks the same as first + * name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge. + * + * @param person + * The Person object to validate. + * + * @return - returns true if the specified Person is valid + * + * @throws ValidationException + * - this Exception is thrown if any kind of validation error occurs. + */ + public static boolean validateLastName(Person person) throws ValidationException { + boolean ret = true; + // The validation rules go here. + // Naive: use simple ifs + if (person == null) { + throw new ValidationException("Person is null (not allowed)!"); + } + if (person.getFirstName() == null) { + throw new ValidationException("Person FirstName is null (not allowed)!"); + } + if (person.getFirstName() + .isEmpty()) { + throw new ValidationException("Person FirstName is an empty String (not allowed)!"); + } + if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { + throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!"); + } + return ret; + } + + /** + * Validates the specified name. If it contains any of the illegalCharacters, + * this method returns false (indicating the name is illegal). Otherwise it returns true. + * + * @param candidate + * The candidate String to validate + * + * @param illegalCharacters + * The characters the String is not allowed to have + * + * @return - boolean - true if the name is valid, false otherwise. + */ + private static boolean isStringValid(String candidate, String[] illegalCharacters) { + boolean ret = true; + for (String illegalChar : illegalCharacters) { + if (candidate.contains(illegalChar)) { + ret = false; + break; + } + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java new file mode 100644 index 0000000000..cd6f2b7e4f --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java @@ -0,0 +1,102 @@ +package com.baeldung.param; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@DisplayName("Testing PersonValidator") +public class PersonValidatorTest { + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver} + * to feed Test methods with "good" data. + */ + @Nested + @DisplayName("When using Valid data") + @ExtendWith(ValidPersonParameterResolver.class) + public class ValidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are valid") + public void validateFirstName(Person person) { + try { + assertTrue(PersonValidator.validateFirstName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * A valid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All last names are valid") + public void validateLastName(Person person) { + try { + assertTrue(PersonValidator.validateLastName(person)); + } catch (PersonValidator.ValidationException e) { + fail("Exception not expected: " + e.getLocalizedMessage()); + } + } + + } + + /** + * Nested class, uses ExtendWith + * {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver} + * to feed Test methods with "bad" data. + */ + @Nested + @DisplayName("When using Invalid data") + @ExtendWith(InvalidPersonParameterResolver.class) + public class InvalidData { + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateFirstName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person)); + } + + /** + * Repeat the test ten times, that way we have a good shot at + * running all of the data through at least once. + * + * @param person + * An invalid Person object to validate. + */ + @RepeatedTest(value = 10) + @DisplayName("All first names are invalid") + public void validateLastName(Person person) { + assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person)); + } + + } + +} diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java new file mode 100644 index 0000000000..10d958b83c --- /dev/null +++ b/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java @@ -0,0 +1,61 @@ +package com.baeldung.param; + +import java.util.Random; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class ValidPersonParameterResolver implements ParameterResolver { + + /** + * The "good" (valid) data for testing purposes has to go somewhere, right? + */ + public static Person[] VALID_PERSONS = { new Person().setId(1L) + .setLastName("Adams") + .setFirstName("Jill"), + new Person().setId(2L) + .setLastName("Baker") + .setFirstName("James"), + new Person().setId(3L) + .setLastName("Carter") + .setFirstName("Samanta"), + new Person().setId(4L) + .setLastName("Daniels") + .setFirstName("Joseph"), + new Person().setId(5L) + .setLastName("English") + .setFirstName("Jane"), + new Person().setId(6L) + .setLastName("Fontana") + .setFirstName("Enrique"), + // TODO: ADD MORE DATA HERE + }; + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + Object ret = null; + // + // Return a random, valid Person object if Person.class is the type of Parameter + /// to be resolved. Otherwise return null. + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; + } + return ret; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + boolean ret = false; + // + // If the Parameter.type == Person.class, then we support it, otherwise, get outta here! + if (parameterContext.getParameter() + .getType() == Person.class) { + ret = true; + } + return ret; + } + +} diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/junit5/src/test/java/com/baeldung/suites/AllTests.java index 24af1e733b..29452efc3d 100644 --- a/junit5/src/test/java/com/baeldung/suites/AllTests.java +++ b/junit5/src/test/java/com/baeldung/suites/AllTests.java @@ -1,8 +1,12 @@ package com.baeldung.suites; -//@RunWith(JUnitPlatform.class) -//@SelectPackages("com.baeldung") -//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages("com.baeldung") +// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) public class AllTests { } diff --git a/junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension new file mode 100644 index 0000000000..6bd0136b96 --- /dev/null +++ b/junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -0,0 +1 @@ +com.baeldung.extensions.EmployeeDaoParameterResolver \ No newline at end of file diff --git a/junit5/src/test/resources/com/baeldung/extensions/application.properties b/junit5/src/test/resources/com/baeldung/extensions/application.properties new file mode 100644 index 0000000000..601f964ff3 --- /dev/null +++ b/junit5/src/test/resources/com/baeldung/extensions/application.properties @@ -0,0 +1 @@ +env=dev \ No newline at end of file diff --git a/junit5/src/test/resources/com/baeldung/helpers/jdbc.properties b/junit5/src/test/resources/com/baeldung/helpers/jdbc.properties new file mode 100644 index 0000000000..8783ea2375 --- /dev/null +++ b/junit5/src/test/resources/com/baeldung/helpers/jdbc.properties @@ -0,0 +1,5 @@ +#h2 db +jdbc.driver=org.h2.Driver +jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.password= \ No newline at end of file diff --git a/kotlin/README.md b/kotlin/README.md index 1408bc1ebd..91933e94dc 100644 --- a/kotlin/README.md +++ b/kotlin/README.md @@ -6,3 +6,11 @@ - [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) - [Difference Between “==” and “===” in Kotlin](http://www.baeldung.com/kotlin-equality-operators) - [Generics in Kotlin](http://www.baeldung.com/kotlin-generics) +- [Introduction to Kotlin Coroutines](http://www.baeldung.com/kotlin-coroutines) +- [Destructuring Declarations in Kotlin](http://www.baeldung.com/kotlin-destructuring-declarations) +- [Kotlin with Mockito](http://www.baeldung.com/kotlin-mockito) +- [Lazy Initialization in Kotlin](http://www.baeldung.com/kotlin-lazy-initialization) +- [Overview of Kotlin Collections API](http://www.baeldung.com/kotlin-collections-api) +- [Converting a List to Map in Kotlin](http://www.baeldung.com/kotlin-list-to-map) +- [Data Classes in Kotlin](http://www.baeldung.com/kotlin-data-classes) + diff --git a/kotlin/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java b/kotlin/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java new file mode 100644 index 0000000000..273749e17e --- /dev/null +++ b/kotlin/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java @@ -0,0 +1,14 @@ +package com.baeldung.lazy; + +public class ClassWithHeavyInitialization { + private ClassWithHeavyInitialization() { + } + + private static class LazyHolder { + public static final ClassWithHeavyInitialization INSTANCE = new ClassWithHeavyInitialization(); + } + + public static ClassWithHeavyInitialization getInstance() { + return LazyHolder.INSTANCE; + } +} \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt new file mode 100644 index 0000000000..d3167ce033 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Person(var id: Int, var name: String, var age: Int) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt new file mode 100644 index 0000000000..e3da9b46a4 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Result(val result: Int, val status: String) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt new file mode 100644 index 0000000000..a5018d93c8 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt @@ -0,0 +1,44 @@ +package com.baeldung.destructuringdeclarations + +import com.baeldung.destructuringdeclarations.Person + +fun main(args: Array) { + + //2.1. Objects + val person = Person(1, "Jon Snow", 20) + val(id, name, age) = person + + println(id) //1 + println(name) //Jon Snow + println(age) //20 + + //2.2. Functions + fun getPersonInfo() = Person(2, "Ned Stark", 45) + val(idf, namef, agef) = getPersonInfo() + + fun twoValuesReturn(): Pair { + + // needed code + + return Pair(1, "success") + } + + // Now, to use this function: + val (result, status) = twoValuesReturn() + + //2.3. Collections and For-loops + var map: HashMap = HashMap() + map.put(1, person) + + for((key, value) in map){ + println("Key: $key, Value: $value") + } + + //2.4. Underscore and Destructuring in Lambdas + val (_, name2, age2) = person + val (id3, name3) = person + + map.mapValues { entry -> "${entry.value}!" } + map.mapValues { (key, value) -> "$value!" } + +} \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt new file mode 100644 index 0000000000..96e54716b3 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin + +sealed class Result { + abstract fun map(func: (S) -> R) : Result + abstract fun mapFailure(func: (F) -> R) : Result + abstract fun get() : S? +} + +data class Success(val success: S) : Result() { + override fun map(func: (S) -> R) : Result = Success(func(success)) + override fun mapFailure(func: (F) -> R): Result = Success(success) + override fun get(): S? = success +} + +data class Failure(val failure: F) : Result() { + override fun map(func: (S) -> R) : Result = Failure(failure) + override fun mapFailure(func: (F) -> R): Result = Failure(func(failure)) + override fun get(): S? = null +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt new file mode 100644 index 0000000000..9ea9f027fc --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt @@ -0,0 +1,35 @@ +package com.baeldung.kotlin.delegates + +val data = arrayOf>( + mutableMapOf( + "id" to 1, + "name" to "George", + "age" to 4 + ), + mutableMapOf( + "id" to 2, + "name" to "Charlotte", + "age" to 2 + ) +) + +class NoRecordFoundException(id: Int) : Exception("No record found for id $id") { + init { + println("No record found for ID $id") + } +} + +fun queryForValue(field: String, id: Int): Any { + println("Loading record $id from the fake database") + val value = data.firstOrNull { it["id"] == id } + ?.get(field) ?: throw NoRecordFoundException(id) + println("Loaded value $value for field $field of record $id") + return value +} + +fun update(field: String, id: Int, value: Any?) { + println("Updating field $field of record $id to value $value in the fake database") + data.firstOrNull { it["id"] == id } + ?.put(field, value) + ?: throw NoRecordFoundException(id) +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt new file mode 100644 index 0000000000..c1c0f8823c --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt @@ -0,0 +1,13 @@ +package com.baeldung.kotlin.delegates + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +class DatabaseDelegate(private val field: String, private val id: Int) : ReadWriteProperty { + override fun getValue(thisRef: R, property: KProperty<*>): T = + queryForValue(field, id) as T + + override fun setValue(thisRef: R, property: KProperty<*>, value: T) { + update(field, id, value) + } +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt new file mode 100644 index 0000000000..7788305ea1 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt @@ -0,0 +1,6 @@ +package com.baeldung.kotlin.delegates + +class User(val id: Int) { + var name: String by DatabaseDelegate("name", id) + var age: Int by DatabaseDelegate("age", id) +} diff --git a/kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java b/kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java new file mode 100644 index 0000000000..e2fe58d537 --- /dev/null +++ b/kotlin/src/test/java/com/baeldung/kotlin/LazyJavaUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.kotlin; + + +import com.baeldung.lazy.ClassWithHeavyInitialization; +import org.junit.Test; + +import static junit.framework.TestCase.assertTrue; + +public class LazyJavaUnitTest { + + @Test + public void giveHeavyClass_whenInitLazy_thenShouldReturnInstanceOnFirstCall() { + //when + ClassWithHeavyInitialization classWithHeavyInitialization = ClassWithHeavyInitialization.getInstance(); + ClassWithHeavyInitialization classWithHeavyInitialization2 = ClassWithHeavyInitialization.getInstance(); + + //then + assertTrue(classWithHeavyInitialization == classWithHeavyInitialization2); + } +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt new file mode 100644 index 0000000000..59d6adccac --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/CollectionsTest.kt @@ -0,0 +1,146 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertTrue +import kotlin.test.assertFalse +import kotlin.test.assertEquals + +class CollectionsTest { + + @Test + fun whenUseDifferentCollections_thenSuccess () { + val theList = listOf("one", "two", "three") + assertTrue(theList.contains("two")) + + val theMutableList = mutableListOf("one", "two", "three") + theMutableList.add("four") + assertTrue(theMutableList.contains("four")) + + val theSet = setOf("one", "two", "three") + assertTrue(theSet.contains("three")) + + val theMutableSet = mutableSetOf("one", "two", "three") + theMutableSet.add("four") + assertTrue(theMutableSet.contains("four")) + + val theMap = mapOf(1 to "one", 2 to "two", 3 to "three") + assertEquals(theMap[2],"two") + + val theMutableMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three") + theMutableMap[4] = "four" + assertEquals(theMutableMap[4],"four") + } + + @Test + fun whenSliceCollection_thenSuccess () { + val theList = listOf("one", "two", "three") + val resultList = theList.slice(1..2) + + assertEquals(2, resultList.size) + assertTrue(resultList.contains("two")) + } + + @Test + fun whenJoinTwoCollections_thenSuccess () { + val firstList = listOf("one", "two", "three") + val secondList = listOf("four", "five", "six") + val resultList = firstList + secondList + + assertEquals(6, resultList.size) + assertTrue(resultList.contains("two")) + assertTrue(resultList.contains("five")) + } + + @Test + fun whenFilterNullValues_thenSuccess () { + val theList = listOf("one", null, "two", null, "three") + val resultList = theList.filterNotNull() + + assertEquals(3, resultList.size) + } + + @Test + fun whenFilterNonPositiveValues_thenSuccess () { + val theList = listOf(1, 2, -3, -4, 5, -6) + val resultList = theList.filter{ it > 0} + //val resultList = theList.filter{ x -> x > 0} + + assertEquals(3, resultList.size) + assertTrue(resultList.contains(1)) + assertFalse(resultList.contains(-4)) + } + + @Test + fun whenDropFirstItems_thenRemoved () { + val theList = listOf("one", "two", "three", "four") + val resultList = theList.drop(2) + + assertEquals(2, resultList.size) + assertFalse(resultList.contains("one")) + assertFalse(resultList.contains("two")) + } + + @Test + fun whenDropFirstItemsBasedOnCondition_thenRemoved () { + val theList = listOf("one", "two", "three", "four") + val resultList = theList.dropWhile{ it.length < 4 } + + assertEquals(2, resultList.size) + assertFalse(resultList.contains("one")) + assertFalse(resultList.contains("two")) + } + + @Test + fun whenExcludeItems_thenRemoved () { + val firstList = listOf("one", "two", "three") + val secondList = listOf("one", "three") + val resultList = firstList - secondList + + assertEquals(1, resultList.size) + assertTrue(resultList.contains("two")) + } + + @Test + fun whenSearchForExistingItem_thenFound () { + val theList = listOf("one", "two", "three") + + assertTrue("two" in theList) + } + + @Test + fun whenGroupItems_thenSuccess () { + val theList = listOf(1, 2, 3, 4, 5, 6) + val resultMap = theList.groupBy{ it % 3} + + assertEquals(3, resultMap.size) + print(resultMap[1]) + assertTrue(resultMap[1]!!.contains(1)) + assertTrue(resultMap[2]!!.contains(5)) + } + + @Test + fun whenApplyFunctionToAllItems_thenSuccess () { + val theList = listOf(1, 2, 3, 4, 5, 6) + val resultList = theList.map{ it * it } + print(resultList) + assertEquals(4, resultList[1]) + assertEquals(9, resultList[2]) + } + + @Test + fun whenApplyMultiOutputFunctionToAllItems_thenSuccess () { + val theList = listOf("John", "Tom") + val resultList = theList.flatMap{ it.toLowerCase().toList()} + print(resultList) + assertEquals(7, resultList.size) + assertTrue(resultList.contains('j')) + } + + @Test + fun whenApplyFunctionToAllItemsWithStartingValue_thenSuccess () { + val theList = listOf(1, 2, 3, 4, 5, 6) + val finalResult = theList.fold( 1000, { oldResult, currentItem -> oldResult + (currentItem *currentItem)}) + print(finalResult) + assertEquals(1091, finalResult) + } +} \ No newline at end of file diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt new file mode 100644 index 0000000000..9e4179f4fe --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/LazyUnitTest.kt @@ -0,0 +1,68 @@ +package com.baeldung.kotlin + +import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.assertEquals + +class LazyUnitTest { + @Test + fun givenLazyValue_whenGetIt_thenShouldInitializeItOnlyOnce() { + //given + val numberOfInitializations: AtomicInteger = AtomicInteger() + val lazyValue: ClassWithHeavyInitialization by lazy { + numberOfInitializations.incrementAndGet() + ClassWithHeavyInitialization() + } + //when + println(lazyValue) + println(lazyValue) + + //then + assertEquals(numberOfInitializations.get(), 1) + } + + @Test + fun givenLazyValue_whenGetItUsingPublication_thenCouldInitializeItMoreThanOnce() { + //given + val numberOfInitializations: AtomicInteger = AtomicInteger() + val lazyValue: ClassWithHeavyInitialization by lazy(LazyThreadSafetyMode.PUBLICATION) { + numberOfInitializations.incrementAndGet() + ClassWithHeavyInitialization() + } + val executorService = Executors.newFixedThreadPool(2) + val countDownLatch = CountDownLatch(1) + //when + executorService.submit { countDownLatch.await(); println(lazyValue) } + executorService.submit { countDownLatch.await(); println(lazyValue) } + countDownLatch.countDown() + + //then + executorService.awaitTermination(1, TimeUnit.SECONDS) + executorService.shutdown() + assertEquals(numberOfInitializations.get(), 2) + } + + class ClassWithHeavyInitialization { + + } + + + lateinit var a: String + @Test + fun givenLateInitProperty_whenAccessItAfterInit_thenPass() { + //when + a = "it" + println(a) + + //then not throw + } + + @Test(expected = UninitializedPropertyAccessException::class) + fun givenLateInitProperty_whenAccessItWithoutInit_thenThrow() { + //when + println(a) + } +} \ No newline at end of file diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt new file mode 100644 index 0000000000..8c7509f653 --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.kotlin + +import org.junit.Assert +import org.junit.Test + +class SealedTest { + fun divide(a: Int, b: Int) : Result = when (b) { + 0 -> Failure("Division by zero") + else -> Success(a.toFloat() / b) + } + + @Test + fun testSuccess() { + val result = divide(10, 5) + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testError() { + val result = divide(10, 0) + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMatchOnSuccess() { + val result = divide(10, 5) + when (result) { + is Success -> { + // Expected + } + is Failure -> Assert.fail("Expected Success") + } + } + + @Test + fun testMatchOnError() { + val result = divide(10, 0) + when (result) { + is Failure -> { + // Expected + } + } + } + + @Test + fun testGetSuccess() { + val result = divide(10, 5) + Assert.assertEquals(2.0f, result.get()) + } + + @Test + fun testGetError() { + val result = divide(10, 0) + Assert.assertNull(result.get()) + } + + @Test + fun testMapOnSuccess() { + val result = divide(10, 5) + .map { "Result: $it" } + Assert.assertEquals(Success("Result: 2.0"), result) + } + + @Test + fun testMapOnError() { + val result = divide(10, 0) + .map { "Result: $it" } + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMapFailureOnSuccess() { + val result = divide(10, 5) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testMapFailureOnError() { + val result = divide(10, 0) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Failure("Failure: Division by zero"), result) + } +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt new file mode 100644 index 0000000000..fc50730dfa --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.delegates + +import org.junit.Test +import kotlin.test.assertEquals + +class DatabaseDelegatesTest { + @Test + fun testGetKnownFields() { + val user = User(1) + assertEquals("George", user.name) + assertEquals(4, user.age) + } + + @Test + fun testSetKnownFields() { + val user = User(2) + user.age = 3 + assertEquals(3, user.age) + } + + @Test(expected = NoRecordFoundException::class) + fun testGetKnownField() { + val user = User(3) + user.name + } +} diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml new file mode 100644 index 0000000000..cae8a725a6 --- /dev/null +++ b/libraries-data/pom.xml @@ -0,0 +1,148 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + libraries-data + libraries-data + jar + + + com.esotericsoftware + kryo + ${kryo.version} + + + com.h2database + h2 + ${h2.version} + + + junit + junit + ${junit.version} + test + + + com.goldmansachs.reladomo + reladomo + ${reladomo.version} + + + com.goldmansachs.reladomo + reladomo-test-util + ${reladomo.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + maven-antrun-plugin + 1.8 + + + generateMithra + generate-sources + + run + + + + + + + + + + + + + + + + + + com.goldmansachs.reladomo + reladomogen + ${reladomo.version} + + + + com.goldmansachs.reladomo + reladomo-gen-util + ${reladomo.version} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/reladomo + + + + + add-resource + generate-resources + + add-resource + + + + + ${project.build.directory}/generated-db/ + + + + + + + + + + + + + 4.0.1 + 1.4.196 + 16.5.1 + 4.12 + 3.6.2 + + \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java new file mode 100644 index 0000000000..0e125e48a9 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java @@ -0,0 +1,16 @@ +package com.baeldung.kryo; + +import java.io.Serializable; + +public class ComplexClass implements Serializable{ + private static final long serialVersionUID = 123456L; + private String name = "Bael"; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/Person.java b/libraries-data/src/main/java/com/baeldung/kryo/Person.java new file mode 100644 index 0000000000..f9be5cfd62 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/Person.java @@ -0,0 +1,54 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.DefaultSerializer; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.KryoSerializable; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +@DefaultSerializer(PersonSerializer.class) +public class Person implements KryoSerializable { + private String name = "John Doe"; + private int age = 18; + private Date birthDate = new Date(933191282821L); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + @Override + public void write(Kryo kryo, Output output) { + output.writeString(name); + output.writeLong(birthDate.getTime()); + output.writeInt(age); + } + + @Override + public void read(Kryo kryo, Input input) { + name = input.readString(); + birthDate = new Date(input.readLong()); + age = input.readInt(); + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java new file mode 100644 index 0000000000..f5d01509a6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java @@ -0,0 +1,33 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +public class PersonSerializer extends Serializer { + + @Override + public void write(Kryo kryo, Output output, Person object) { + output.writeString(object.getName()); + output.writeLong(object.getBirthDate() + .getTime()); + } + + @Override + public Person read(Kryo kryo, Input input, Class type) { + Person person = new Person(); + person.setName(input.readString()); + long birthDate = input.readLong(); + person.setBirthDate(new Date(birthDate)); + person.setAge(calculateAge(birthDate)); + return person; + } + + private int calculateAge(long birthDate) { + // Some custom logic + return 18; + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/Department.java b/libraries-data/src/main/java/com/baeldung/reladomo/Department.java new file mode 100644 index 0000000000..d26ddafbf4 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/Department.java @@ -0,0 +1,15 @@ +package com.baeldung.reladomo; + +public class Department extends DepartmentAbstract { + public Department() { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Department(long id, String name) { + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java new file mode 100644 index 0000000000..4cfb5cb055 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class DepartmentDatabaseObject extends DepartmentDatabaseObjectAbstract +{ +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentList.java b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentList.java new file mode 100644 index 0000000000..edad6bc1f4 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/DepartmentList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class DepartmentList extends DepartmentListAbstract +{ + public DepartmentList() + { + super(); + } + + public DepartmentList(int initialSize) + { + super(initialSize); + } + + public DepartmentList(Collection c) + { + super(c); + } + + public DepartmentList(Operation operation) + { + super(operation); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/Employee.java b/libraries-data/src/main/java/com/baeldung/reladomo/Employee.java new file mode 100644 index 0000000000..519e841282 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/Employee.java @@ -0,0 +1,16 @@ +package com.baeldung.reladomo; +public class Employee extends EmployeeAbstract +{ + public Employee() + { + super(); + // You must not modify this constructor. Mithra calls this internally. + // You can call this constructor. You can also add new constructors. + } + + public Employee(long id, String name){ + super(); + this.setId(id); + this.setName(name); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java new file mode 100644 index 0000000000..407049f342 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeDatabaseObject.java @@ -0,0 +1,4 @@ +package com.baeldung.reladomo; +public class EmployeeDatabaseObject extends EmployeeDatabaseObjectAbstract +{ +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeList.java b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeList.java new file mode 100644 index 0000000000..4e759898c3 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/EmployeeList.java @@ -0,0 +1,25 @@ +package com.baeldung.reladomo; +import com.gs.fw.finder.Operation; +import java.util.*; +public class EmployeeList extends EmployeeListAbstract +{ + public EmployeeList() + { + super(); + } + + public EmployeeList(int initialSize) + { + super(initialSize); + } + + public EmployeeList(Collection c) + { + super(c); + } + + public EmployeeList(Operation operation) + { + super(operation); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoApplication.java b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoApplication.java new file mode 100644 index 0000000000..c6b242d3ae --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoApplication.java @@ -0,0 +1,54 @@ +package com.baeldung.reladomo; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.gs.fw.common.mithra.MithraManager; +import com.gs.fw.common.mithra.MithraManagerProvider; + +public class ReladomoApplication { + + public static void main(String[] args) { + + try { + ReladomoConnectionManager.getInstance().createTables(); + } catch (Exception e1) { + e1.printStackTrace(); + } + + MithraManager mithraManager = MithraManagerProvider.getMithraManager(); + mithraManager.setTransactionTimeout(120); + + try (InputStream is = ReladomoApplication.class.getClassLoader().getResourceAsStream("ReladomoRuntimeConfig.xml")) { + MithraManagerProvider.getMithraManager().readConfiguration(is); + + Department department = new Department(1, "IT"); + Employee employee = new Employee(1, "John"); + department.getEmployees().add(employee); + department.cascadeInsert(); + + Department depFound = DepartmentFinder.findByPrimaryKey(1); + System.out.println("Department Name:" + department.getName()); + + Employee empFound = EmployeeFinder.findOne(EmployeeFinder.name().eq("John")); + System.out.println("Employee Id:" + empFound.getId()); + empFound.setName("Steven"); + empFound.delete(); + Department depDetached = DepartmentFinder.findByPrimaryKey(1).getDetachedCopy(); + + mithraManager.executeTransactionalCommand(tx -> { + Department dep = new Department(2, "HR"); + Employee emp = new Employee(2, "Jim"); + dep.getEmployees().add(emp); + dep.cascadeInsert(); + return null; + }); + + } catch (java.io.IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java new file mode 100644 index 0000000000..66a8f9ff99 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/reladomo/ReladomoConnectionManager.java @@ -0,0 +1,92 @@ +package com.baeldung.reladomo; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.TimeZone; +import java.util.stream.Stream; + +import org.h2.tools.RunScript; + +import com.gs.fw.common.mithra.bulkloader.BulkLoader; +import com.gs.fw.common.mithra.bulkloader.BulkLoaderException; +import com.gs.fw.common.mithra.connectionmanager.SourcelessConnectionManager; +import com.gs.fw.common.mithra.connectionmanager.XAConnectionManager; +import com.gs.fw.common.mithra.databasetype.DatabaseType; +import com.gs.fw.common.mithra.databasetype.H2DatabaseType; + +public class ReladomoConnectionManager implements SourcelessConnectionManager { + + private static ReladomoConnectionManager instance; + + private XAConnectionManager xaConnectionManager; + + private final String databaseName = "myDb"; + + public static synchronized ReladomoConnectionManager getInstance() { + if (instance == null) { + instance = new ReladomoConnectionManager(); + } + return instance; + } + + private ReladomoConnectionManager() { + this.createConnectionManager(); + } + + private XAConnectionManager createConnectionManager() { + xaConnectionManager = new XAConnectionManager(); + xaConnectionManager.setDriverClassName("org.h2.Driver"); + xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName); + xaConnectionManager.setJdbcUser("sa"); + xaConnectionManager.setJdbcPassword(""); + xaConnectionManager.setPoolName("My Connection Pool"); + xaConnectionManager.setInitialSize(1); + xaConnectionManager.setPoolSize(10); + xaConnectionManager.initialisePool(); + return xaConnectionManager; + } + + @Override + public BulkLoader createBulkLoader() throws BulkLoaderException { + return null; + } + + @Override + public Connection getConnection() { + return xaConnectionManager.getConnection(); + } + + @Override + public DatabaseType getDatabaseType() { + return H2DatabaseType.getInstance(); + } + + @Override + public TimeZone getDatabaseTimeZone() { + return TimeZone.getDefault(); + } + + @Override + public String getDatabaseIdentifier() { + return databaseName; + } + + public void createTables() throws Exception { + Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI()); + + try (Connection conn = xaConnectionManager.getConnection(); Stream list = Files.list(ddlPath);) { + list.forEach(path -> { + try { + RunScript.execute(conn, Files.newBufferedReader(path)); + } catch (SQLException | IOException exc) { + exc.printStackTrace(); + } + }); + } + } + +} diff --git a/libraries-data/src/main/resources/ReladomoRuntimeConfig.xml b/libraries-data/src/main/resources/ReladomoRuntimeConfig.xml new file mode 100644 index 0000000000..7181e75406 --- /dev/null +++ b/libraries-data/src/main/resources/ReladomoRuntimeConfig.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/reladomo/Department.xml b/libraries-data/src/main/resources/reladomo/Department.xml new file mode 100644 index 0000000000..a284965cd6 --- /dev/null +++ b/libraries-data/src/main/resources/reladomo/Department.xml @@ -0,0 +1,11 @@ + + com.baeldung.reladomo + Department + departments + + + + + Employee.departmentId = this.id + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/reladomo/Employee.xml b/libraries-data/src/main/resources/reladomo/Employee.xml new file mode 100644 index 0000000000..00e360bc67 --- /dev/null +++ b/libraries-data/src/main/resources/reladomo/Employee.xml @@ -0,0 +1,9 @@ + + com.baeldung.reladomo + Employee + employees + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/reladomo/ReladomoClassList.xml b/libraries-data/src/main/resources/reladomo/ReladomoClassList.xml new file mode 100644 index 0000000000..99118a745d --- /dev/null +++ b/libraries-data/src/main/resources/reladomo/ReladomoClassList.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java new file mode 100644 index 0000000000..c124ca618d --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.kryo; + +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.Test; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import com.esotericsoftware.kryo.serializers.JavaSerializer; + +public class KryoUnitTest { + + private Kryo kryo; + private Output output; + private Input input; + + @Before + public void init() { + kryo = new Kryo(); + try { + output = new Output(new FileOutputStream("file.dat")); + input = new Input(new FileInputStream("file.dat")); + } catch (FileNotFoundException ex) { + Logger.getLogger(KryoUnitTest.class.getName()) + .log(Level.SEVERE, null, ex); + } + } + + @Test + public void givenObject_whenSerializing_thenReadCorrectly() { + Object someObject = "Some string"; + + kryo.writeClassAndObject(output, someObject); + output.close(); + + Object theObject = kryo.readClassAndObject(input); + input.close(); + + assertEquals(theObject, "Some string"); + } + + @Test + public void givenObjects_whenSerializing_thenReadCorrectly() { + String someString = "Multiple Objects"; + Date someDate = new Date(915170400000L); + + kryo.writeObject(output, someString); + kryo.writeObject(output, someDate); + output.close(); + + String readString = kryo.readObject(input, String.class); + Date readDate = kryo.readObject(input, Date.class); + input.close(); + + assertEquals(readString, "Multiple Objects"); + assertEquals(readDate.getTime(), 915170400000L); + } + + @Test + public void givenPerson_whenSerializing_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + } + + @Test + public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() { + Person person = new Person(); + person.setAge(0); + kryo.register(Person.class, new PersonSerializer()); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenPerson_whenCustomSerialization_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenJavaSerializable_whenSerializing_thenReadCorrectly() { + ComplexClass complexClass = new ComplexClass(); + kryo.register(ComplexClass.class, new JavaSerializer()); + + kryo.writeObject(output, complexClass); + output.close(); + + ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class); + input.close(); + + assertEquals(readComplexObject.getName(), "Bael"); + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java b/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java new file mode 100644 index 0000000000..61c29e8aa3 --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/reladomo/ReladomoTest.java @@ -0,0 +1,38 @@ +package com.baeldung.reladomo; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.gs.fw.common.mithra.test.ConnectionManagerForTests; +import com.gs.fw.common.mithra.test.MithraTestResource; + +public class ReladomoTest { + private MithraTestResource mithraTestResource; + + @Before + public void setUp() throws Exception { + this.mithraTestResource = new MithraTestResource("reladomo/ReladomoTestConfig.xml"); + + final ConnectionManagerForTests connectionManager = ConnectionManagerForTests.getInstanceForDbName("testDb"); + this.mithraTestResource.createSingleDatabase(connectionManager); + + mithraTestResource.addTestDataToDatabase("reladomo/test-data.txt", connectionManager); + + this.mithraTestResource.setUp(); + } + + @Test + public void whenGetTestData_thenOk() { + Employee employee = EmployeeFinder.findByPrimaryKey(1); + assertEquals(employee.getName(), "Paul"); + } + + @After + public void tearDown() throws Exception { + this.mithraTestResource.tearDown(); + } + +} diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml new file mode 100644 index 0000000000..a1951f09b7 --- /dev/null +++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/libraries-data/src/test/resources/reladomo/test-data.txt b/libraries-data/src/test/resources/reladomo/test-data.txt new file mode 100644 index 0000000000..8e407278ac --- /dev/null +++ b/libraries-data/src/test/resources/reladomo/test-data.txt @@ -0,0 +1,7 @@ +class com.baeldung.reladomo.Department +id, name +1, "Marketing" + +class com.baeldung.reladomo.Employee +id, name +1, "Paul" \ No newline at end of file diff --git a/libraries/OpenNLP/PartOfSpeechTag.txt b/libraries/OpenNLP/PartOfSpeechTag.txt deleted file mode 100644 index fdd8238ec4..0000000000 --- a/libraries/OpenNLP/PartOfSpeechTag.txt +++ /dev/null @@ -1 +0,0 @@ -Out of the night that covers me \ No newline at end of file diff --git a/libraries/OpenNLP/doc-cat.train b/libraries/OpenNLP/doc-cat.train deleted file mode 100644 index c457221ec6..0000000000 --- a/libraries/OpenNLP/doc-cat.train +++ /dev/null @@ -1,10 +0,0 @@ -GOOD good morning / -GOOD good evening / -GOOD have a good day / -GOOD nice party! / -GOOD fine pants / -BAD nightmare volcano in the sea / -BAD darkest sky / -BAD greed and waste / -BAD army attacks / -BAD bomb explodes / \ No newline at end of file diff --git a/libraries/OpenNLP/en-chunker.bin b/libraries/OpenNLP/en-chunker.bin deleted file mode 100644 index 65d9356888..0000000000 Binary files a/libraries/OpenNLP/en-chunker.bin and /dev/null differ diff --git a/libraries/OpenNLP/en-ner-location.bin b/libraries/OpenNLP/en-ner-location.bin deleted file mode 100644 index f3788bc1f6..0000000000 Binary files a/libraries/OpenNLP/en-ner-location.bin and /dev/null differ diff --git a/libraries/OpenNLP/en-ner-person.bin b/libraries/OpenNLP/en-ner-person.bin deleted file mode 100644 index 2f68318203..0000000000 Binary files a/libraries/OpenNLP/en-ner-person.bin and /dev/null differ diff --git a/libraries/OpenNLP/en-pos-maxent.bin b/libraries/OpenNLP/en-pos-maxent.bin deleted file mode 100644 index c8cae23c5f..0000000000 Binary files a/libraries/OpenNLP/en-pos-maxent.bin and /dev/null differ diff --git a/libraries/OpenNLP/en-sent.bin b/libraries/OpenNLP/en-sent.bin deleted file mode 100644 index e89076be5a..0000000000 Binary files a/libraries/OpenNLP/en-sent.bin and /dev/null differ diff --git a/libraries/OpenNLP/en-token.bin b/libraries/OpenNLP/en-token.bin deleted file mode 100644 index c417277ca7..0000000000 Binary files a/libraries/OpenNLP/en-token.bin and /dev/null differ diff --git a/libraries/README.md b/libraries/README.md index 293e11cf0c..ed6d214c7a 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -12,12 +12,25 @@ - [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to JaVer](http://www.baeldung.com/serenity-bdd) - [Introduction to Netty](http://www.baeldung.com/netty) +- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) +- [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) +- [Introduction to Quartz](http://www.baeldung.com/quartz) +- [How to Warm Up the JVM](http://www.baeldung.com/java-jvm-warmup) +- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) - [Guide to Java Data Objects](http://www.baeldung.com/jdo) - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) - [Introduction to HikariCP](http://www.baeldung.com/hikaricp) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) +- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) +- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) +- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) +- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) +- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index ff9c72399d..6d1098246e 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,13 +1,12 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> parent-modules com.baeldung 1.0.0-SNAPSHOT 4.0.0 - libraries libraries @@ -21,7 +20,6 @@ maven-bundle-plugin 3.3.0 maven-plugin - true @@ -59,7 +57,8 @@ ${basedir}/datanucleus.properties ${basedir}/log4j.properties true - false + false + @@ -70,10 +69,52 @@ + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + test + test + + test + + + + test/java/com/baeldung/neuroph/XORTest.java + + + + + + + - + + + org.beykery + neuroph + ${neuroph.version} + cglib @@ -141,6 +182,16 @@ jetty-servlet ${jetty.version} + + rome + rome + ${rome.version} + + + io.specto + hoverfly-java + 0.8.0 + org.apache.httpcomponents httpclient @@ -157,6 +208,21 @@ commons-io ${commons.io.version} + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + org.apache.flink flink-core @@ -256,6 +322,11 @@ datanucleus-xml 5.0.0-release + + net.openhft + chronicle + 3.6.4 + org.springframework spring-web @@ -299,7 +370,7 @@ com.h2database h2 - 1.4.195 + ${h2.version} pl.pragmatists @@ -312,11 +383,10 @@ quartz 2.3.0 - one.util streamex - 0.6.5 + ${streamex.version} org.jooq @@ -338,12 +408,6 @@ netty-all ${netty.version} - - - org.apache.opennlp - opennlp-tools - 1.8.0 - junit junit @@ -378,13 +442,91 @@ ${awaitility.version} test + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + net.agkn + hll + ${hll.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + + + org.pcollections + pcollections + ${pcollections.version} + + + com.machinezoo.noexception + noexception + 1.1.0 + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + io.vavr + vavr + ${vavr.version} + + + org.geotools + gt-shapefile + ${geotools.version} + + + org.geotools + gt-epsg-hsql + ${geotools.version} + + + org.geotools + gt-swing + ${geotools.version} + + + + maven2-repository.dev.java.net + Java.net repository + http://download.java.net/maven/2 + + + osgeo + Open Source Geospatial Foundation Repository + http://download.osgeo.org/webdav/geotools/ + + + + true + + opengeo + OpenGeo Maven Repository + http://repo.opengeo.org + + 0.7.0 3.2.4 3.5 1.1 1.9.3 + 1.2 + 1.4 1.9.2 1.2 3.21.0-GA @@ -394,11 +536,14 @@ 9.4.3.v20170317 4.5.3 2.5 + 1.6 + 1.4.196 9.4.2.v20170220 4.5.3 2.5 1.2.0 2.8.5 + 2.92 1.4.0 1.24.0 1.1.3-rc.5 @@ -410,6 +555,14 @@ 0.10 3.5.0 3.0.0 + 2.0.0.0 + 1.6.0 + 1.7.1 + 2.1.2 + 1.0 + 8.2.0 + 0.6.5 + 0.9.0 + 15.2 - - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java b/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java index 3bc82afaac..adfa3e1fb2 100644 --- a/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java +++ b/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java @@ -8,25 +8,23 @@ public class AsyncService { private final int DELAY = 1000; private final int INIT_DELAY = 2000; - private AtomicLong value = new AtomicLong(0); - private Executor executor = Executors.newFixedThreadPool(4); + private final AtomicLong value = new AtomicLong(0); + private final Executor executor = Executors.newFixedThreadPool(4); private volatile boolean initialized = false; - public void initialize() { + void initialize() { executor.execute(() -> { sleep(INIT_DELAY); initialized = true; }); } - public boolean isInitialized() { + boolean isInitialized() { return initialized; } - public void addValue(long val) { - if (!isInitialized()) { - throw new IllegalStateException("Service is not initialized"); - } + void addValue(long val) { + throwIfNotInitialized(); executor.execute(() -> { sleep(DELAY); value.addAndGet(val); @@ -34,9 +32,7 @@ public class AsyncService { } public long getValue() { - if (!isInitialized()) { - throw new IllegalStateException("Service is not initialized"); - } + throwIfNotInitialized(); return value.longValue(); } @@ -47,4 +43,10 @@ public class AsyncService { e.printStackTrace(); } } + + private void throwIfNotInitialized() { + if (!initialized) { + throw new IllegalStateException("Service is not initialized"); + } + } } diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java new file mode 100644 index 0000000000..d0362a6c92 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java @@ -0,0 +1,16 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.implementation.bind.annotation.BindingPriority; + +public class Bar { + + @BindingPriority(3) + public static String sayHelloBar() { return "Holla in Bar!"; } + + @BindingPriority(2) + public static String sayBar() { return "bar"; } + + public String bar() { return Bar.class.getSimpleName() + " - Bar"; } + + +} diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java new file mode 100644 index 0000000000..4be06785b1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java @@ -0,0 +1,7 @@ +package com.baeldung.bytebuddy; + +public class Foo { + + public String sayHelloFoo() { return "Hello in Foo!"; } + +} diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java new file mode 100644 index 0000000000..f6bd25c0fe --- /dev/null +++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java @@ -0,0 +1,23 @@ +package com.baeldung.chronicle.queue; + +import java.io.IOException; + +import net.openhft.chronicle.Chronicle; +import net.openhft.chronicle.ExcerptAppender; + +public class ChronicleQueue { + + static void writeToQueue( + Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) + throws IOException { + ExcerptAppender appender = chronicle.createAppender(); + appender.startExcerpt(); + appender.writeUTF(stringValue); + appender.writeInt(intValue); + appender.writeLong(longValue); + appender.writeDouble(doubleValue); + appender.finish(); + appender.close(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java new file mode 100644 index 0000000000..cbcf03c7d4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java @@ -0,0 +1,23 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; + +import static com.baeldung.commons.chain.AtmConstants.AMOUNT_LEFT_TO_BE_WITHDRAWN; + +public abstract class AbstractDenominationDispenser implements Command { + + @Override + public boolean execute(Context context) throws Exception { + int amountLeftToBeWithdrawn = (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN); + if (amountLeftToBeWithdrawn >= getDenominationValue()) { + context.put(getDenominationString(), amountLeftToBeWithdrawn / getDenominationValue()); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, amountLeftToBeWithdrawn % getDenominationValue()); + } + return false; + } + + protected abstract String getDenominationString(); + + protected abstract int getDenominationValue(); +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java new file mode 100644 index 0000000000..768517e19a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java @@ -0,0 +1,13 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.CatalogBase; + +import static com.baeldung.commons.chain.AtmConstants.ATM_WITHDRAWAL_CHAIN; + +public class AtmCatalog extends CatalogBase { + + public AtmCatalog() { + super(); + addCommand(ATM_WITHDRAWAL_CHAIN, new AtmWithdrawalChain()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java new file mode 100644 index 0000000000..d9425fcfac --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java @@ -0,0 +1,10 @@ +package com.baeldung.commons.chain; + +public class AtmConstants { + public static final String TOTAL_AMOUNT_TO_BE_WITHDRAWN = "totalAmountToBeWithdrawn"; + public static final String AMOUNT_LEFT_TO_BE_WITHDRAWN = "amountLeftToBeWithdrawn"; + public static final String NO_OF_HUNDREDS_DISPENSED = "noOfHundredsDispensed"; + public static final String NO_OF_FIFTIES_DISPENSED = "noOfFiftiesDispensed"; + public static final String NO_OF_TENS_DISPENSED = "noOfTensDispensed"; + public static final String ATM_WITHDRAWAL_CHAIN = "atmWithdrawalChain"; +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java new file mode 100644 index 0000000000..ee089705ad --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java @@ -0,0 +1,52 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ContextBase; + +public class AtmRequestContext extends ContextBase { + + int totalAmountToBeWithdrawn; + int noOfHundredsDispensed; + int noOfFiftiesDispensed; + int noOfTensDispensed; + int amountLeftToBeWithdrawn; + + public int getTotalAmountToBeWithdrawn() { + return totalAmountToBeWithdrawn; + } + + public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) { + this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn; + } + + public int getNoOfHundredsDispensed() { + return noOfHundredsDispensed; + } + + public void setNoOfHundredsDispensed(int noOfHundredsDispensed) { + this.noOfHundredsDispensed = noOfHundredsDispensed; + } + + public int getNoOfFiftiesDispensed() { + return noOfFiftiesDispensed; + } + + public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) { + this.noOfFiftiesDispensed = noOfFiftiesDispensed; + } + + public int getNoOfTensDispensed() { + return noOfTensDispensed; + } + + public void setNoOfTensDispensed(int noOfTensDispensed) { + this.noOfTensDispensed = noOfTensDispensed; + } + + public int getAmountLeftToBeWithdrawn() { + return amountLeftToBeWithdrawn; + } + + public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) { + this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn; + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java new file mode 100644 index 0000000000..fdea5e5744 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java @@ -0,0 +1,14 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ChainBase; + +public class AtmWithdrawalChain extends ChainBase { + + public AtmWithdrawalChain() { + super(); + addCommand(new HundredDenominationDispenser()); + addCommand(new FiftyDenominationDispenser()); + addCommand(new TenDenominationDispenser()); + addCommand(new AuditFilter()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java new file mode 100644 index 0000000000..973e2d498e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java @@ -0,0 +1,18 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Context; +import org.apache.commons.chain.Filter; + +public class AuditFilter implements Filter { + + @Override + public boolean postprocess(Context context, Exception exception) { + // Send notification to customer & bank. + return false; + } + + @Override + public boolean execute(Context context) throws Exception { + return false; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java new file mode 100644 index 0000000000..f0f5959764 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_FIFTIES_DISPENSED; + +public class FiftyDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_FIFTIES_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 50; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java new file mode 100644 index 0000000000..e65d0d34c9 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_HUNDREDS_DISPENSED; + +public class HundredDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_HUNDREDS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 100; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java new file mode 100644 index 0000000000..423440bc4d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_TENS_DISPENSED; + +public class TenDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_TENS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 10; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java new file mode 100644 index 0000000000..c82798d52d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java @@ -0,0 +1,38 @@ +package com.baeldung.commons.dbutils; + +public class Email { + private Integer id; + private Integer employeeId; + private String address; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Integer employeeId) { + this.employeeId = employeeId; + } + + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + return "Email{" + "id=" + id + ", address=" + address + '}'; + } + +} diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java b/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java new file mode 100644 index 0000000000..e6f34c0201 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java @@ -0,0 +1,67 @@ +package com.baeldung.commons.dbutils; + +import java.util.Date; +import java.util.List; + +public class Employee { + private Integer id; + private String firstName; + private String lastName; + private Double salary; + private Date hiredDate; + private List emails; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Double getSalary() { + return salary; + } + + public void setSalary(Double salary) { + this.salary = salary; + } + + public Date getHiredDate() { + return hiredDate; + } + + public void setHiredDate(Date hiredDate) { + this.hiredDate = hiredDate; + } + + public List getEmails() { + return emails; + } + + public void setEmails(List emails) { + this.emails = emails; + } + + @Override + public String toString() { + return "Employee{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", salary=" + salary + ", hiredDate=" + hiredDate + '}'; + } + +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java b/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java new file mode 100644 index 0000000000..6f68bafe57 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java @@ -0,0 +1,45 @@ +package com.baeldung.commons.dbutils; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.dbutils.BasicRowProcessor; +import org.apache.commons.dbutils.BeanProcessor; + +import org.apache.commons.dbutils.QueryRunner; +import org.apache.commons.dbutils.handlers.BeanListHandler; + +public class EmployeeHandler extends BeanListHandler { + + private Connection connection; + + public EmployeeHandler(Connection con) { + super(Employee.class, new BasicRowProcessor(new BeanProcessor(getColumnsToFieldsMap()))); + this.connection = con; + } + + @Override + public List handle(ResultSet rs) throws SQLException { + List employees = super.handle(rs); + + QueryRunner runner = new QueryRunner(); + BeanListHandler handler = new BeanListHandler<>(Email.class); + String query = "SELECT * FROM email WHERE employeeid = ?"; + for (Employee employee : employees) { + List emails = runner.query(connection, query, handler, employee.getId()); + employee.setEmails(emails); + } + return employees; + } + + public static Map getColumnsToFieldsMap() { + Map columnsToFieldsMap = new HashMap<>(); + columnsToFieldsMap.put("FIRST_NAME", "firstName"); + columnsToFieldsMap.put("LAST_NAME", "lastName"); + columnsToFieldsMap.put("HIRED_DATE", "hiredDate"); + return columnsToFieldsMap; + } +} diff --git a/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java new file mode 100644 index 0000000000..0d08c94b47 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java @@ -0,0 +1,15 @@ +package com.baeldung.distinct; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; + +public class DistinctWithJavaFunction { + + public static Predicate distinctByKey(Function keyExtractor) { + Map seen = new ConcurrentHashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } + +} diff --git a/libraries/src/main/java/com/baeldung/distinct/Person.java b/libraries/src/main/java/com/baeldung/distinct/Person.java new file mode 100644 index 0000000000..8a2a5f7a45 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/distinct/Person.java @@ -0,0 +1,65 @@ +package com.baeldung.distinct; + +public class Person { + int age; + String name; + String email; + + public Person(int age, String name, String email) { + super(); + this.age = age; + this.name = name; + this.email = email; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [age="); + builder.append(age); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.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; + Person other = (Person) obj; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + return true; + } + +} diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java new file mode 100644 index 0000000000..069baeab9f --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java @@ -0,0 +1,20 @@ +package com.baeldung.eclipsecollections; + +import java.util.List; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.set.mutable.UnifiedSet; + +public class ConvertContainerToAnother { + + @SuppressWarnings("rawtypes") + public static List convertToList() { + UnifiedSet cars = new UnifiedSet<>(); + + cars.add("Toyota"); + cars.add("Mercedes"); + cars.add("Volkswagen"); + + return cars.toList(); + } +} diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java new file mode 100644 index 0000000000..cf6c06cec0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/eclipsecollections/Student.java @@ -0,0 +1,46 @@ +package com.baeldung.eclipsecollections; + +import java.util.List; + +public class Student { + + private String firstName; + private String lastName; + private List addresses; + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(String firstName, String lastName, List addresses) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.addresses = addresses; + } + + public String getFirstName() { + return this.firstName; + } + + public String getLastName() { + return this.lastName; + } + + public List getAddresses() { + return addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java new file mode 100644 index 0000000000..77c67abc84 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/geotools/ShapeFile.java @@ -0,0 +1,187 @@ +package com.baeldung.geotools; + +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.geotools.data.DataUtilities; +import org.geotools.data.DefaultTransaction; +import org.geotools.data.Transaction; +import org.geotools.data.shapefile.ShapefileDataStore; +import org.geotools.data.shapefile.ShapefileDataStoreFactory; +import org.geotools.data.simple.SimpleFeatureSource; +import org.geotools.data.simple.SimpleFeatureStore; +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.geotools.feature.simple.SimpleFeatureTypeBuilder; +import org.geotools.geometry.jts.JTSFactoryFinder; +import org.geotools.referencing.crs.DefaultGeographicCRS; +import org.geotools.swing.data.JFileDataStoreChooser; +import org.opengis.feature.simple.SimpleFeature; +import org.opengis.feature.simple.SimpleFeatureType; + +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.Point; + +public class ShapeFile { + + private static final String FILE_NAME = "shapefile.shp"; + + public static void main(String[] args) throws Exception { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String"); + + SimpleFeatureType CITY = createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + addLocations(featureBuilder, collection); + + File shapeFile = getNewShapeFile(); + + ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); + + Map params = new HashMap(); + params.put("url", shapeFile.toURI() + .toURL()); + params.put("create spatial index", Boolean.TRUE); + + ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); + dataStore.createSchema(CITY); + + // If you decide to use the TYPE type and create a Data Store with it, + // You will need to uncomment this line to set the Coordinate Reference System + // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); + + Transaction transaction = new DefaultTransaction("create"); + + String typeName = dataStore.getTypeNames()[0]; + SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); + + if (featureSource instanceof SimpleFeatureStore) { + SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; + + featureStore.setTransaction(transaction); + try { + featureStore.addFeatures(collection); + transaction.commit(); + + } catch (Exception problem) { + problem.printStackTrace(); + transaction.rollback(); + + } finally { + transaction.close(); + } + System.exit(0); // success! + } else { + System.out.println(typeName + " does not support read/write access"); + System.exit(1); + } + + } + + public static SimpleFeatureType createFeatureType() { + + SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); + builder.setName("Location"); + builder.setCRS(DefaultGeographicCRS.WGS84); + + builder.add("Location", Point.class); + builder.length(15) + .add("Name", String.class); + + SimpleFeatureType CITY = builder.buildFeatureType(); + + return CITY; + } + + public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) { + + Map> locations = new HashMap<>(); + + double lat = 13.752222; + double lng = 100.493889; + String name = "Bangkok"; + addToLocationMap(name, lat, lng, locations); + + lat = 53.083333; + lng = -0.15; + name = "New York"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.925278; + lng = 18.423889; + name = "Cape Town"; + addToLocationMap(name, lat, lng, locations); + + lat = -33.859972; + lng = 151.211111; + name = "Sydney"; + addToLocationMap(name, lat, lng, locations); + + lat = 45.420833; + lng = -75.69; + name = "Ottawa"; + addToLocationMap(name, lat, lng, locations); + + lat = 30.07708; + lng = 31.285909; + name = "Cairo"; + addToLocationMap(name, lat, lng, locations); + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + + for (Map.Entry> location : locations.entrySet()) { + Point point = geometryFactory.createPoint(new Coordinate(location.getValue() + .get(0), + location.getValue() + .get(1))); + featureBuilder.add(point); + featureBuilder.add(name); + SimpleFeature feature = featureBuilder.buildFeature(null); + collection.add(feature); + } + + } + + private static void addToLocationMap(String name, double lat, double lng, Map> locations) { + List coordinates = new ArrayList<>(); + + coordinates.add(lat); + coordinates.add(lng); + locations.put(name, coordinates); + } + + private static File getNewShapeFile() { + String filePath = new File(".").getAbsolutePath() + FILE_NAME; + + + JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp"); + chooser.setDialogTitle("Save shapefile"); + chooser.setSelectedFile(new File(filePath)); + + int returnVal = chooser.showSaveDialog(null); + + if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) { + System.exit(0); + } + + File shapeFile = chooser.getSelectedFile(); + if (shapeFile.equals(filePath)) { + System.out.println("Error: cannot replace " + filePath); + System.exit(0); + } + + return shapeFile; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java index 1033a7266d..364b05473a 100644 --- a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java +++ b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java @@ -6,11 +6,11 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; -public class JettyServer { +class JettyServer { private Server server; - public void start() throws Exception { + void start() throws Exception { int maxThreads = 100; int minThreads = 10; @@ -33,7 +33,7 @@ public class JettyServer { } - public void stop() throws Exception { + void stop() throws Exception { server.stop(); } } diff --git a/libraries/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java b/libraries/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java index a2c1573dca..60436865a9 100644 --- a/libraries/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java +++ b/libraries/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java @@ -1,8 +1,8 @@ package com.baeldung.junitparams; -public class SafeAdditionUtil { +class SafeAdditionUtil { - public int safeAdd(int a, int b) { + int safeAdd(int a, int b) { long result = ((long) a) + b; if (result > Integer.MAX_VALUE) { return Integer.MAX_VALUE; diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServer.java b/libraries/src/main/java/com/baeldung/netty/NettyServer.java index b9d35859d0..319829b7b6 100644 --- a/libraries/src/main/java/com/baeldung/netty/NettyServer.java +++ b/libraries/src/main/java/com/baeldung/netty/NettyServer.java @@ -13,7 +13,7 @@ public class NettyServer { private int port; - public NettyServer(int port) { + private NettyServer(int port) { this.port = port; } @@ -27,7 +27,7 @@ public class NettyServer { new NettyServer(port).run(); } - public void run() throws Exception { + private void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries/src/main/java/com/baeldung/netty/RequestData.java index e7404c1663..402aa1ef91 100644 --- a/libraries/src/main/java/com/baeldung/netty/RequestData.java +++ b/libraries/src/main/java/com/baeldung/netty/RequestData.java @@ -4,27 +4,27 @@ public class RequestData { private int intValue; private String stringValue; - public int getIntValue() { + int getIntValue() { return intValue; } - public void setIntValue(int intValue) { + void setIntValue(int intValue) { this.intValue = intValue; } - public String getStringValue() { + String getStringValue() { return stringValue; } - public void setStringValue(String stringValue) { + void setStringValue(String stringValue) { this.stringValue = stringValue; } @Override public String toString() { return "RequestData{" + - "intValue=" + intValue + - ", stringValue='" + stringValue + '\'' + - '}'; + "intValue=" + intValue + + ", stringValue='" + stringValue + '\'' + + '}'; } } diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries/src/main/java/com/baeldung/netty/ResponseData.java index ce388a9a3d..51d1adaafb 100644 --- a/libraries/src/main/java/com/baeldung/netty/ResponseData.java +++ b/libraries/src/main/java/com/baeldung/netty/ResponseData.java @@ -3,11 +3,11 @@ package com.baeldung.netty; public class ResponseData { private int intValue; - public int getIntValue() { + int getIntValue() { return intValue; } - public void setIntValue(int intValue) { + void setIntValue(int intValue) { this.intValue = intValue; } diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java b/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java index ee33679dfe..16e2a61bd3 100644 --- a/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java +++ b/libraries/src/main/java/com/baeldung/netty/ResponseDataDecoder.java @@ -1,11 +1,11 @@ package com.baeldung.netty; -import java.util.List; - import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; +import java.util.List; + public class ResponseDataDecoder extends ReplayingDecoder { @Override diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java new file mode 100644 index 0000000000..fb6a01d4c1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java @@ -0,0 +1,73 @@ +package com.baeldung.neuroph; + +import org.neuroph.core.Layer; +import org.neuroph.core.NeuralNetwork; +import org.neuroph.core.Neuron; +import org.neuroph.core.data.DataSet; +import org.neuroph.core.data.DataSetRow; +import org.neuroph.nnet.learning.BackPropagation; +import org.neuroph.util.ConnectionFactory; +import org.neuroph.util.NeuralNetworkType; + +public class NeurophXOR { + + public static NeuralNetwork assembleNeuralNetwork() { + + Layer inputLayer = new Layer(); + inputLayer.addNeuron(new Neuron()); + inputLayer.addNeuron(new Neuron()); + + Layer hiddenLayerOne = new Layer(); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + + Layer hiddenLayerTwo = new Layer(); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + + Layer outputLayer = new Layer(); + outputLayer.addNeuron(new Neuron()); + + NeuralNetwork ann = new NeuralNetwork(); + + ann.addLayer(0, inputLayer); + ann.addLayer(1, hiddenLayerOne); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1)); + ann.addLayer(2, hiddenLayerTwo); + ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); + ann.addLayer(3, outputLayer); + ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); + + ann.setInputNeurons(inputLayer.getNeurons()); + ann.setOutputNeurons(outputLayer.getNeurons()); + + ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON); + return ann; + } + + public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) { + int inputSize = 2; + int outputSize = 1; + DataSet ds = new DataSet(inputSize, outputSize); + + DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); + ds.addRow(rOne); + DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); + ds.addRow(rTwo); + DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); + ds.addRow(rThree); + DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); + ds.addRow(rFour); + + BackPropagation backPropagation = new BackPropagation(); + backPropagation.setMaxIterations(1000); + + ann.learn(ds, backPropagation); + return ann; + } +} diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 0000000000..59e13efaa0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java b/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java deleted file mode 100644 index dd44e96a3a..0000000000 --- a/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.baeldung.opennlp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.logging.Logger; - -import opennlp.tools.chunker.ChunkerME; -import opennlp.tools.chunker.ChunkerModel; -import opennlp.tools.cmdline.postag.POSModelLoader; -import opennlp.tools.doccat.DoccatFactory; -import opennlp.tools.doccat.DoccatModel; -import opennlp.tools.doccat.DocumentCategorizerME; -import opennlp.tools.doccat.DocumentSample; -import opennlp.tools.doccat.DocumentSampleStream; -import opennlp.tools.namefind.NameFinderME; -import opennlp.tools.namefind.TokenNameFinderModel; -import opennlp.tools.postag.POSModel; -import opennlp.tools.postag.POSSample; -import opennlp.tools.postag.POSTaggerME; -import opennlp.tools.sentdetect.SentenceDetectorME; -import opennlp.tools.sentdetect.SentenceModel; -import opennlp.tools.tokenize.Tokenizer; -import opennlp.tools.tokenize.TokenizerME; -import opennlp.tools.tokenize.TokenizerModel; -import opennlp.tools.tokenize.WhitespaceTokenizer; -import opennlp.tools.util.InputStreamFactory; -import opennlp.tools.util.InvalidFormatException; -import opennlp.tools.util.ObjectStream; -import opennlp.tools.util.PlainTextByLineStream; -import opennlp.tools.util.Span; -import opennlp.tools.util.TrainingParameters; - -public class OpenNLP { - - private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName()); - private final static String text = buildString(); - private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." }; - - private DoccatModel docCatModel; - - public static void main(String[] args) { - new OpenNLP(); - } - - public static String buildString(){ - StringBuilder sb = new StringBuilder(); - sb.append("To get to the south:"); - sb.append(" Go to the store."); - sb.append(" Buy a compass."); - sb.append(" Use the compass."); - sb.append(" Then walk to the south."); - return sb.toString(); - } - - public OpenNLP() { - try { - sentenceDetector(); - tokenizer(); - nameFinder(); - locationFinder(); - trainDocumentCategorizer(); - documentCategorizer(); - partOfSpeechTagger(); - chunker(); - } catch (InvalidFormatException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void sentenceDetector() throws InvalidFormatException, IOException { - - InputStream is = new FileInputStream("OpenNLP/en-sent.bin"); - SentenceModel model = new SentenceModel(is); - SentenceDetectorME sdetector = new SentenceDetectorME(model); - String sentences[] = sdetector.sentDetect(text); - for (String sentence : sentences) { - LOGGER.info(sentence); - } - is.close(); - } - - public void tokenizer() throws InvalidFormatException, IOException { - InputStream is = new FileInputStream("OpenNLP/en-token.bin"); - TokenizerModel model = new TokenizerModel(is); - Tokenizer tokenizer = new TokenizerME(model); - String tokens[] = tokenizer.tokenize(text); - for (String token : tokens) { - LOGGER.info(token); - } - is.close(); - } - - public static void nameFinder() throws IOException { - InputStream is = new FileInputStream("OpenNLP/en-ner-person.bin"); - TokenNameFinderModel model = new TokenNameFinderModel(is); - is.close(); - NameFinderME nameFinder = new NameFinderME(model); - Span nameSpans[] = nameFinder.find(sentence); - String[] names = Span.spansToStrings(nameSpans, sentence); - Arrays.stream(names).forEach(LOGGER::info); - for (String name : names) { - LOGGER.info(name); - } - } - - public static void locationFinder() throws IOException { - InputStream is = new FileInputStream("OpenNLP/en-ner-location.bin"); - TokenNameFinderModel model = new TokenNameFinderModel(is); - is.close(); - NameFinderME nameFinder = new NameFinderME(model); - Span locationSpans[] = nameFinder.find(sentence); - String[] locations = Span.spansToStrings(locationSpans, sentence); - Arrays.stream(locations).forEach(LOGGER::info); - for (String location : locations) { - LOGGER.info(location); - } - } - - public void trainDocumentCategorizer() { - - try { - InputStreamFactory isf = new InputStreamFactory() { - public InputStream createInputStream() throws IOException { - return new FileInputStream("OpenNLP/doc-cat.train"); - } - }; - ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); - ObjectStream sampleStream = new DocumentSampleStream(lineStream); - DoccatFactory docCatFactory = new DoccatFactory(); - docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void documentCategorizer() { - DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel); - double[] outcomes = myCategorizer.categorize(sentence); - String category = myCategorizer.getBestCategory(outcomes); - - if (category.equalsIgnoreCase("GOOD")) { - LOGGER.info("Document is positive :) "); - } else { - LOGGER.info("Document is negative :( "); - } - } - - public static void partOfSpeechTagger() throws IOException { - try { - POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin")); - POSTaggerME posTaggerME = new POSTaggerME(posModel); - InputStreamFactory isf = new InputStreamFactory() { - public InputStream createInputStream() throws IOException { - return new FileInputStream("OpenNLP/PartOfSpeechTag.txt"); - } - }; - ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); - String line; - while ((line = lineStream.read()) != null) { - String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line); - String[] tags = posTaggerME.tag(whitespaceTokenizerLine); - POSSample posSample = new POSSample(whitespaceTokenizerLine, tags); - LOGGER.info(posSample.toString()); - } - lineStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void chunker() throws IOException { - InputStream is = new FileInputStream("OpenNLP/en-chunker.bin"); - ChunkerModel cModel = new ChunkerModel(is); - ChunkerME chunkerME = new ChunkerME(cModel); - String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"}; - String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"}; - String chunks[] = chunkerME.chunk(taggedSentence, pos); - for (String chunk : chunks) { - LOGGER.info(chunk); - } - } - -} diff --git a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java index 20853aa01b..4757d912f8 100644 --- a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java +++ b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java @@ -20,44 +20,44 @@ public class QuartzExample { Scheduler sched = schedFact.getScheduler(); JobDetail job = JobBuilder.newJob(SimpleJob.class) - .withIdentity("myJob", "group1") - .usingJobData("jobSays", "Hello World!") - .usingJobData("myFloatValue", 3.141f) - .build(); + .withIdentity("myJob", "group1") + .usingJobData("jobSays", "Hello World!") + .usingJobData("myFloatValue", 3.141f) + .build(); Trigger trigger = TriggerBuilder.newTrigger() - .withIdentity("myTrigger", "group1") - .startNow() - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); - + .withIdentity("myTrigger", "group1") + .startNow() + .withSchedule(SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(40) + .repeatForever()) + .build(); + JobDetail jobA = JobBuilder.newJob(JobA.class) - .withIdentity("jobA", "group2") - .build(); - + .withIdentity("jobA", "group2") + .build(); + JobDetail jobB = JobBuilder.newJob(JobB.class) - .withIdentity("jobB", "group2") - .build(); - + .withIdentity("jobB", "group2") + .build(); + Trigger triggerA = TriggerBuilder.newTrigger() - .withIdentity("triggerA", "group2") - .startNow() - .withPriority(15) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(40) - .repeatForever()) - .build(); - - Trigger triggerB = TriggerBuilder.newTrigger() - .withIdentity("triggerB", "group2") - .startNow() - .withPriority(10) - .withSchedule(SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(20) - .repeatForever()) - .build(); + .withIdentity("triggerA", "group2") + .startNow() + .withPriority(15) + .withSchedule(SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(40) + .repeatForever()) + .build(); + + Trigger triggerB = TriggerBuilder.newTrigger() + .withIdentity("triggerB", "group2") + .startNow() + .withPriority(10) + .withSchedule(SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(20) + .repeatForever()) + .build(); sched.scheduleJob(job, trigger); sched.scheduleJob(jobA, triggerA); diff --git a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java index 986c5e96e5..554d3b9358 100644 --- a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java +++ b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java @@ -9,13 +9,11 @@ public class SimpleJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap dataMap = context.getJobDetail() - .getJobDataMap(); + .getJobDataMap(); String jobSays = dataMap.getString("jobSays"); float myFloatValue = dataMap.getFloat("myFloatValue"); System.out.println("Job says: " + jobSays + ", and val is: " + myFloatValue); - } - } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java new file mode 100644 index 0000000000..66a9e0ebce --- /dev/null +++ b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java @@ -0,0 +1,76 @@ +package com.baeldung.rome; + +import com.sun.syndication.feed.synd.*; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.SyndFeedOutput; +import com.sun.syndication.io.XmlReader; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RSSRomeExample { + + public static void main(String[] args) throws IOException, FeedException { + SyndFeed feed = createFeed(); + addEntryToFeed(feed); + publishFeed(feed); + readFeed(); + } + + private static SyndFeed createFeed() { + SyndFeed feed = new SyndFeedImpl(); + feed.setFeedType("rss_1.0"); + feed.setTitle("Test title"); + feed.setLink("http://www.somelink.com"); + feed.setDescription("Basic description"); + + return feed; + } + + private static void addEntryToFeed(SyndFeed feed) { + SyndEntry entry = new SyndEntryImpl(); + entry.setTitle("Entry title"); + entry.setLink("http://www.somelink.com/entry1"); + + addDescriptionToEntry(entry); + addCategoryToEntry(entry); + + feed.setEntries(Arrays.asList(entry)); + } + + private static void addDescriptionToEntry(SyndEntry entry) { + SyndContent description = new SyndContentImpl(); + description.setType("text/html"); + description.setValue("First entry"); + + entry.setDescription(description); + } + + private static void addCategoryToEntry(SyndEntry entry) { + List categories = new ArrayList<>(); + SyndCategory category = new SyndCategoryImpl(); + category.setName("Sophisticated category"); + categories.add(category); + + entry.setCategories(categories); + } + + private static void publishFeed(SyndFeed feed) throws IOException, FeedException { + Writer writer = new FileWriter("xyz.txt"); + SyndFeedOutput syndFeedOutput = new SyndFeedOutput(); + syndFeedOutput.output(feed, writer); + writer.close(); + } + + private static SyndFeed readFeed() throws IOException, FeedException { + URL feedSource = new URL("http://rssblog.whatisrss.com/feed/"); + SyndFeedInput input = new SyndFeedInput(); + return input.build(new XmlReader(feedSource)); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/stm/Account.java b/libraries/src/main/java/com/baeldung/stm/Account.java index 734d332308..8b17f87120 100644 --- a/libraries/src/main/java/com/baeldung/stm/Account.java +++ b/libraries/src/main/java/com/baeldung/stm/Account.java @@ -10,20 +10,20 @@ public class Account { private final TxnLong lastUpdate; private final TxnInteger balance; - public Account(final int balance) { + Account(final int balance) { this.lastUpdate = StmUtils.newTxnLong(System.currentTimeMillis()); this.balance = StmUtils.newTxnInteger(balance); } - public Integer getBalance() { + Integer getBalance() { return balance.atomicGet(); } - public void adjustBy(final int amount) { + void adjustBy(final int amount) { adjustBy(amount, System.currentTimeMillis()); } - public void adjustBy(final int amount, final long date) { + private void adjustBy(final int amount, final long date) { StmUtils.atomic(() -> { balance.increment(amount); lastUpdate.set(date); @@ -34,7 +34,7 @@ public class Account { }); } - public void transferTo(final Account other, final int amount) { + void transferTo(final Account other, final int amount) { StmUtils.atomic(() -> { final long date = System.currentTimeMillis(); adjustBy(-amount, date); @@ -45,6 +45,6 @@ public class Account { @Override public String toString() { return StmUtils.atomic((TxnCallable) - txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); + txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn)); } } \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..430759f3a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -0,0 +1,22 @@ +package com.baeldung.streamutils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.util.StreamUtils; + +public class CopyStream { + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } + + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } +} diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..6ee4a1ef3a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -0,0 +1,11 @@ +package com.baeldung.streamutils; + +import java.io.InputStream; + +import org.springframework.util.StreamUtils; + +public class DrainStream { + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } +} diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java similarity index 64% rename from libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java rename to libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java index 4f07d556b9..d17a7dcf1b 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java @@ -1,20 +1,23 @@ package com.baeldung.awaitility; -import static org.awaitility.Awaitility.await; -import static org.awaitility.Awaitility.fieldIn; -import static org.awaitility.Awaitility.given; -import static org.awaitility.proxy.AwaitilityClassProxy.to; -import static org.hamcrest.Matchers.equalTo; - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - import org.awaitility.Awaitility; import org.awaitility.Duration; import org.junit.Before; import org.junit.Test; -public class AsyncServiceUnitTest { +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.awaitility.Awaitility.fieldIn; +import static org.awaitility.Awaitility.given; +import static org.awaitility.Awaitility.setDefaultPollDelay; +import static org.awaitility.Awaitility.setDefaultPollInterval; +import static org.awaitility.Awaitility.setDefaultTimeout; +import static org.awaitility.proxy.AwaitilityClassProxy.to; +import static org.hamcrest.Matchers.equalTo; + +public class AsyncServiceLongRunningUnitTest { private AsyncService asyncService; @Before @@ -25,28 +28,28 @@ public class AsyncServiceUnitTest { @Test public void givenAsyncService_whenInitialize_thenInitOccurs1() { asyncService.initialize(); - Callable isInitialized = () -> asyncService.isInitialized(); + Callable isInitialized = asyncService::isInitialized; await().until(isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs2() { asyncService.initialize(); - Callable isInitialized = () -> asyncService.isInitialized(); + Callable isInitialized = asyncService::isInitialized; await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) - .atMost(Duration.FIVE_SECONDS) - .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) - .until(isInitialized); + .atMost(Duration.FIVE_SECONDS) + .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) + .until(isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() { - Awaitility.setDefaultPollInterval(10, TimeUnit.MILLISECONDS); - Awaitility.setDefaultPollDelay(Duration.ZERO); - Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); + setDefaultPollInterval(10, TimeUnit.MILLISECONDS); + setDefaultPollDelay(Duration.ZERO); + setDefaultTimeout(Duration.ONE_MINUTE); asyncService.initialize(); - await().until(() -> asyncService.isInitialized()); + await().until(asyncService::isInitialized); } @Test @@ -59,14 +62,14 @@ public class AsyncServiceUnitTest { public void givenAsyncService_whenInitialize_thenInitOccurs3() { asyncService.initialize(); await().until(fieldIn(asyncService) - .ofType(boolean.class) - .andWithName("initialized"), equalTo(true)); + .ofType(boolean.class) + .andWithName("initialized"), equalTo(true)); } @Test public void givenValue_whenAddValue_thenValueAdded() { asyncService.initialize(); - await().until(() -> asyncService.isInitialized()); + await().until(asyncService::isInitialized); long value = 5; asyncService.addValue(value); await().until(asyncService::getValue, equalTo(value)); @@ -76,9 +79,9 @@ public class AsyncServiceUnitTest { public void givenAsyncService_whenGetValue_thenExceptionIgnored() { asyncService.initialize(); given().ignoreException(IllegalStateException.class) - .await() - .atMost(Duration.FIVE_SECONDS) - .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) - .until(asyncService::getValue, equalTo(0L)); + .await() + .atMost(Duration.FIVE_SECONDS) + .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) + .until(asyncService::getValue, equalTo(0L)); } } diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java new file mode 100644 index 0000000000..6b7364a0a5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.bytebuddy; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.agent.ByteBuddyAgent; +import net.bytebuddy.dynamic.DynamicType; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; +import net.bytebuddy.implementation.FixedValue; +import net.bytebuddy.implementation.MethodDelegation; +import net.bytebuddy.matcher.ElementMatchers; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import static net.bytebuddy.matcher.ElementMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ByteBuddyUnitTest { + + @Test + public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException { + DynamicType.Unloaded unloadedType = new ByteBuddy() + .subclass(Object.class) + .method(ElementMatchers.isToString()) + .intercept(FixedValue.value("Hello World ByteBuddy!")) + .make(); + + Class dynamicType = unloadedType.load(getClass().getClassLoader()) + .getLoaded(); + + assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!"); + } + + @Test + public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception { + ByteBuddyAgent.install(); + new ByteBuddy() + .redefine(Foo.class) + .method(named("sayHelloFoo")) + .intercept(FixedValue.value("Hello Foo Redefined")) + .make() + .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent()); + Foo f = new Foo(); + assertEquals(f.sayHelloFoo(), "Hello Foo Redefined"); + } + + @Test + public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException { + + String r = new ByteBuddy() + .subclass(Foo.class) + .method( + named("sayHelloFoo") + .and(isDeclaredBy(Foo.class) + .and(returns(String.class))) + ) + .intercept(MethodDelegation.to(Bar.class)) + .make() + .load(getClass().getClassLoader()) + .getLoaded() + .newInstance() + .sayHelloFoo(); + + assertEquals(r, Bar.sayHelloBar()); + } + + @Test + public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception { + Class type = new ByteBuddy() + .subclass(Object.class) + .name("MyClassName") + .defineMethod("custom", String.class, Modifier.PUBLIC) + .intercept(MethodDelegation.to(Bar.class)) + .defineField("x", String.class, Modifier.PUBLIC) + .make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); + + Method m = type.getDeclaredMethod("custom", null); + + assertEquals(m.invoke(type.newInstance()), Bar.sayHelloBar()); + assertNotNull(type.getDeclaredField("x")); + + } + + +} diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java index 033cc47c74..1224d73724 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java @@ -19,14 +19,14 @@ public class BeanGeneratorIntegrationTest { beanGenerator.addProperty("name", String.class); Object myBean = beanGenerator.create(); Method setter = myBean - .getClass() - .getMethod("setName", String.class); + .getClass() + .getMethod("setName", String.class); setter.invoke(myBean, "some string value set by a cglib"); //then Method getter = myBean - .getClass() - .getMethod("getName"); + .getClass() + .getMethod("getName"); assertEquals("some string value set by a cglib", getter.invoke(myBean)); } } diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java index a89d9fe2c3..93b34bf92b 100644 --- a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java +++ b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java @@ -1,6 +1,10 @@ package com.baeldung.cglib.proxy; -import com.baeldung.cglib.mixin.*; +import com.baeldung.cglib.mixin.Class1; +import com.baeldung.cglib.mixin.Class2; +import com.baeldung.cglib.mixin.Interface1; +import com.baeldung.cglib.mixin.Interface2; +import com.baeldung.cglib.mixin.MixinInterface; import net.sf.cglib.proxy.Mixin; import org.junit.Test; @@ -12,8 +16,8 @@ public class MixinUnitTest { public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception { //when Mixin mixin = Mixin.create( - new Class[]{Interface1.class, Interface2.class, MixinInterface.class}, - new Object[]{new Class1(), new Class2()} + new Class[]{Interface1.class, Interface2.class, MixinInterface.class}, + new Object[]{new Class1(), new Class2()} ); MixinInterface mixinDelegate = (MixinInterface) mixin; diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java new file mode 100644 index 0000000000..9c0a0ac910 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.chronicle.queue; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import org.junit.Test; + +import net.openhft.chronicle.Chronicle; +import net.openhft.chronicle.ChronicleQueueBuilder; +import net.openhft.chronicle.ExcerptTailer; +import net.openhft.chronicle.tools.ChronicleTools; + +public class ChronicleQueueIntegrationTest { + + @Test + public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException { + File queueDir = Files.createTempDirectory("chronicle-queue").toFile(); + ChronicleTools.deleteOnExit(queueDir.getPath()); + + Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build(); + String stringVal = "Hello World"; + int intVal = 101; + long longVal = System.currentTimeMillis(); + double doubleVal = 90.00192091d; + + ChronicleQueue.writeToQueue(chronicle, stringVal, intVal, longVal, doubleVal); + + ExcerptTailer tailer = chronicle.createTailer(); + while (tailer.nextIndex()) { + assertEquals(stringVal, tailer.readUTF()); + assertEquals(intVal, tailer.readInt()); + assertEquals(longVal, tailer.readLong()); + assertEquals((Double) doubleVal, (Double) tailer.readDouble()); + } + tailer.finish(); + tailer.close(); + chronicle.close(); + } + +} diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java new file mode 100644 index 0000000000..9f670af03c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueTest.java @@ -0,0 +1,159 @@ +package com.baeldung.circularfifoqueue; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.queue.CircularFifoQueue; +import org.junit.Assert; +import org.junit.Test; + +public class CircularFifoQueueTest { + + private static final int DEFAULT_SIZE = 32; + + private static final int FIXED_SIZE = 5; + + private static final int COLLECTION_SIZE = 7; + + private static final String TEST_COLOR = "Red"; + + private static final String TEST_COLOR_BY_INDEX = "Blue"; + + @Test + public void whenUsingDefualtConstructor_correctSizeQueue() { + CircularFifoQueue bits = new CircularFifoQueue<>(); + + Assert.assertEquals(DEFAULT_SIZE, bits.maxSize()); + } + + @Test + public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(FIXED_SIZE, colors.maxSize()); + } + + @Test + public void whenUsingCollectionConstructor_correctSizeQueue() { + List days = new ArrayList<>(); + days.add("Monday"); + days.add("Tuesday"); + days.add("Wednesday"); + days.add("Thursday"); + days.add("Friday"); + days.add("Saturday"); + days.add("Sunday"); + + CircularFifoQueue daysOfWeek = new CircularFifoQueue<>(days); + + Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize()); + } + + @Test + public void givenAddElements_whenGetElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1)); + } + + @Test + public void givenAddElements_whenPollElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.poll()); + } + + @Test + public void givenAddElements_whenPeekQueue_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.peek()); + } + + @Test + public void givenAddElements_whenElementQueue_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.element()); + } + + @Test + public void givenAddElements_whenRemoveElement_correctElement() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(TEST_COLOR, colors.remove()); + } + + @Test + public void givenFullQueue_whenClearQueue_getIsEmpty() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + colors.clear(); + + Assert.assertEquals(true, colors.isEmpty()); + } + + @Test + public void givenFullQueue_whenCheckFull_getIsFull() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + Assert.assertEquals(false, colors.isFull()); + } + + @Test + public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() { + CircularFifoQueue colors = new CircularFifoQueue<>(5); + colors.add("Red"); + colors.add("Blue"); + colors.add("Green"); + colors.offer("White"); + colors.offer("Black"); + + colors.add("Orange"); + colors.add("Violet"); + colors.add("Pink"); + + Assert.assertEquals(true, colors.isAtFullCapacity()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java new file mode 100644 index 0000000000..cd9a7baaf3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java @@ -0,0 +1,37 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Catalog; +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.junit.Assert; +import org.junit.Test; + +import static com.baeldung.commons.chain.AtmConstants.*; + +public class AtmChainTest { + + public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460; + public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0; + public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4; + public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1; + public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1; + + @Test + public void givenInputsToContext_whenAppliedChain_thenExpectedContext() { + Context context = new AtmRequestContext(); + context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460); + Catalog catalog = new AtmCatalog(); + Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN); + try { + atmWithdrawalChain.execute(context); + } catch (Exception e) { + e.printStackTrace(); + } + Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED)); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java index 64a3932fb3..e46d8654a2 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java @@ -2,16 +2,12 @@ package com.baeldung.commons.collections; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; -import org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap; -import org.apache.commons.collections4.bidimap.DualTreeBidiMap; -import org.apache.commons.collections4.bidimap.TreeBidiMap; import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -/** - * Created by smatt on 03/07/2017. - */ public class BidiMapUnitTest { @Test diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java index 9166865484..aa8b799c9d 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java @@ -3,14 +3,17 @@ package com.baeldung.commons.collections; import com.baeldung.commons.collectionutil.Address; import com.baeldung.commons.collectionutil.Customer; -import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; import org.junit.Before; import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -36,13 +39,13 @@ public class CollectionUtilsGuideTest { linkedList1 = new LinkedList<>(list1); } - + @Test public void givenList_whenAddIgnoreNull_thenNoNullAdded() { CollectionUtils.addIgnoreNull(list1, null); assertFalse(list1.contains(null)); } - + @Test public void givenTwoSortedLists_whenCollated_thenSorted() { List sortedList = CollectionUtils.collate(list1, list2); @@ -51,63 +54,69 @@ public class CollectionUtilsGuideTest { assertTrue(sortedList.get(0).getName().equals("Bob")); assertTrue(sortedList.get(2).getName().equals("Daniel")); } - + @Test public void givenListOfCustomers_whenTransformed_thenListOfAddress() { - Collection
addressCol = CollectionUtils.collect(list1, customer -> { - return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); + Collection
addressCol = CollectionUtils.collect(list1, new Transformer() { + public Address transform(Customer customer) { + return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); + } }); - + List
addressList = new ArrayList<>(addressCol); assertTrue(addressList.size() == 3); assertTrue(addressList.get(0).getLocality().equals("locality1")); } - + @Test public void givenCustomerList_whenFiltered_thenCorrectSize() { - - boolean isModified = CollectionUtils.filter(linkedList1, customer -> Arrays.asList("Daniel","Kyle").contains(customer.getName())); - + + boolean isModified = CollectionUtils.filter(linkedList1, new Predicate() { + public boolean evaluate(Customer customer) { + return Arrays.asList("Daniel", "Kyle").contains(customer.getName()); + } + }); + //filterInverse does the opposite. It removes the element from the list if the Predicate returns true //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection - + assertTrue(isModified && linkedList1.size() == 2); } - + @Test public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() { List emptyList = new ArrayList<>(); List nullList = null; - + //Very handy at times where we want to check if a collection is not null and not empty too. //isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading assertTrue(CollectionUtils.isNotEmpty(list1)); assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(emptyList)); } - + @Test public void givenCustomerListAndASubcollection_whenChecked_thenTrue() { assertTrue(CollectionUtils.isSubCollection(list3, list1)); } - + @Test public void givenTwoLists_whenIntersected_thenCheckSize() { Collection intersection = CollectionUtils.intersection(list1, list3); assertTrue(intersection.size() == 2); } - + @Test public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() { Collection result = CollectionUtils.subtract(list1, list3); assertFalse(result.contains(customer1)); } - + @Test public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() { Collection union = CollectionUtils.union(list1, list2); assertTrue(union.contains(customer1)); assertTrue(union.contains(customer4)); } - + } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java new file mode 100644 index 0000000000..4685d84781 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -0,0 +1,132 @@ +package com.baeldung.commons.collections; + +import org.apache.commons.collections4.MapIterator; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.collections4.PredicateUtils; +import org.apache.commons.collections4.TransformerUtils; +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; +import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class MapUtilsTest { + + private String[][] color2DArray = new String[][]{ + {"RED", "#FF0000"}, + {"GREEN", "#00FF00"}, + {"BLUE", "#0000FF"} + }; + private String[] color1DArray = new String[]{ + "RED", "#FF0000", + "GREEN", "#00FF00", + "BLUE", "#0000FF" + }; + private Map colorMap; + + @Before + public void createMap() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); + } + + @Test + public void whenCreateMapFrom2DArray_theMapIsCreated() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color2DArray); + + assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length))); + + assertThat(this.colorMap, hasEntry("RED", "#FF0000")); + assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); + assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); + } + + @Test + public void whenCreateMapFrom1DArray_theMapIsCreated() { + this.colorMap = MapUtils.putAll(new HashMap(), this.color1DArray); + + assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2))); + + assertThat(this.colorMap, hasEntry("RED", "#FF0000")); + assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); + assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); + } + + @Test + public void whenVerbosePrintMap_thenMustPrintFormattedMap() { + MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); + } + + @Test + public void whenGetKeyNotPresent_thenMustReturnDefaultValue() { + String defaultColorStr = "COLOR_NOT_FOUND"; + String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr); + + assertEquals(color, defaultColorStr); + } + + @Test + public void whenGetOnNullMap_thenMustReturnDefaultValue() { + String defaultColorStr = "COLOR_NOT_FOUND"; + String color = MapUtils.getString(null, "RED", defaultColorStr); + + assertEquals(color, defaultColorStr); + } + + @Test + public void whenInvertMap_thenMustReturnInvertedMap() { + Map invColorMap = MapUtils.invertMap(this.colorMap); + + int size = invColorMap.size(); + Assertions.assertThat(invColorMap) + .hasSameSizeAs(colorMap) + .containsKeys(this.colorMap.values().toArray(new String[size])) + .containsValues(this.colorMap.keySet().toArray(new String[size])); + } + + @Test(expected = IllegalArgumentException.class) + public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { + Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll( + new HashMap(), + this.color1DArray)); + + rgbMap.put("ORANGE", "#FFA500"); + } + + @Test(expected = IllegalArgumentException.class) + public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { + Map uniqValuesMap + = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); + + uniqValuesMap.put("NEW_RED", "#FF0000"); + } + + @Test + public void whenCreateLazyMap_theMapIsCreated() { + Map intStrMap = MapUtils.lazyMap( + new HashMap(), + TransformerUtils.stringValueTransformer()); + + assertThat(intStrMap, is(anEmptyMap())); + + intStrMap.get(1); + intStrMap.get(2); + intStrMap.get(3); + + assertThat(intStrMap, is(aMapWithSize(3))); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java index 4d264e3aea..7d214bc5c5 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java @@ -11,9 +11,6 @@ import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -/** - * Created by smatt on 21/06/2017. - */ public class SetUtilsUnitTest { @Test(expected = IllegalArgumentException.class) @@ -27,33 +24,33 @@ public class SetUtilsUnitTest { @Test public void givenTwoSets_whenDifference_thenSetView() { - Set a = new HashSet<>(Arrays.asList(1,2,5)); - Set b = new HashSet<>(Arrays.asList(1,2)); + Set a = new HashSet<>(Arrays.asList(1, 2, 5)); + Set b = new HashSet<>(Arrays.asList(1, 2)); SetUtils.SetView result = SetUtils.difference(a, b); assertTrue(result.size() == 1 && result.contains(5)); } @Test public void givenTwoSets_whenUnion_thenUnionResult() { - Set a = new HashSet<>(Arrays.asList(1,2,5)); - Set b = new HashSet<>(Arrays.asList(1,2)); - Set expected = new HashSet<>(Arrays.asList(1,2,5)); + Set a = new HashSet<>(Arrays.asList(1, 2, 5)); + Set b = new HashSet<>(Arrays.asList(1, 2)); + Set expected = new HashSet<>(Arrays.asList(1, 2, 5)); SetUtils.SetView union = SetUtils.union(a, b); assertTrue(SetUtils.isEqualSet(expected, union)); } @Test public void givenTwoSets_whenIntersection_thenIntersectionResult() { - Set a = new HashSet<>(Arrays.asList(1,2,5)); - Set b = new HashSet<>(Arrays.asList(1,2)); - Set expected = new HashSet<>(Arrays.asList(1,2)); + Set a = new HashSet<>(Arrays.asList(1, 2, 5)); + Set b = new HashSet<>(Arrays.asList(1, 2)); + Set expected = new HashSet<>(Arrays.asList(1, 2)); SetUtils.SetView intersect = SetUtils.intersection(a, b); assertTrue(SetUtils.isEqualSet(expected, intersect)); } @Test public void givenSet_whenTransformedSet_thenTransformedResult() { - Set a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2 ); + Set a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2); a.add(2); assertEquals(a.toArray()[0], 4); @@ -65,19 +62,19 @@ public class SetUtilsUnitTest { @Test public void givenTwoSet_whenDisjunction_thenDisjunctionSet() { - Set a = new HashSet<>(Arrays.asList(1,2,5)); - Set b = new HashSet<>(Arrays.asList(1,2,3)); + Set a = new HashSet<>(Arrays.asList(1, 2, 5)); + Set b = new HashSet<>(Arrays.asList(1, 2, 3)); SetUtils.SetView result = SetUtils.disjunction(a, b); assertTrue(result.toSet().contains(5) && result.toSet().contains(3)); } @Test public void givenSet_when_OrderedSet_thenMaintainElementOrder() { - Set set = new HashSet<>(Arrays.asList(10,1,5)); + Set set = new HashSet<>(Arrays.asList(10, 1, 5)); System.out.println("unordered set: " + set); Set orderedSet = SetUtils.orderedSet(new HashSet<>()); - orderedSet.addAll(Arrays.asList(10,1,5)); + orderedSet.addAll(Arrays.asList(10, 1, 5)); System.out.println("ordered set = " + orderedSet); } } \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java index 6b2777c289..7a05228e51 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java @@ -1,10 +1,5 @@ package com.baeldung.commons.collections.orderedmap; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.map.LinkedMap; @@ -12,6 +7,11 @@ import org.apache.commons.collections4.map.ListOrderedMap; import org.junit.Before; import org.junit.Test; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + public class OrderedMapUnitTest { private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"}; diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java new file mode 100644 index 0000000000..4ce250d979 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java @@ -0,0 +1,85 @@ +package com.baeldung.commons.collections4; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.collections4.Bag; +import org.apache.commons.collections4.bag.CollectionBag; +import org.apache.commons.collections4.bag.HashBag; +import org.apache.commons.collections4.bag.TreeBag; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class BagTests { + + Bag baseBag; + TreeBag treeBag; + + @Before + public void before() { + baseBag = new HashBag(); + treeBag = new TreeBag(); + treeBag = new TreeBag(); + } + + @Test + public void whenAdd_thenRemoveFromBaseBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + baseBag.remove("lemon"); + Assert.assertEquals(3, baseBag.size()); + Assert.assertFalse(baseBag.contains("lemon")); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertFalse(baseBag.containsAll(containList)); + } + + @Test + public void whenAdd_thenRemoveFromBaseCollectionBag_thenContainsCorrect() { + baseBag.add("apple", 2); + baseBag.add("lemon", 6); + baseBag.add("lime"); + + CollectionBag baseCollectionBag = new CollectionBag( + baseBag); + + baseCollectionBag.remove("lemon"); + Assert.assertEquals(8, baseCollectionBag.size()); + Assert.assertTrue(baseCollectionBag.contains("lemon")); + + baseCollectionBag.remove("lemon",1); + Assert.assertEquals(7, baseCollectionBag.size()); + + Assert.assertTrue(baseBag.uniqueSet().contains("apple")); + + List containList = new ArrayList(); + containList.add("apple"); + containList.add("lemon"); + containList.add("lime"); + Assert.assertTrue(baseBag.containsAll(containList)); + } + + @Test + public void whenAddtoTreeBag_thenRemove_thenContainsCorrect() { + treeBag.add("banana", 8); + treeBag.add("apple", 2); + treeBag.add("lime"); + + Assert.assertEquals(11, treeBag.size()); + Assert.assertEquals("apple", treeBag.first()); + Assert.assertEquals("lime", treeBag.last()); + + treeBag.remove("apple"); + Assert.assertEquals(9, treeBag.size()); + Assert.assertEquals("banana", treeBag.first()); + + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java new file mode 100644 index 0000000000..6f47b89396 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.csv; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.Test; + +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringWriter; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class CSVReaderWriterTest { + + public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { + { + put("Dan Simmons", "Hyperion"); + put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); + } + }); + public static final String[] HEADERS = { "author", "title" }; + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; + + @Test + public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + Iterable records = CSVFormat.DEFAULT + .withHeader(HEADERS) + .withFirstRecordAsHeader() + .parse(in); + for (CSVRecord record : records) { + String author = record.get("author"); + String title = record.get("title"); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { + StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + AUTHOR_BOOK_MAP.forEach((author, title) -> { + try { + printer.printRecord(author, title); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + assertEquals(EXPECTED_FILESTREAM, sw + .toString() + .trim()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java new file mode 100644 index 0000000000..bc7623589c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java @@ -0,0 +1,163 @@ +package com.baeldung.commons.dbutils; + +import org.apache.commons.dbutils.AsyncQueryRunner; +import org.apache.commons.dbutils.DbUtils; +import org.apache.commons.dbutils.QueryRunner; +import org.apache.commons.dbutils.handlers.BeanListHandler; +import org.apache.commons.dbutils.handlers.MapListHandler; +import org.apache.commons.dbutils.handlers.ScalarHandler; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DbUtilsUnitTest { + + private Connection connection; + + @Before + public void setupDB() throws Exception { + Class.forName("org.h2.Driver"); + String db = "jdbc:h2:mem:;INIT=runscript from 'classpath:/employees.sql'"; + connection = DriverManager.getConnection(db); + } + + @After + public void closeBD() { + DbUtils.closeQuietly(connection); + } + + @Test + public void givenResultHandler_whenExecutingQuery_thenExpectedList() throws SQLException { + MapListHandler beanListHandler = new MapListHandler(); + + QueryRunner runner = new QueryRunner(); + List> list = runner.query(connection, "SELECT * FROM employee", beanListHandler); + + assertEquals(list.size(), 5); + assertEquals(list.get(0) + .get("firstname"), "John"); + assertEquals(list.get(4) + .get("firstname"), "Christian"); + } + + @Test + public void givenResultHandler_whenExecutingQuery_thenEmployeeList() throws SQLException { + BeanListHandler beanListHandler = new BeanListHandler<>(Employee.class); + + QueryRunner runner = new QueryRunner(); + List employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler); + + assertEquals(employeeList.size(), 5); + assertEquals(employeeList.get(0) + .getFirstName(), "John"); + assertEquals(employeeList.get(4) + .getFirstName(), "Christian"); + } + + @Test + public void givenResultHandler_whenExecutingQuery_thenExpectedScalar() throws SQLException { + ScalarHandler scalarHandler = new ScalarHandler<>(); + + QueryRunner runner = new QueryRunner(); + String query = "SELECT COUNT(*) FROM employee"; + long count = runner.query(connection, query, scalarHandler); + + assertEquals(count, 5); + } + + @Test + public void givenResultHandler_whenExecutingQuery_thenEmailsSetted() throws SQLException { + EmployeeHandler employeeHandler = new EmployeeHandler(connection); + + QueryRunner runner = new QueryRunner(); + List employees = runner.query(connection, "SELECT * FROM employee", employeeHandler); + + assertEquals(employees.get(0) + .getEmails() + .size(), 2); + assertEquals(employees.get(2) + .getEmails() + .size(), 3); + assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId()); + } + + @Test + public void givenResultHandler_whenExecutingQuery_thenAllPropertiesSetted() throws SQLException { + EmployeeHandler employeeHandler = new EmployeeHandler(connection); + + QueryRunner runner = new QueryRunner(); + String query = "SELECT * FROM employee_legacy"; + List employees = runner.query(connection, query, employeeHandler); + + assertEquals((int) employees.get(0).getId(), 1); + assertEquals(employees.get(0).getFirstName(), "John"); + } + + @Test + public void whenInserting_thenInserted() throws SQLException { + QueryRunner runner = new QueryRunner(); + String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)"; + + int numRowsInserted = runner.update(connection, insertSQL, "Leia", "Kane", 60000.60, new Date()); + + assertEquals(numRowsInserted, 1); + } + + @Test + public void givenHandler_whenInserting_thenExpectedId() throws SQLException { + ScalarHandler scalarHandler = new ScalarHandler<>(); + + QueryRunner runner = new QueryRunner(); + String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)"; + + int newId = runner.insert(connection, insertSQL, scalarHandler, "Jenny", "Medici", 60000.60, new Date()); + + assertEquals(newId, 6); + } + + @Test + public void givenSalary_whenUpdating_thenUpdated() throws SQLException { + double salary = 35000; + + QueryRunner runner = new QueryRunner(); + String updateSQL = "UPDATE employee SET salary = salary * 1.1 WHERE salary <= ?"; + int numRowsUpdated = runner.update(connection, updateSQL, salary); + + assertEquals(numRowsUpdated, 3); + } + + @Test + public void whenDeletingRecord_thenDeleted() throws SQLException { + QueryRunner runner = new QueryRunner(); + String deleteSQL = "DELETE FROM employee WHERE id = ?"; + int numRowsDeleted = runner.update(connection, deleteSQL, 3); + + assertEquals(numRowsDeleted, 1); + } + + @Test + public void givenAsyncRunner_whenExecutingQuery_thenExpectedList() throws Exception { + AsyncQueryRunner runner = new AsyncQueryRunner(Executors.newCachedThreadPool()); + + EmployeeHandler employeeHandler = new EmployeeHandler(connection); + String query = "SELECT * FROM employee"; + Future> future = runner.query(connection, query, employeeHandler); + List employeeList = future.get(10, TimeUnit.SECONDS); + + assertEquals(employeeList.size(), 5); + } + +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java index 15620455aa..191387d088 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java @@ -2,9 +2,10 @@ package com.baeldung.commons.lang3; import org.apache.commons.lang3.StringUtils; import org.junit.Test; + import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class StringUtilsUnitTest { @Test diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java new file mode 100644 index 0000000000..dffde3917c --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.eclipse.collections.impl.block.factory.HashingStrategies; +import org.eclipse.collections.impl.utility.ListIterate; +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithEclipseCollectionsUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName)); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge)); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java new file mode 100644 index 0000000000..68775fac66 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; +import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey; + +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithJavaFunctionUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getName())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = personList.stream() + .filter(distinctByKey(p -> p.getAge())) + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 2); + } + + @Test + public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() { + List personListFiltered = personList.stream() + .distinct() + .collect(Collectors.toList()); + assertTrue(personListFiltered.size() == 5); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java new file mode 100644 index 0000000000..f50c76a486 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import one.util.streamex.StreamEx; + +public class DistinctWithStreamexUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getName) + .toList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = StreamEx.of(personList) + .distinct(Person::getAge) + .toList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java new file mode 100644 index 0000000000..b4025cd313 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.distinct; + +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class DistinctWithVavrUnitTest { + List personList; + + @Before + public void init() { + personList = PersonDataGenerator.getPersonListWithFakeValues(); + } + + @Test + public void whenFilterListByName_thenSizeShouldBe4() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getName) + .toJavaList(); + assertTrue(personListFiltered.size() == 4); + } + + @Test + public void whenFilterListByAge_thenSizeShouldBe2() { + List personListFiltered = io.vavr.collection.List.ofAll(personList) + .distinctBy(Person::getAge) + .toJavaList(); + assertTrue(personListFiltered.size() == 2); + } + +} diff --git a/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java new file mode 100644 index 0000000000..51590005ac --- /dev/null +++ b/libraries/src/test/java/com/baeldung/distinct/PersonDataGenerator.java @@ -0,0 +1,19 @@ +package com.baeldung.distinct; + +import java.util.Arrays; +import java.util.List; + +public class PersonDataGenerator { + + public static List getPersonListWithFakeValues() { + // @formatter:off + return Arrays.asList( + new Person(20, "Jhon", "jhon@test.com"), + new Person(20, "Jhon", "jhon1@test.com"), + new Person(20, "Jhon", "jhon2@test.com"), + new Person(21, "Tom", "Tom@test.com"), + new Person(21, "Mark", "Mark@test.com"), + new Person(20, "Julia", "jhon@test.com")); + // @formatter:on + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java new file mode 100644 index 0000000000..ee369fc75b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AllSatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.allSatisfy(Predicates.greaterThan(0)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java new file mode 100644 index 0000000000..a3314ebee6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertTrue; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class AnySatisfyPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + boolean result = list.anySatisfy(Predicates.greaterThan(30)); + + assertTrue(result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java new file mode 100644 index 0000000000..ee384c2f9d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/CollectPatternTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; + +import org.assertj.core.api.Assertions; +import org.junit.Test; + +public class CollectPatternTest { + + @Test + public void whenCollect_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + + MutableList students = FastList.newListWith(student1, student2); + + MutableList lastNames = students.collect(Student::getLastName); + + Assertions.assertThat(lastNames) + .containsExactly("Hopkins", "Adams"); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java new file mode 100644 index 0000000000..4655431872 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherTest.java @@ -0,0 +1,18 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Test; + +public class ConvertContainerToAnotherTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void whenConvertContainerToAnother_thenCorrect() { + MutableList cars = (MutableList) ConvertContainerToAnother.convertToList(); + + Assertions.assertThat(cars) + .containsExactlyElementsOf(FastList.newListWith("Volkswagen", "Toyota", "Mercedes")); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java new file mode 100644 index 0000000000..c5b5e1c412 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/DetectPatternTest.java @@ -0,0 +1,26 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class DetectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenDetect_thenCorrect() { + Integer result = list.detect(Predicates.greaterThan(30)); + + Assertions.assertThat(result) + .isEqualTo(41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java new file mode 100644 index 0000000000..021c72e91e --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/FlatCollectTest.java @@ -0,0 +1,50 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class FlatCollectTest { + + MutableList addresses1; + MutableList addresses2; + MutableList addresses3; + MutableList addresses4; + + List expectedAddresses; + MutableList students; + + @Before + public void setup() { + String address1 = "73 Pacific St., Forest Hills, NY 11375"; + String address2 = "93 Bayport Ave., South Richmond Hill, NY 11419"; + String address3 = "548 Market St, San Francisco, CA 94104"; + String address4 = "8605 Santa Monica Blvd, West Hollywood, CA 90069"; + + this.addresses1 = FastList.newListWith(address1, address2); + this.addresses2 = FastList.newListWith(address3, address4); + Student student1 = new Student("John", "Hopkins", addresses1); + Student student2 = new Student("George", "Adams", addresses2); + this.addresses2 = FastList.newListWith(address3, address4); + this.students = FastList.newListWith(student1, student2); + this.expectedAddresses = new ArrayList<>(); + this.expectedAddresses.add("73 Pacific St., Forest Hills, NY 11375"); + this.expectedAddresses.add("93 Bayport Ave., South Richmond Hill, NY 11419"); + this.expectedAddresses.add("548 Market St, San Francisco, CA 94104"); + this.expectedAddresses.add("8605 Santa Monica Blvd, West Hollywood, CA 90069"); + } + + @Test + public void whenFlatCollect_thenCorrect() { + MutableList addresses = students.flatCollect(Student::getAddresses); + + Assertions.assertThat(addresses) + .containsExactlyElementsOf(this.expectedAddresses); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java new file mode 100644 index 0000000000..8cea575222 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ForEachPatternTest.java @@ -0,0 +1,29 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Test; + +public class ForEachPatternTest { + + @SuppressWarnings("unchecked") + @Test + public void whenInstantiateAndChangeValues_thenCorrect() { + Pair pair1 = Tuples.pair(1, "One"); + Pair pair2 = Tuples.pair(2, "Two"); + Pair pair3 = Tuples.pair(3, "Three"); + + UnifiedMap map = UnifiedMap.newMapWith(pair1, pair2, pair3); + + for (int i = 0; i < map.size(); i++) { + map.put(i + 1, "New Value"); + } + + for (int i = 0; i < map.size(); i++) { + assertEquals("New Value", map.get(i + 1)); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java new file mode 100644 index 0000000000..bcd34021b1 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternTest.java @@ -0,0 +1,23 @@ +package com.baeldung.eclipsecollections; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class InjectIntoPatternTest { + + @Test + public void whenInjectInto_thenCorrect() { + List list = Lists.mutable.of(1, 2, 3, 4); + int result = 5; + for (int i = 0; i < list.size(); i++) { + Integer v = list.get(i); + result = result + v.intValue(); + } + + assertEquals(15, result); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java new file mode 100644 index 0000000000..9c216ecc87 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/LazyIterationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.factory.Lists; +import org.junit.Test; + +public class LazyIterationTest { + + @Test + public void whenLazyIteration_thenCorrect() { + Student student1 = new Student("John", "Hopkins"); + Student student2 = new Student("George", "Adams"); + Student student3 = new Student("Jennifer", "Rodriguez"); + + MutableList students = Lists.mutable.with(student1, student2, student3); + LazyIterable lazyStudents = students.asLazy(); + LazyIterable lastNames = lazyStudents.collect(Student::getLastName); + + Assertions.assertThat(lastNames) + .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez")); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java new file mode 100644 index 0000000000..c055413cd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/PartitionPatternTest.java @@ -0,0 +1,44 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.partition.list.PartitionMutableList; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class PartitionPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void whenAnySatisfiesCondition_thenCorrect() { + MutableList numbers = list; + PartitionMutableList partitionedFolks = numbers.partition(new Predicate() { + + /** + * + */ + private static final long serialVersionUID = -1551138743683678406L; + + public boolean accept(Integer each) { + return each > 30; + } + }); + MutableList greaterThanThirty = partitionedFolks.getSelected() + .sortThis(); + MutableList smallerThanThirty = partitionedFolks.getRejected() + .sortThis(); + + Assertions.assertThat(smallerThanThirty) + .containsExactly(1, 5, 8, 17, 23); + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java new file mode 100644 index 0000000000..1666c86333 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/RejectPatternTest.java @@ -0,0 +1,29 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class RejectPatternTest { + + MutableList list; + MutableList expectedList; + + @Before + public void setup() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + this.expectedList = FastList.newListWith(1, 5, 8, 17, 23); + } + + @Test + public void whenReject_thenCorrect() { + MutableList notGreaterThanThirty = list.reject(Predicates.greaterThan(30)) + .sortThis(); + + Assertions.assertThat(notGreaterThanThirty) + .containsExactlyElementsOf(this.expectedList); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java new file mode 100644 index 0000000000..d79c864fc5 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/SelectPatternTest.java @@ -0,0 +1,42 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.block.factory.Predicates; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.junit.Before; +import org.junit.Test; + +public class SelectPatternTest { + + MutableList list; + + @Before + public void getList() { + this.list = FastList.newListWith(1, 8, 5, 41, 31, 17, 23, 38); + } + + @Test + public void givenListwhenSelect_thenCorrect() { + MutableList greaterThanThirty = list.select(Predicates.greaterThan(30)) + .sortThis(); + + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); + } + + @SuppressWarnings("rawtypes") + public MutableList selectUsingLambda() { + return list.select(each -> each > 30) + .sortThis(); + } + + @SuppressWarnings("unchecked") + @Test + public void givenListwhenSelectUsingLambda_thenCorrect() { + MutableList greaterThanThirty = selectUsingLambda(); + + Assertions.assertThat(greaterThanThirty) + .containsExactly(31, 38, 41); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java new file mode 100644 index 0000000000..29f0c23954 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipTest.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipsecollections; + +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.tuple.Tuples; + +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; + +public class ZipTest { + + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("1", "Porsche"); + Pair pair2 = Tuples.pair("2", "Volvo"); + Pair pair3 = Tuples.pair("3", "Toyota"); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + + @Test + public void whenZip_thenCorrect() { + MutableList numbers = Lists.mutable.with("1", "2", "3", "Ignored"); + MutableList cars = Lists.mutable.with("Porsche", "Volvo", "Toyota"); + MutableList> pairs = numbers.zip(cars); + + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); + } +} diff --git a/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java new file mode 100644 index 0000000000..a2d8be44ec --- /dev/null +++ b/libraries/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexTest.java @@ -0,0 +1,33 @@ +package com.baeldung.eclipsecollections; + +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.list.mutable.FastList; +import org.eclipse.collections.impl.tuple.Tuples; +import org.junit.Before; +import org.junit.Test; + +public class ZipWithIndexTest { + + MutableList> expectedPairs; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + Pair pair1 = Tuples.pair("Porsche", 0); + Pair pair2 = Tuples.pair("Volvo", 1); + Pair pair3 = Tuples.pair("Toyota", 2); + expectedPairs = Lists.mutable.of(pair1, pair2, pair3); + } + + @Test + public void whenZip_thenCorrect() { + MutableList cars = FastList.newListWith("Porsche", "Volvo", "Toyota"); + MutableList> pairs = cars.zipWithIndex(); + + Assertions.assertThat(pairs) + .containsExactlyElementsOf(this.expectedPairs); + } +} diff --git a/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java new file mode 100644 index 0000000000..44cd47edc3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/geotools/GeoToolsUnitTestTest.java @@ -0,0 +1,27 @@ +package com.baeldung.geotools; + +import static org.junit.Assert.assertNotNull; + +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.junit.Test; +import org.opengis.feature.simple.SimpleFeatureType; + +public class GeoToolsUnitTestTest { + + @Test + public void givenFeatureType_whenAddLocations_returnFeatureCollection() { + + DefaultFeatureCollection collection = new DefaultFeatureCollection(); + + SimpleFeatureType CITY = ShapeFile.createFeatureType(); + + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY); + + ShapeFile.addLocations(featureBuilder, collection); + + assertNotNull(collection); + + } + +} diff --git a/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java b/libraries/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java similarity index 88% rename from libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java rename to libraries/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java index 1a1c5ef868..80588ecc03 100644 --- a/libraries/src/test/java/com/baeldung/hikaricp/HikariCPUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java @@ -6,7 +6,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; -public class HikariCPUnitTest { +public class HikariCPIntegrationTest { @Test public void givenConnection_thenFetchDbData() { diff --git a/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java new file mode 100644 index 0000000000..5ecd4442d8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hll/HLLLongRunningUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.hll; + + +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hashing; +import net.agkn.hll.HLL; +import org.assertj.core.data.Offset; +import org.junit.Test; + +import java.util.stream.LongStream; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class HLLLongRunningUnitTest { + + @Test + public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { + //given + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; + HashFunction hashFunction = Hashing.murmur3_128(); + HLL hll = new HLL(14, 5); + + //when + LongStream.range(0, numberOfElements).forEach(element -> { + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + hll.addRaw(hashedValue); + } + ); + + //then + long cardinality = hll.cardinality(); + assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference)); + } + + @Test + public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() { + //given + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; + HashFunction hashFunction = Hashing.murmur3_128(); + HLL firstHll = new HLL(15, 5); + HLL secondHLL = new HLL(15, 5); + + //when + LongStream.range(0, numberOfElements).forEach(element -> { + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + firstHll.addRaw(hashedValue); + } + ); + + LongStream.range(numberOfElements, numberOfElements * 2).forEach(element -> { + long hashedValue = hashFunction.newHasher().putLong(element).hash().asLong(); + secondHLL.addRaw(hashedValue); + } + ); + + //then + firstHll.union(secondHLL); + long cardinality = firstHll.cardinality(); + assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2)); + } +} diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java new file mode 100644 index 0000000000..167aef5ec6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiIntegrationTest.java @@ -0,0 +1,140 @@ +package com.baeldung.hoverfly; + +import static io.specto.hoverfly.junit.core.SimulationSource.dsl; +import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service; +import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes; +import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.time.StopWatch; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import io.specto.hoverfly.junit.core.SimulationSource; +import io.specto.hoverfly.junit.rule.HoverflyRule; + +public class HoverflyApiIntegrationTest { + + private static final SimulationSource source = dsl( + service("http://www.baeldung.com") + .get("/api/courses/1") + .willReturn(success().body( + jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses") + .willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS) + .forMethod("POST"), + + service(matches("www.*dung.com")) + .get(startsWith("/api/student")) + .queryParam("page", any()) + .willReturn(success()) + + .post(equalsTo("/api/student")) + .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))) + .willReturn(success()) + + .put("/api/student/1") + .body(matchesJsonPath("$.name")) + .willReturn(success()) + + .post("/api/student") + .body(equalsToXml("2John")) + .willReturn(success()) + + .put("/api/student/2") + .body(matchesXPath("/student/name")) + .willReturn(success())); + + @ClassRule + public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); + private final RestTemplate restTemplate = new RestTemplate(); + + @Test + public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/courses/1", String.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); + } + + @Test + public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/courses", null, Void.class); + stopWatch.stop(); + long postTime = stopWatch.getTime(); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime)); + } + + @Test + public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/student?page=3", Void.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + @Test + public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/1")) + .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "2John", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + + @Test + public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/2")) + .body("" + + "2Monica"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } +} diff --git a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java index 39d54085e2..5e65c585aa 100644 --- a/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jasypt/JasyptUnitTest.java @@ -8,7 +8,9 @@ import org.jasypt.util.text.BasicTextEncryptor; import org.junit.Ignore; import org.junit.Test; -import static junit.framework.Assert.*; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertNotSame; +import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertEquals; public class JasyptUnitTest { @@ -30,7 +32,7 @@ public class JasyptUnitTest { } @Test - public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame(){ + public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldBeSame() { String password = "secret-pass"; BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); @@ -43,7 +45,7 @@ public class JasyptUnitTest { } @Test - public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame(){ + public void givenTextPassword_whenOneWayEncryption_thenCompareEncryptedPasswordsShouldNotBeSame() { String password = "secret-pass"; BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor(); String encryptedPassword = passwordEncryptor.encryptPassword(password); @@ -56,7 +58,6 @@ public class JasyptUnitTest { } - @Test @Ignore("should have installed local_policy.jar") public void givenTextPrivateData_whenDecrypt_thenCompareToEncryptedWithCustomAlgorithm() { @@ -77,7 +78,7 @@ public class JasyptUnitTest { @Test @Ignore("should have installed local_policy.jar") - public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt(){ + public void givenTextPrivateData_whenDecryptOnHighPerformance_thenDecrypt() { //given String privateData = "secret-data"; PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); diff --git a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java index 578f9ff902..e916a229f7 100644 --- a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java @@ -8,7 +8,6 @@ import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.jdo.Transaction; -import java.util.Iterator; import java.util.List; import static org.junit.Assert.assertEquals; diff --git a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java similarity index 64% rename from jooq/src/test/java/com/baeldung/JOOLUnitTest.java rename to libraries/src/test/java/com/baeldung/jool/JOOLTest.java index 17873db50a..ba20e153fd 100644 --- a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.jool; import org.jooq.lambda.Seq; import org.jooq.lambda.Unchecked; @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,7 +21,7 @@ import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertEquals; import static org.jooq.lambda.tuple.Tuple.tuple; -public class JOOLUnitTest { +public class JOOLTest { @Test public void givenSeq_whenCheckContains_shouldReturnTrue() { List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); @@ -54,58 +55,58 @@ public class JOOLUnitTest { @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) + Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2)) ); assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) + Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) ); assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) + Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) ); assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) + Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), + Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) ); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) + Seq.of(1, 2, 3).cycle().limit(9).toList(), + Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) ); assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) + Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) ); assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) + Seq.of(1, 2, 3, 4).intersperse(0).toList(), + Arrays.asList(1, 0, 2, 0, 3, 0, 4) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 + Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), + 5 ); assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) + Seq.of(1, 2, 3, 4).reverse().toList(), + Arrays.asList(4, 3, 2, 1) ); } @@ -117,20 +118,20 @@ public class JOOLUnitTest { expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy + Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), + expectedAfterGroupBy ); assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" + Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), + "!abc" ); assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" + Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), + "abc!" ); } @@ -138,13 +139,13 @@ public class JOOLUnitTest { public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), + Arrays.asList(3, 4, 5) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), + Arrays.asList(3, 4, 5) ); } @@ -152,19 +153,19 @@ public class JOOLUnitTest { public void givenSeq_whenZip_shouldHaveZippedSeq() { assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), + Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) ); assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), + Arrays.asList("1:a", "2:b", "3:c") ); assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) + Seq.of("a", "b", "c").zipWithIndex().toList(), + Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) ); } @@ -187,8 +188,8 @@ public class JOOLUnitTest { //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -197,13 +198,13 @@ public class JOOLUnitTest { public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { //when List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(elem -> methodThatThrowsChecked(elem))) - .collect(Collectors.toList()); + .map(Unchecked.function(this::methodThatThrowsChecked)) + .collect(Collectors.toList()); //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -236,5 +237,4 @@ public class JOOLUnitTest { Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) ); } - } diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java new file mode 100644 index 0000000000..4a6ecf8e46 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -0,0 +1,58 @@ +package com.baeldung.neuroph; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.neuroph.core.NeuralNetwork; + +import static org.junit.Assert.*; + +public class XORTest { + private NeuralNetwork ann = null; + + private void print(String input, double output, double actual) { + System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output); + } + + @Before + public void annInit() { + ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); + } + + @Test + public void leftDisjunctTest() { + ann.setInput(0, 1); + ann.calculate(); + print("0, 1", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); + } + + @Test + public void rightDisjunctTest() { + ann.setInput(1, 0); + ann.calculate(); + print("1, 0", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); + } + + @Test + public void bothFalseConjunctTest() { + ann.setInput(0, 0); + ann.calculate(); + print("0, 0", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); + } + + @Test + public void bothTrueConjunctTest() { + ann.setInput(1, 1); + ann.calculate(); + print("1, 1", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); + } + + @After + public void annClose() { + ann = null; + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 0000000000..b7619202fe --- /dev/null +++ b/libraries/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + Exceptions.log(logger).run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithMessage() { + Exceptions.log(logger, "Something went wrong:").run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} diff --git a/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java b/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java deleted file mode 100644 index 38bc8e002b..0000000000 --- a/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.baeldung.opennlp; - -import opennlp.tools.chunker.ChunkerME; -import opennlp.tools.chunker.ChunkerModel; -import opennlp.tools.cmdline.postag.POSModelLoader; -import opennlp.tools.doccat.DoccatFactory; -import opennlp.tools.doccat.DoccatModel; -import opennlp.tools.doccat.DocumentCategorizerME; -import opennlp.tools.doccat.DocumentSample; -import opennlp.tools.doccat.DocumentSampleStream; -import opennlp.tools.namefind.NameFinderME; -import opennlp.tools.namefind.TokenNameFinderModel; -import opennlp.tools.postag.POSModel; -import opennlp.tools.postag.POSSample; -import opennlp.tools.postag.POSTaggerME; -import opennlp.tools.sentdetect.SentenceDetectorME; -import opennlp.tools.sentdetect.SentenceModel; -import opennlp.tools.tokenize.WhitespaceTokenizer; -import opennlp.tools.util.InputStreamFactory; -import opennlp.tools.util.ObjectStream; -import opennlp.tools.util.PlainTextByLineStream; -import opennlp.tools.util.Span; -import opennlp.tools.util.TrainingParameters; -import org.junit.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; - -public class OpenNLPTests { - - private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south."; - private final static String sentence[] = new String[]{"James", "Jordan", "live", "in", "Oklahoma", "city", "."}; - - @Test - public void givenText_WhenDetectSentences_ThenCountSentences() { - InputStream is; - SentenceModel model; - try { - is = new FileInputStream("OpenNLP/en-sent.bin"); - model = new SentenceModel(is); - SentenceDetectorME sdetector = new SentenceDetectorME(model); - String sentences[] = sdetector.sentDetect(text); - assertEquals(4, sentences.length); - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void givenText_WhenDetectTokens_ThenVerifyNames() { - InputStream is; - TokenNameFinderModel model; - try { - is = new FileInputStream("OpenNLP/en-ner-person.bin"); - model = new TokenNameFinderModel(is); - is.close(); - NameFinderME nameFinder = new NameFinderME(model); - Span nameSpans[] = nameFinder.find(sentence); - String[] names = Span.spansToStrings(nameSpans, sentence); - assertEquals(1, names.length); - assertEquals("James Jordan", names[0]); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void givenText_WhenDetectTokens_ThenVerifyLocations() { - InputStream is; - TokenNameFinderModel model; - try { - is = new FileInputStream("OpenNLP/en-ner-location.bin"); - model = new TokenNameFinderModel(is); - is.close(); - NameFinderME nameFinder = new NameFinderME(model); - Span locationSpans[] = nameFinder.find(sentence); - String[] locations = Span.spansToStrings(locationSpans, sentence); - assertEquals(1, locations.length); - assertEquals("Oklahoma", locations[0]); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void givenText_WhenCategorizeDocument_ThenVerifyDocumentContent() { - DoccatModel docCatModel; - try { - InputStreamFactory isf = new InputStreamFactory() { - public InputStream createInputStream() throws IOException { - return new FileInputStream("OpenNLP/doc-cat.train"); - } - }; - ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); - ObjectStream sampleStream = new DocumentSampleStream(lineStream); - DoccatFactory docCatFactory = new DoccatFactory(); - docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory); - DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel); - double[] outcomes = myCategorizer.categorize(sentence); - String category = myCategorizer.getBestCategory(outcomes); - assertEquals("GOOD", category); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void givenText_WhenTagDocument_ThenVerifyTaggedString() { - try { - POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin")); - POSTaggerME posTaggerME = new POSTaggerME(posModel); - InputStreamFactory isf = new InputStreamFactory() { - public InputStream createInputStream() throws IOException { - return new FileInputStream("OpenNLP/PartOfSpeechTag.txt"); - } - }; - ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); - String line; - while ((line = lineStream.read()) != null) { - String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line); - String[] tags = posTaggerME.tag(whitespaceTokenizerLine); - POSSample posSample = new POSSample(whitespaceTokenizerLine, tags); - assertEquals("Out_IN of_IN the_DT night_NN that_WDT covers_VBZ me_PRP", posSample.toString()); - } - lineStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void givenText_WhenChunked_ThenCountChunks() { - try { - InputStream is = new FileInputStream("OpenNLP/en-chunker.bin"); - ChunkerModel cModel = new ChunkerModel(is); - ChunkerME chunkerME = new ChunkerME(cModel); - String pos[] = new String[]{"NNP", "NNP", "NNP", "POS", "NNP", "NN", "VBD"}; - String chunks[] = chunkerME.chunk(sentence, pos); - assertEquals(7, chunks.length); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java index 2952938cd9..b152b22964 100644 --- a/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java +++ b/libraries/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java @@ -8,7 +8,11 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.RequestResponsePact; import org.junit.Rule; import org.junit.Test; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.HashMap; @@ -20,7 +24,7 @@ public class PactConsumerDrivenContractUnitTest { @Rule public PactProviderRuleMk2 mockProvider - = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); + = new PactProviderRuleMk2("test_provider", "localhost", 8080, this); @Pact(consumer = "test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { @@ -28,25 +32,25 @@ public class PactConsumerDrivenContractUnitTest { headers.put("Content-Type", "application/json"); return builder - .given("test GET ") - .uponReceiving("GET REQUEST") - .path("/") - .method("GET") - .willRespondWith() - .status(200) - .headers(headers) - .body("{\"condition\": true, \"name\": \"tom\"}") - .given("test POST") - .uponReceiving("POST REQUEST") - .method("POST") - .headers(headers) - .body("{\"name\": \"Michael\"}") - .path("/create") - .willRespondWith() - .status(201) - .headers(headers) - .body("") - .toPact(); + .given("test GET ") + .uponReceiving("GET REQUEST") + .path("/") + .method("GET") + .willRespondWith() + .status(200) + .headers(headers) + .body("{\"condition\": true, \"name\": \"tom\"}") + .given("test POST") + .uponReceiving("POST REQUEST") + .method("POST") + .headers(headers) + .body("{\"name\": \"Michael\"}") + .path("/create") + .willRespondWith() + .status(201) + .headers(headers) + .body("") + .toPact(); } @@ -55,7 +59,7 @@ public class PactConsumerDrivenContractUnitTest { public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() { //when ResponseEntity response - = new RestTemplate().getForEntity(mockProvider.getUrl(), String.class); + = new RestTemplate().getForEntity(mockProvider.getUrl(), String.class); //then assertThat(response.getStatusCode().value()).isEqualTo(200); @@ -69,10 +73,10 @@ public class PactConsumerDrivenContractUnitTest { //when ResponseEntity postResponse = new RestTemplate().exchange( - mockProvider.getUrl() + "/create", - HttpMethod.POST, - new HttpEntity<>(jsonBody, httpHeaders), - String.class + mockProvider.getUrl() + "/create", + HttpMethod.POST, + new HttpEntity<>(jsonBody, httpHeaders), + String.class ); //then diff --git a/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java new file mode 100644 index 0000000000..acc7718ea8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -0,0 +1,97 @@ +package com.baeldung.pcollections; + +import org.junit.Test; +import org.pcollections.HashPMap; +import org.pcollections.HashTreePMap; +import org.pcollections.HashTreePSet; +import org.pcollections.MapPSet; +import org.pcollections.PVector; +import org.pcollections.TreePVector; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PCollectionsUnitTest { + + @Test + public void whenEmpty_thenCreateEmptyHashPMap() { + HashPMap pmap = HashTreePMap.empty(); + assertEquals(pmap.size(), 0); + } + + @Test + public void givenKeyValue_whenSingleton_thenCreateNonEmptyHashPMap() { + HashPMap pmap1 = HashTreePMap.singleton("key1", "value1"); + assertEquals(pmap1.size(), 1); + } + + @Test + public void givenExistingHashMap_whenFrom_thenCreateHashPMap() { + Map map = new HashMap<>(); + map.put("mkey1", "mval1"); + map.put("mkey2", "mval2"); + + HashPMap pmap2 = HashTreePMap.from(map); + assertEquals(pmap2.size(), 2); + } + + @Test + public void whenHashPMapMethods_thenPerformOperations() { + + HashPMap pmap = HashTreePMap.empty(); + HashPMap pmap0 = pmap.plus("key1", "value1"); + + Map map = new HashMap<>(); + map.put("key2", "val2"); + map.put("key3", "val3"); + + HashPMap pmap1 = pmap0.plusAll(map); + HashPMap pmap2 = pmap1.minus("key1"); + HashPMap pmap3 = pmap2.minusAll(map.keySet()); + + assertEquals(pmap0.size(), 1); + assertEquals(pmap1.size(), 3); + assertFalse(pmap2.containsKey("key1")); + assertEquals(pmap3.size(), 0); + } + + @Test + public void whenTreePVectorMethods_thenPerformOperations() { + TreePVector pVector = TreePVector.empty(); + + TreePVector pV1 = pVector.plus("e1"); + TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4")); + + assertEquals(1, pV1.size()); + assertEquals(4, pV2.size()); + + TreePVector pV3 = pV2.minus("e1"); + TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4")); + + assertEquals(pV3.size(), 3); + assertEquals(pV4.size(), 0); + + TreePVector pSub = pV2.subList(0, 2); + assertTrue(pSub.contains("e1") && pSub.contains("e2")); + + PVector pVW = pV2.with(0, "e10"); + assertEquals(pVW.get(0), "e10"); + } + + @Test + public void whenMapPSetMethods_thenPerformOperations() { + + MapPSet pSet = HashTreePSet.empty() + .plusAll(Arrays.asList("e1", "e2", "e3", "e4")); + assertEquals(pSet.size(), 4); + + MapPSet pSet1 = pSet.minus("e4"); + assertFalse(pSet1.contains("e4")); + } + +} diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9a65075e5b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + +} diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java index a8dbaadc5a..f08b43f69b 100644 --- a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java @@ -5,12 +5,12 @@ import org.junit.Assert; import org.junit.Test; public class StrBuilderTest { - + @Test public void whenReplaced_thenCorrect() { StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); strBuilder.replaceAll("example", "new"); - + Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); } @@ -21,4 +21,4 @@ public class StrBuilderTest { Assert.assertEquals(new StrBuilder(""), strBuilder); } -} +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java b/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java index b9268d67b3..fafba2fbb5 100644 --- a/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/text/WordUtilsTest.java @@ -13,11 +13,11 @@ public class WordUtilsTest { Assert.assertEquals("To Be Capitalized!", result); } - + @Test public void whenContainsWords_thenCorrect() { boolean containsWords = WordUtils.containsAllWords("String to search", "to", "search"); - + Assert.assertTrue(containsWords); } } diff --git a/libraries/src/test/resources/book.csv b/libraries/src/test/resources/book.csv new file mode 100644 index 0000000000..d709152a5e --- /dev/null +++ b/libraries/src/test/resources/book.csv @@ -0,0 +1,3 @@ +author,title +Dan Simmons,Hyperion +Douglas Adams,The Hitchhiker's Guide to the Galaxy diff --git a/libraries/src/test/resources/employees.sql b/libraries/src/test/resources/employees.sql new file mode 100644 index 0000000000..c6109724cf --- /dev/null +++ b/libraries/src/test/resources/employees.sql @@ -0,0 +1,43 @@ +CREATE TABLE employee( + id int NOT NULL PRIMARY KEY auto_increment, + firstname varchar(255), + lastname varchar(255), + salary double, + hireddate date +); + +CREATE TABLE email( + id int NOT NULL PRIMARY KEY auto_increment, + employeeid int, + address varchar(255) +); + +CREATE TABLE employee_legacy( + id int NOT NULL PRIMARY KEY auto_increment, + first_name varchar(255), + last_name varchar(255), + salary double, + hired_date date +); + + +INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy')); +INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy')); +INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy')); +INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy')); +INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy')); + +INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy')); +INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy')); +INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy')); +INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy')); +INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy')); + +INSERT INTO email (employeeid,address) VALUES (1, 'john@baeldung.com'); +INSERT INTO email (employeeid,address) VALUES (1, 'john@gmail.com'); +INSERT INTO email (employeeid,address) VALUES (2, 'kevin@baeldung.com'); +INSERT INTO email (employeeid,address) VALUES (3, 'kim@baeldung.com'); +INSERT INTO email (employeeid,address) VALUES (3, 'kim@gmail.com'); +INSERT INTO email (employeeid,address) VALUES (3, 'kim@outlook.com'); +INSERT INTO email (employeeid,address) VALUES (4, 'stephen@baeldung.com'); +INSERT INTO email (employeeid,address) VALUES (5, 'christian@gmail.com'); diff --git a/libraries/src/test/resources/input.txt b/libraries/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/libraries/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/libraries/src/test/resources/output.txt b/libraries/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/libraries/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file diff --git a/liquibase/README.md b/liquibase/README.md new file mode 100644 index 0000000000..0e5bfcb8a6 --- /dev/null +++ b/liquibase/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Liquibase Rollback](http://www.baeldung.com/liquibase-rollback) diff --git a/log-mdc/README.md b/log-mdc/README.md index be0b2670c3..3841224824 100644 --- a/log-mdc/README.md +++ b/log-mdc/README.md @@ -2,6 +2,7 @@ - TBD - [Improved Java Logging with Mapped Diagnostic Context (MDC)](http://www.baeldung.com/mdc-in-log4j-2-logback) - [Java Logging with Nested Diagnostic Context (NDC)](http://www.baeldung.com/java-logging-ndc-log4j) +- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel) ### References diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java new file mode 100644 index 0000000000..a1454c16cc --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.logging.log4j2.tests; + +import java.util.Random; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.Test; + +public class LambdaExpressionsIntegrationTest { + + private static final Logger logger = LogManager.getRootLogger(); + + @Test + public void whenCheckLogMessage_thenOk() { + if (logger.isTraceEnabled()) { + logger.trace("Numer is {}", getRandomNumber()); + } + } + + @Test + public void whenUseLambdaExpression_thenOk() { + logger.trace("Number is {}", () -> getRandomNumber()); + logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber()); + } + + private int getRandomNumber() { + return (new Random()).nextInt(10); + } + + private String getName() { + return "John"; + } +} diff --git a/metrics/README.md b/metrics/README.md index c98024c479..09fe925604 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics) +- [Introduction to Netflix Servo](http://www.baeldung.com/netflix-servo) diff --git a/metrics/pom.xml b/metrics/pom.xml index 794c53b157..574c1ac132 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 @@ -15,7 +15,7 @@ 3.1.2 3.1.0 - 0.12.16 + 0.12.17 @@ -44,10 +44,24 @@ javax.servlet-api ${dep.ver.servlet} + com.netflix.servo servo-core ${netflix.servo.ver} + test + + + com.netflix.servo + servo-atlas + ${netflix.servo.ver} + test + + + com.fasterxml.jackson.dataformat + jackson-dataformat-smile + 2.8.9 + test diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java new file mode 100644 index 0000000000..134c3c91cf --- /dev/null +++ b/metrics/src/test/java/com/baeldung/metrics/servo/AtlasObserverLiveTest.java @@ -0,0 +1,92 @@ +package com.baeldung.metrics.servo; + +import com.netflix.servo.DefaultMonitorRegistry; +import com.netflix.servo.monitor.BasicCounter; +import com.netflix.servo.monitor.Counter; +import com.netflix.servo.monitor.MonitorConfig; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.MonitorRegistryMetricPoller; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; +import com.netflix.servo.publish.atlas.AtlasMetricObserver; +import com.netflix.servo.publish.atlas.BasicAtlasConfig; +import com.netflix.servo.tag.BasicTagList; +import org.apache.commons.lang.math.RandomUtils; +import org.apache.http.HttpEntity; +import org.apache.http.impl.client.HttpClients; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.apache.http.client.methods.RequestBuilder.get; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +public class AtlasObserverLiveTest { + + private final String atlasUri = "http://localhost:7101/api/v1"; + + @Before + public void prepareScheduler() { + System.setProperty("servo.pollers", "1000"); + System.setProperty("servo.atlas.batchSize", "1"); + System.setProperty("servo.atlas.uri", atlasUri + "/publish"); + AtlasMetricObserver observer = new AtlasMetricObserver(new BasicAtlasConfig(), BasicTagList.of("servo", "counter")); + + PollRunnable task = new PollRunnable(new MonitorRegistryMetricPoller(), new BasicMetricFilter(true), observer); + PollScheduler + .getInstance() + .start(); + PollScheduler + .getInstance() + .addPoller(task, 1, SECONDS); + } + + @After + public void stopScheduler() { + if (PollScheduler + .getInstance() + .isStarted()) { + PollScheduler + .getInstance() + .stop(); + } + } + + private String atlasValuesOfTag(String tagname) throws Exception { + HttpEntity entity = HttpClients + .createDefault() + .execute(get() + .setUri(atlasUri + "/tags/" + tagname) + .build()) + .getEntity(); + return new BufferedReader(new InputStreamReader(entity.getContent())).readLine(); + } + + @Test + public void givenAtlasAndCounter_whenRegister_thenPublishedToAtlas() throws Exception { + Counter counter = new BasicCounter(MonitorConfig + .builder("test") + .withTag("servo", "counter") + .build()); + DefaultMonitorRegistry + .getInstance() + .register(counter); + assertThat(atlasValuesOfTag("servo"), not(containsString("counter"))); + + for (int i = 0; i < 3; i++) { + counter.increment(RandomUtils.nextInt(10)); + SECONDS.sleep(1); + counter.increment(-1 * RandomUtils.nextInt(10)); + SECONDS.sleep(1); + } + + assertThat(atlasValuesOfTag("servo"), containsString("counter")); + } + +} diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java similarity index 95% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java index 3d6a73912f..2f908531f6 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricAnnotationManualTest.java @@ -22,10 +22,7 @@ import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -/** - * @author aiet - */ -public class MetricAnnotationTest extends MetricTestBase { +public class MetricAnnotationManualTest extends MetricTestBase { @Monitor(name = "integerCounter", type = DataSourceType.COUNTER, description = "Total number of update operations.") private final AtomicInteger updateCount = new AtomicInteger(0); diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java similarity index 86% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java index 14d3c2646f..3bb421b3ef 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricObserverManualTest.java @@ -13,14 +13,16 @@ import java.util.List; import static com.netflix.servo.annotations.DataSourceType.GAUGE; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricObserverTest extends MetricTestBase { +public class MetricObserverManualTest extends MetricTestBase { @Test public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java similarity index 74% rename from metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java rename to metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java index 4a9a77efde..318170fb1f 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricPollerManualTest.java @@ -1,20 +1,23 @@ package com.baeldung.metrics.servo; import com.netflix.servo.Metric; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.JvmMetricPoller; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.Test; import java.util.List; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; -/** - * @author aiet - */ -public class MetricPollerTest { +public class MetricPollerManualTest { @Test public void givenJvmPoller_whenMonitor_thenDataCollected() throws Exception { diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java index 86a9d201e8..42f3c72e97 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTestBase.java @@ -1,14 +1,16 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.publish.*; +import com.netflix.servo.publish.BasicMetricFilter; +import com.netflix.servo.publish.MemoryMetricObserver; +import com.netflix.servo.publish.MetricFilter; +import com.netflix.servo.publish.MonitorRegistryMetricPoller; +import com.netflix.servo.publish.PollRunnable; +import com.netflix.servo.publish.PollScheduler; import org.junit.After; import org.junit.Before; import static java.util.concurrent.TimeUnit.SECONDS; -/** - * @author aiet - */ abstract class MetricTestBase { MemoryMetricObserver observer; diff --git a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java index 68ba23244d..99009f8d84 100644 --- a/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/servo/MetricTypeTest.java @@ -1,6 +1,21 @@ package com.baeldung.metrics.servo; -import com.netflix.servo.monitor.*; +import com.netflix.servo.monitor.BasicCounter; +import com.netflix.servo.monitor.BasicGauge; +import com.netflix.servo.monitor.BasicInformational; +import com.netflix.servo.monitor.BasicTimer; +import com.netflix.servo.monitor.BucketConfig; +import com.netflix.servo.monitor.BucketTimer; +import com.netflix.servo.monitor.Counter; +import com.netflix.servo.monitor.Gauge; +import com.netflix.servo.monitor.MaxGauge; +import com.netflix.servo.monitor.Monitor; +import com.netflix.servo.monitor.MonitorConfig; +import com.netflix.servo.monitor.Monitors; +import com.netflix.servo.monitor.PeakRateCounter; +import com.netflix.servo.monitor.StatsTimer; +import com.netflix.servo.monitor.StepCounter; +import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.stats.StatsConfig; import org.junit.Ignore; import org.junit.Test; @@ -9,13 +24,12 @@ import java.util.Map; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toMap; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasEntry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -/** - * Unit test for simple App. - */ public class MetricTypeTest { @Test @@ -113,7 +127,7 @@ public class MetricTypeTest { BucketTimer timer = new BucketTimer(MonitorConfig .builder("test") .build(), new BucketConfig.Builder() - .withBuckets(new long[] { 2L, 5L }) + .withBuckets(new long[]{2L, 5L}) .withTimeUnit(SECONDS) .build(), SECONDS); timer.record(3); @@ -150,7 +164,7 @@ public class MetricTypeTest { .builder("test") .build(), new StatsConfig.Builder() .withComputeFrequencyMillis(2000) - .withPercentiles(new double[] { 99.0, 95.0, 90.0 }) + .withPercentiles(new double[]{99.0, 95.0, 90.0}) .withPublishMax(true) .withPublishMin(true) .withPublishCount(true) diff --git a/mockito/pom.xml b/mockito/pom.xml index c77d42f97d..19dd2f6468 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -41,7 +41,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 ${powermock.version} test @@ -65,7 +65,7 @@ 3.5 - 1.6.6 + 1.7.0 diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java index 771444f13d..9a3bc8875b 100644 --- a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java @@ -1,12 +1,12 @@ package com.baeldung.powermockito.introduction; -public class CollaboratorForPartialMocking { +class CollaboratorForPartialMocking { - public static String staticMethod() { + static String staticMethod() { return "Hello Baeldung!"; } - public final String finalMethod() { + final String finalMethod() { return "Hello Baeldung!"; } @@ -14,7 +14,7 @@ public class CollaboratorForPartialMocking { return "Hello Baeldung!"; } - public String privateMethodCaller() { + String privateMethodCaller() { return privateMethod() + " Welcome to the Java world."; } } \ No newline at end of file diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java index 8287454782..f748b6a6fc 100644 --- a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java @@ -1,8 +1,8 @@ package com.baeldung.powermockito.introduction; -public class CollaboratorWithFinalMethods { +class CollaboratorWithFinalMethods { - public final String helloMethod() { + final String helloMethod() { return "Hello World!"; } diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java index 2795ae97f1..1f416aefa7 100644 --- a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java @@ -1,16 +1,16 @@ package com.baeldung.powermockito.introduction; -public class CollaboratorWithStaticMethods { +class CollaboratorWithStaticMethods { - public static String firstMethod(String name) { + static String firstMethod(String name) { return "Hello " + name + " !"; } - public static String secondMethod() { + static String secondMethod() { return "Hello no one!"; } - public static String thirdMethod() { + static String thirdMethod() { return "Hello no one again!"; } } \ No newline at end of file diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java index 4e090e6652..5e083adbf5 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java @@ -17,7 +17,7 @@ public class MockitoAnnotationIntegrationTest { private List mockedList; @Spy - List spiedList = new ArrayList(); + private List spiedList = new ArrayList<>(); @Before public void init() { @@ -87,6 +87,7 @@ public class MockitoAnnotationIntegrationTest { } @Captor + private ArgumentCaptor argCaptor; @Test @@ -98,10 +99,10 @@ public class MockitoAnnotationIntegrationTest { } @Mock - Map wordMap; + private Map wordMap; @InjectMocks - MyDictionary dic = new MyDictionary(); + private MyDictionary dic = new MyDictionary(); @Test public void whenUseInjectMocksAnnotation_thenCorrect() { diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java index 6ec3b34db5..f846907fd7 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java @@ -24,7 +24,7 @@ public class MockitoMockIntegrationTest { } @Rule - public ExpectedException thrown = ExpectedException.none(); + private ExpectedException thrown = ExpectedException.none(); @Test public void whenUsingSimpleMock_thenCorrect() { diff --git a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java index a613b28f59..8a0ea92502 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java +++ b/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java @@ -3,19 +3,19 @@ package org.baeldung.mockito; import java.util.HashMap; import java.util.Map; -public class MyDictionary { +class MyDictionary { - Map wordMap; + private Map wordMap; - public MyDictionary() { - wordMap = new HashMap(); + MyDictionary() { + wordMap = new HashMap<>(); } public void add(final String word, final String meaning) { wordMap.put(word, meaning); } - public String getMeaning(final String word) { + String getMeaning(final String word) { return wordMap.get(word); } } diff --git a/mockito/src/test/java/org/baeldung/mockito/MyList.java b/mockito/src/test/java/org/baeldung/mockito/MyList.java index 548596e6b6..be69ef8a8a 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyList.java +++ b/mockito/src/test/java/org/baeldung/mockito/MyList.java @@ -2,7 +2,7 @@ package org.baeldung.mockito; import java.util.AbstractList; -public class MyList extends AbstractList { +class MyList extends AbstractList { @Override public String get(final int index) { diff --git a/mockito2/pom.xml b/mockito2/pom.xml index 523cfa816d..a7c4683c30 100644 --- a/mockito2/pom.xml +++ b/mockito2/pom.xml @@ -53,6 +53,6 @@ UTF-8 - 2.7.5 + 2.8.9 diff --git a/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml index 2ab35651f1..e350457f54 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/mocks/mock-comparisons/pom.xml @@ -13,7 +13,7 @@ mock-comparisons - 1.10.19 + 2.8.9 3.4 1.29 diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java index 18bc2ae189..9d47b2f5d4 100644 --- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java +++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java @@ -7,7 +7,13 @@ import org.baeldung.mocks.testCase.UserForm; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.mockito.*; +import org.mockito.ArgumentMatcher; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; public class LoginControllerIntegrationTest { @@ -41,50 +47,63 @@ public class LoginControllerIntegrationTest { public void assertTwoMethodsHaveBeenCalled() { UserForm userForm = new UserForm(); userForm.username = "foo"; - Mockito.when(loginService.login(userForm)).thenReturn(true); + Mockito.when(loginService.login(userForm)) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); - Mockito.verify(loginService).setCurrentUser("foo"); + Mockito.verify(loginService) + .login(userForm); + Mockito.verify(loginService) + .setCurrentUser("foo"); } @Test public void assertOnlyOneMethodHasBeenCalled() { UserForm userForm = new UserForm(); userForm.username = "foo"; - Mockito.when(loginService.login(userForm)).thenReturn(false); + Mockito.when(loginService.login(userForm)) + .thenReturn(false); String login = loginController.login(userForm); Assert.assertEquals("KO", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); Mockito.verifyNoMoreInteractions(loginService); } @Test public void mockExceptionThrowing() { UserForm userForm = new UserForm(); - Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class); + Mockito.when(loginService.login(userForm)) + .thenThrow(IllegalArgumentException.class); String login = loginController.login(userForm); Assert.assertEquals("ERROR", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); Mockito.verifyZeroInteractions(loginService); } @Test public void mockAnObjectToPassAround() { - UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock(); - Mockito.when(loginService.login(userForm)).thenReturn(true); + UserForm userForm = Mockito.when(Mockito.mock(UserForm.class) + .getUsername()) + .thenReturn("foo") + .getMock(); + Mockito.when(loginService.login(userForm)) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); - Mockito.verify(loginService).setCurrentUser("foo"); + Mockito.verify(loginService) + .login(userForm); + Mockito.verify(loginService) + .setCurrentUser("foo"); } @Test @@ -92,19 +111,22 @@ public class LoginControllerIntegrationTest { UserForm userForm = new UserForm(); userForm.username = "foo"; // default matcher - Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true); + Mockito.when(loginService.login(Mockito.any(UserForm.class))) + .thenReturn(true); String login = loginController.login(userForm); Assert.assertEquals("OK", login); - Mockito.verify(loginService).login(userForm); + Mockito.verify(loginService) + .login(userForm); // complex matcher - Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object argument) { - return argument instanceof String && ((String) argument).startsWith("foo"); - } - })); + Mockito.verify(loginService) + .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher() { + @Override + public boolean matches(String argument) { + return argument.startsWith("foo"); + } + })); } @Test @@ -114,12 +136,14 @@ public class LoginControllerIntegrationTest { UserForm userForm = new UserForm(); userForm.username = "foo"; // let service's login use implementation so let's mock DAO call - Mockito.when(loginDao.login(userForm)).thenReturn(1); + Mockito.when(loginDao.login(userForm)) + .thenReturn(1); String login = loginController.login(userForm); Assert.assertEquals("OK", login); // verify mocked call - Mockito.verify(spiedLoginService).setCurrentUser("foo"); + Mockito.verify(spiedLoginService) + .setCurrentUser("foo"); } } diff --git a/mockserver/pom.xml b/mockserver/pom.xml new file mode 100644 index 0000000000..8d3e97f129 --- /dev/null +++ b/mockserver/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.baeldung + mockserver + 1.0.0-SNAPSHOT + + 3.10.8 + 4.4.1 + + + + + org.mock-server + mockserver-netty + ${mock-sever-netty-version} + + + + org.mock-server + mockserver-client-java + ${mock-sever-netty-version} + + + + org.apache.httpcomponents + httpclient + ${apche-http-version} + + + org.apache.httpcomponents + httpcore + ${apche-http-version} + + + + + + + maven-surefire-plugin + 2.20 + + + **/**LiveTest.java + + + + + + + \ No newline at end of file diff --git a/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java new file mode 100644 index 0000000000..a74dca28da --- /dev/null +++ b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java @@ -0,0 +1,23 @@ +package com.baeldung.mock.server; + +import org.mockserver.mock.action.ExpectationCallback; +import org.mockserver.model.HttpRequest; +import org.mockserver.model.HttpResponse; + +import static org.mockserver.model.HttpResponse.notFoundResponse; +import static org.mockserver.model.HttpResponse.response; + + +public class ExpectationCallbackHandler implements ExpectationCallback { + + public HttpResponse handle(HttpRequest httpRequest) { + if (httpRequest.getPath().getValue().endsWith("/callback")) { + return httpResponse; + } else { + return notFoundResponse(); + } + } + + public static HttpResponse httpResponse = response() + .withStatusCode(200); +} diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java new file mode 100644 index 0000000000..e7b972f6a4 --- /dev/null +++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java @@ -0,0 +1,173 @@ +package com.baeldung.mock.server; + +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.*; +import org.mockserver.client.server.MockServerClient; +import org.mockserver.integration.ClientAndProxy; +import org.mockserver.integration.ClientAndServer; +import org.mockserver.model.Header; +import org.mockserver.model.HttpForward; +import org.mockserver.verify.VerificationTimes; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static junit.framework.Assert.assertEquals; +import static org.mockserver.integration.ClientAndProxy.startClientAndProxy; +import static org.mockserver.integration.ClientAndServer.startClientAndServer; +import static org.mockserver.matchers.Times.exactly; +import static org.mockserver.model.HttpClassCallback.callback; +import static org.mockserver.model.HttpForward.forward; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.response; +import static org.mockserver.model.StringBody.exact; + +public class MockServerLiveTest { + + private static ClientAndServer mockServer; + + @BeforeClass + public static void startServer() { + mockServer = startClientAndServer(1080); + } + + + @Test + public void whenPostRequestMockServer_thenServerReceived(){ + createExpectationForInvalidAuth(); + hitTheServerWithPostRequest(); + verifyPostRequest(); + } + + @Test + public void whenPostRequestForInvalidAuth_then401Received(){ + createExpectationForInvalidAuth(); + org.apache.http.HttpResponse response = hitTheServerWithPostRequest(); + assertEquals(401, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenGetRequest_ThenForward(){ + createExpectationForForward(); + hitTheServerWithGetRequest("index.html"); + verifyGetRequest(); + + } + + @Test + public void whenCallbackRequest_ThenCallbackMethodCalled(){ + createExpectationForCallBack(); + org.apache.http.HttpResponse response= hitTheServerWithGetRequest("/callback"); + assertEquals(200,response.getStatusLine().getStatusCode()); + } + + private void verifyPostRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("POST") + .withPath("/validate") + .withBody(exact("{username: 'foo', password: 'bar'}")), + VerificationTimes.exactly(1) + ); + } + private void verifyGetRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("GET") + .withPath("/index.html"), + VerificationTimes.exactly(1) + ); + } + + private org.apache.http.HttpResponse hitTheServerWithPostRequest() { + String url = "http://127.0.0.1:1080/validate"; + HttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(url); + post.setHeader("Content-type", "application/json"); + org.apache.http.HttpResponse response=null; + + try { + StringEntity stringEntity = new StringEntity("{username: 'foo', password: 'bar'}"); + post.getRequestLine(); + post.setEntity(stringEntity); + response=client.execute(post); + + } catch (Exception e) { + throw new RuntimeException(e); + } + return response; + } + + private org.apache.http.HttpResponse hitTheServerWithGetRequest(String page) { + String url = "http://127.0.0.1:1080/"+page; + HttpClient client = HttpClientBuilder.create().build(); + org.apache.http.HttpResponse response=null; + HttpGet get = new HttpGet(url); + try { + response=client.execute(get); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return response; + } + + private void createExpectationForInvalidAuth() { + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("POST") + .withPath("/validate") + .withHeader("\"Content-type\", \"application/json\"") + .withBody(exact("{username: 'foo', password: 'bar'}")), + exactly(1) + ) + .respond( + response() + .withStatusCode(401) + .withHeaders( + new Header("Content-Type", "application/json; charset=utf-8"), + new Header("Cache-Control", "public, max-age=86400") + ) + .withBody("{ message: 'incorrect username and password combination' }") + .withDelay(TimeUnit.SECONDS,1) + ); + } + + private void createExpectationForForward(){ + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("GET") + .withPath("/index.html"), + exactly(1) + ) + .forward( + forward() + .withHost("www.mock-server.com") + .withPort(80) + .withScheme(HttpForward.Scheme.HTTP) + ); + } + + private void createExpectationForCallBack(){ + mockServer + .when( + request() + .withPath("/callback") + ) + .callback( + callback() + .withCallbackClass("com.baeldung.mock.server.ExpectationCallbackHandler") + ); + } + + @AfterClass + public static void stopServer() { + mockServer.stop(); + } +} diff --git a/noexception/README.md b/noexception/README.md new file mode 100644 index 0000000000..d840191369 --- /dev/null +++ b/noexception/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) diff --git a/jooq/pom.xml b/noexception/pom.xml similarity index 57% rename from jooq/pom.xml rename to noexception/pom.xml index 667640d085..64c0591fda 100644 --- a/jooq/pom.xml +++ b/noexception/pom.xml @@ -1,25 +1,23 @@ - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - jooq + com.baeldung + noexception + 1.0 + noexception + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - org.jooq - jool - ${jool.version} + com.machinezoo.noexception + noexception + 1.1.0 - - - 0.9.12 - - - \ No newline at end of file + diff --git a/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java new file mode 100644 index 0000000000..59e13efaa0 --- /dev/null +++ b/noexception/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.ExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CustomExceptionHandler extends ExceptionHandler { + + private Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class); + + @Override + public boolean handle(Throwable throwable) { + + if (throwable.getClass() + .isAssignableFrom(RuntimeException.class) + || throwable.getClass() + .isAssignableFrom(Error.class)) { + return false; + } else { + logger.error("Caught Exception ", throwable); + return true; + } + } +} diff --git a/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java new file mode 100644 index 0000000000..690ea43520 --- /dev/null +++ b/noexception/src/test/java/com/baeldung/noexception/NoExceptionUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.noexception; + +import com.machinezoo.noexception.Exceptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoExceptionUnitTest { + + private static Logger logger = LoggerFactory.getLogger(NoExceptionUnitTest.class); + + @Test + public void whenStdExceptionHandling_thenCatchAndLog() { + try { + System.out.println("Result is " + Integer.parseInt("foobar")); + } catch (Throwable exception) { + logger.error("Caught exception:", exception); + } + } + + @Test + public void whenDefaultNoException_thenCatchAndLog() { + + Exceptions.log().run(() -> System.out.println("Result is " + Integer.parseInt("foobar"))); + } + + @Test + public void givenLogger_whenDefaultNoException_thenCatchAndLogWithClassName() { + System.out.println("Result is " + Exceptions.log(logger).get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenLoggerAndMessage_whenDefaultNoException_thenCatchAndLogWithClassNameAndMessage() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test + public void givenDefaultValue_whenDefaultNoException_thenCatchAndLogPrintDefault() { + System.out.println("Result is " + Exceptions.log(logger, "Something went wrong:").get(() -> +Integer.parseInt("foobar")).orElse(-1)); + } + + @Test(expected = Error.class) + public void givenCustomHandler_whenError_thenRethrowError() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwError()); + } + + @Test + public void givenCustomHandler_whenException_thenCatchAndLog() { + CustomExceptionHandler customExceptionHandler = new CustomExceptionHandler(); + customExceptionHandler.run(() -> throwException()); + } + + private static void throwError() { + throw new Error("This is very bad."); + } + + private static void throwException() { + String testString = "foo"; + testString.charAt(5); + } + +} diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 550409b643..5b7eb48a86 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -22,7 +22,6 @@ org.slf4j slf4j-api ${slf4j.version} - provided diff --git a/pom.xml b/pom.xml index 818d131359..da38d65df3 100644 --- a/pom.xml +++ b/pom.xml @@ -12,10 +12,13 @@ UTF-8 refs/heads/master + true + false + false 4.12 1.3 - 1.10.19 + 2.8.9 1.7.21 1.1.7 @@ -35,10 +38,12 @@ apache-thrift autovalue axon + bootique cdi core-java + core-java-concurrency couchbase-sdk deltaspike @@ -57,6 +62,7 @@ guava guava18 guava19 + guava21 guice disruptor @@ -76,10 +82,9 @@ javax-servlets javaxval jaxb - + jee7 jjwt - jooq jpa-storedprocedure jsf json-path @@ -89,6 +94,7 @@ jws libraries + libraries-data log-mdc log4j log4j2 @@ -101,6 +107,7 @@ mockito2 mocks mustache + noexception orika @@ -123,6 +130,7 @@ spark-java spring-5-mvc + spring-activiti spring-akka spring-amqp spring-all @@ -168,6 +176,7 @@ spring-mvc-webflow spring-mvc-xml spring-mvc-simple + spring-mvc-kotlin spring-security-openid spring-protobuf spring-quartz @@ -208,6 +217,7 @@ spring-zuul spring-reactor spring-vertx + testing testng @@ -228,6 +238,8 @@ drools liquibase spring-boot-property-exp + mockserver + undertow @@ -324,11 +336,11 @@ - + 3.4 + diff --git a/ratpack/README.md b/ratpack/README.md index 91c8e025f0..8215f74148 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -2,3 +2,4 @@ - [Introduction to Ratpack](http://www.baeldung.com/ratpack) - [Ratpack Google Guice Integration](http://www.baeldung.com/ratpack-google-guice) +- [Ratpack Integration with Spring Boot](http://www.baeldung.com/ratpack-spring-boot) diff --git a/ratpack/pom.xml b/ratpack/pom.xml index 8681f5fc10..3f953b3ed0 100644 --- a/ratpack/pom.xml +++ b/ratpack/pom.xml @@ -1,55 +1,86 @@ - 4.0.0 - com.baeldung - ratpack - jar - 1.0-SNAPSHOT - ratpack - http://maven.apache.org + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + ratpack + jar + 1.0-SNAPSHOT + ratpack + http://maven.apache.org - - UTF-8 - 1.8 - 1.8 - + + UTF-8 + 1.8 + 1.8 + 1.4.6 + com.baeldung parent-modules 1.0.0-SNAPSHOT - - - - - io.ratpack - ratpack-core - 1.4.5 - - - io.ratpack - ratpack-hikari - 1.4.5 - - - io.ratpack - ratpack-test - 1.4.5 - - - com.h2database - h2 - 1.4.193 - - + - - ${project.artifactId} - - - src/main/resources - - - + + + + io.ratpack + ratpack-spring-boot-starter + ${ratpack.version} + pom + + + + io.ratpack + ratpack-core + ${ratpack.version} + + + io.ratpack + ratpack-hikari + ${ratpack.version} + + + io.ratpack + ratpack-hystrix + ${ratpack.version} + + + io.ratpack + ratpack-rx + ${ratpack.version} + + + io.ratpack + ratpack-test + ${ratpack.version} + test + + + com.h2database + h2 + 1.4.193 + + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + org.apache.httpcomponents + httpcore + 4.4.6 + + + + + ${project.artifactId} + + + src/main/resources + + + diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java new file mode 100644 index 0000000000..a1a19150c3 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixAsyncHttpCommand.java @@ -0,0 +1,54 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixAsyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixAsyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-async")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(new HttpGet(uri)) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's async fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java new file mode 100644 index 0000000000..f9f85c705b --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixReactiveHttpCommand.java @@ -0,0 +1,44 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixObservableCommand; +import ratpack.http.client.HttpClient; +import ratpack.rx.RxRatpack; +import rx.Observable; + +import java.net.URI; + +/** + * @author aiet + */ +public class HystrixReactiveHttpCommand extends HystrixObservableCommand { + + private HttpClient httpClient; + private URI uri; + + HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + this.httpClient = httpClient; + this.uri = uri; + } + + @Override + protected Observable construct() { + return RxRatpack.observe(httpClient + .get(uri, requestSpec -> requestSpec.headers(mutableHeaders -> mutableHeaders.add("User-Agent", "Baeldung HttpClient"))) + .map(receivedResponse -> receivedResponse + .getBody() + .getText())); + } + + @Override + protected Observable resumeWithFallback() { + return Observable.just("eugenp's reactive fallback profile"); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java new file mode 100644 index 0000000000..7c848331ca --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/HystrixSyncHttpCommand.java @@ -0,0 +1,55 @@ +package com.baeldung.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandProperties; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; + +import java.net.URI; +import java.util.Collections; + +/** + * @author aiet + */ +public class HystrixSyncHttpCommand extends HystrixCommand { + + private URI uri; + private RequestConfig requestConfig; + + HystrixSyncHttpCommand(URI uri, int timeoutMillis) { + super(Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync")) + .andCommandPropertiesDefaults(HystrixCommandProperties + .Setter() + .withExecutionTimeoutInMilliseconds(timeoutMillis))); + requestConfig = RequestConfig + .custom() + .setSocketTimeout(timeoutMillis) + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(timeoutMillis) + .build(); + this.uri = uri; + } + + @Override + protected String run() throws Exception { + HttpGet request = new HttpGet(uri); + return EntityUtils.toString(HttpClientBuilder + .create() + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient"))) + .build() + .execute(request) + .getEntity()); + } + + @Override + protected String getFallback() { + return "eugenp's sync fallback profile"; + } + +} diff --git a/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java new file mode 100644 index 0000000000..1e4724bd96 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/hystrix/RatpackHystrixApp.java @@ -0,0 +1,30 @@ +package com.baeldung.hystrix; + +import ratpack.guice.Guice; +import ratpack.http.client.HttpClient; +import ratpack.hystrix.HystrixMetricsEventStreamHandler; +import ratpack.hystrix.HystrixModule; +import ratpack.server.RatpackServer; + +import java.net.URI; + +public class RatpackHystrixApp { + + public static void main(String[] args) throws Exception { + final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout")); + final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp"); + + RatpackServer.start(server -> server + .registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse()))) + .handlers(chain -> chain + .get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout) + .toObservable() + .subscribe(ctx::render)) + .get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout) + .queue() + .get())) + .get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute())) + .get("hystrix", new HystrixMetricsEventStreamHandler()))); + + } +} diff --git a/ratpack/src/main/java/com/baeldung/spring/ArticleList.java b/ratpack/src/main/java/com/baeldung/spring/ArticleList.java new file mode 100644 index 0000000000..b4d50bb3d3 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/spring/ArticleList.java @@ -0,0 +1,11 @@ +package com.baeldung.spring; + +import java.util.List; + +/** + * @author aiet + */ +public interface ArticleList { + + List articles(); +} diff --git a/ratpack/src/main/java/com/baeldung/spring/Config.java b/ratpack/src/main/java/com/baeldung/spring/Config.java new file mode 100644 index 0000000000..ec0d1787e6 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/spring/Config.java @@ -0,0 +1,24 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Arrays; + +/** + * @author aiet + */ +@Configuration +public class Config { + + @Bean + public Content content() { + return () -> "hello baeldung!"; + } + + @Bean + public ArticleList articles() { + return () -> Arrays.asList("Introduction to Ratpack", "Ratpack Google Guice Integration", "Ratpack Spring Boot Integration"); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/spring/Content.java b/ratpack/src/main/java/com/baeldung/spring/Content.java new file mode 100644 index 0000000000..4d01c70cb9 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/spring/Content.java @@ -0,0 +1,10 @@ +package com.baeldung.spring; + +/** + * @author aiet + */ +public interface Content { + + String body(); + +} diff --git a/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java b/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java new file mode 100644 index 0000000000..7f3483d676 --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/spring/EmbedRatpackApp.java @@ -0,0 +1,46 @@ +package com.baeldung.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import ratpack.func.Action; +import ratpack.handling.Chain; +import ratpack.server.ServerConfig; +import ratpack.spring.config.EnableRatpack; + +/** + * @author aiet + */ +@SpringBootApplication +@EnableRatpack +public class EmbedRatpackApp { + + @Autowired private Content content; + @Autowired private ArticleList list; + + @Bean + public Action hello() { + return chain -> chain.get("hello", ctx -> ctx.render(content.body())); + } + + @Bean + public Action list() { + return chain -> chain.get("list", ctx -> ctx.render(list + .articles() + .toString())); + } + + @Bean + public ServerConfig ratpackServerConfig() { + return ServerConfig + .builder() + .findBaseDir("public") + .build(); + } + + public static void main(String[] args) { + SpringApplication.run(EmbedRatpackApp.class, args); + } + +} diff --git a/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java b/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java new file mode 100644 index 0000000000..05ff00cbbd --- /dev/null +++ b/ratpack/src/main/java/com/baeldung/spring/EmbedSpringBootApp.java @@ -0,0 +1,19 @@ +package com.baeldung.spring; + +import ratpack.server.RatpackServer; + +import static ratpack.spring.Spring.spring; + +public class EmbedSpringBootApp { + + public static void main(String[] args) throws Exception { + RatpackServer.start(server -> server + .registry(spring(Config.class)) + .handlers(chain -> chain.get(ctx -> ctx.render(ctx + .get(Content.class) + .body())))); + } + +} + + diff --git a/ratpack/src/main/resources/public/index.html b/ratpack/src/main/resources/public/index.html new file mode 100644 index 0000000000..d6573bfb7f --- /dev/null +++ b/ratpack/src/main/resources/public/index.html @@ -0,0 +1,10 @@ + + + + + Special Static Resource + + +This page is static. + + \ No newline at end of file diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java new file mode 100644 index 0000000000..25287a5cbd --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppFallbackLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppFallbackLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "10"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("reactive fallback profile")); + } + + @Test + public void whenFetchAsync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("async fallback profile")); + } + + @Test + public void whenFetchSync_thenGotFallbackProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("sync fallback profile")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} diff --git a/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java new file mode 100644 index 0000000000..843ef68e13 --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/hystrix/RatpackHystrixAppLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.hystrix; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class RatpackHystrixAppLiveTest { + + static MainClassApplicationUnderTest appUnderTest; + + @BeforeClass + public static void setup() { + System.setProperty("ratpack.hystrix.timeout", "5000"); + appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class); + } + + @Test + public void whenFetchReactive_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("rx"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchAsync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("async"), containsString("www.baeldung.com")); + } + + @Test + public void whenFetchSync_thenGotEugenProfile() { + assertThat(appUnderTest + .getHttpClient() + .getText("sync"), containsString("www.baeldung.com")); + } + + @AfterClass + public static void clean() { + appUnderTest.close(); + } + +} diff --git a/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java b/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java new file mode 100644 index 0000000000..802fe75d5c --- /dev/null +++ b/ratpack/src/test/java/com/baeldung/spring/EmbedRatpackAppIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.spring; + +import org.junit.Test; +import ratpack.test.MainClassApplicationUnderTest; + +import java.io.IOException; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +/** + * @author aiet + */ +public class EmbedRatpackAppIntegrationTest { + + MainClassApplicationUnderTest appUnderTest = new MainClassApplicationUnderTest(EmbedRatpackApp.class); + + @Test + public void whenSayHello_thenGotWelcomeMessage() { + assertEquals("hello baeldung!", appUnderTest + .getHttpClient() + .getText("/hello")); + } + + @Test + public void whenRequestList_thenGotArticles() throws IOException { + assertEquals(3, appUnderTest + .getHttpClient() + .getText("/list") + .split(",").length); + } + + @Test + public void whenRequestStaticResource_thenGotStaticContent() { + assertThat(appUnderTest + .getHttpClient() + .getText("/"), containsString("page is static")); + } + +} diff --git a/rule-engines/easy-rules/pom.xml b/rule-engines/easy-rules/pom.xml new file mode 100644 index 0000000000..78edc09d1a --- /dev/null +++ b/rule-engines/easy-rules/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.easyrules + easy-rules + 1.0 + + easy-rules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.jeasy + easy-rules-core + 3.0.0 + + + \ No newline at end of file diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java new file mode 100644 index 0000000000..5448eabf2a --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/HelloWorldRule.java @@ -0,0 +1,20 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.annotation.Action; +import org.jeasy.rules.annotation.Condition; +import org.jeasy.rules.annotation.Rule; + +@Rule(name = "Hello World rule", description = "Always say hello world") +public class HelloWorldRule { + + @Condition + public boolean when() { + return true; + } + + @Action + public void then() throws Exception { + System.out.println("hello world"); + } + +} diff --git a/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java new file mode 100644 index 0000000000..427e3eace0 --- /dev/null +++ b/rule-engines/easy-rules/src/main/java/com/baeldung/easyrules/Launcher.java @@ -0,0 +1,21 @@ +package com.baeldung.easyrules; + +import org.jeasy.rules.api.Facts; +import org.jeasy.rules.api.Rules; +import org.jeasy.rules.api.RulesEngine; +import org.jeasy.rules.core.DefaultRulesEngine; + +public class Launcher { + public static void main(String... args) { + // create facts + Facts facts = new Facts(); + + // create rules + Rules rules = new Rules(); + rules.register(new HelloWorldRule()); + + // create a rules engine and fire rules on known facts + RulesEngine rulesEngine = new DefaultRulesEngine(); + rulesEngine.fire(rules, facts); + } +} diff --git a/rule-engines/openl-tablets/pom.xml b/rule-engines/openl-tablets/pom.xml new file mode 100644 index 0000000000..e983d4e566 --- /dev/null +++ b/rule-engines/openl-tablets/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung.openltablets + openl-tablets + 1.0 + + openl-tablets + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.openl + org.openl.core + 5.19.4 + + + org.openl.rules + org.openl.rules + 5.19.4 + + + \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java new file mode 100644 index 0000000000..f9f5f4bd5f --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Case.java @@ -0,0 +1,23 @@ +package com.baeldung.openltablets.model; + +public class Case { + + private User user; + private int hourOfDay; + + public User getUser() { + return user; + } + + public void setUser(final User user) { + this.user = user; + } + + public int getHourOfDay() { + return hourOfDay; + } + + public void setHourOfDay(final int hourOfDay) { + this.hourOfDay = hourOfDay; + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java new file mode 100644 index 0000000000..5dc7bcd117 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/Greeting.java @@ -0,0 +1,20 @@ +package com.baeldung.openltablets.model; + +public enum Greeting { + + GOOD_MORNING("Good Morning"), + GOOD_AFTERNOON("Good Afternoon"), + GOOD_EVENING("Good Evening"), + GOOD_NIGHT("Good Night"); + + private final String literal; + + private Greeting(final String literal) { + this.literal = literal; + } + + public String getLiteral() { + return literal; + } + +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java new file mode 100644 index 0000000000..8e45487497 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/model/User.java @@ -0,0 +1,14 @@ +package com.baeldung.openltablets.model; + +public class User { + + private String name; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java new file mode 100644 index 0000000000..857a6433ef --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/IRule.java @@ -0,0 +1,7 @@ +package com.baeldung.openltablets.rules; + +import com.baeldung.openltablets.model.Case; + +public interface IRule { + void helloUser(final Case aCase, final Response response); +} \ No newline at end of file diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java new file mode 100644 index 0000000000..34f5c48ed1 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.openltablets.rules; + + +import java.time.LocalDateTime; + +import org.openl.rules.runtime.RulesEngineFactory; +import org.openl.runtime.EngineFactory; + +import com.baeldung.openltablets.model.Case; +import com.baeldung.openltablets.model.User; + +public class Main { + private IRule instance; + + public static void main(String[] args) { + Main rules = new Main(); + User user = new User(); + user.setName("Donald Duck"); + Case aCase = new Case(); + aCase.setUser(user); + aCase.setHourOfDay(23); + rules.process(aCase); + } + + public void process(Case aCase) { + final EngineFactory engineFactory = new RulesEngineFactory(getClass().getClassLoader() + .getResource("openltablets/HelloUser.xls"), IRule.class); + instance = engineFactory.newEngineInstance(); + instance.helloUser(aCase, new Response()); + } +} diff --git a/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java new file mode 100644 index 0000000000..27fa634866 --- /dev/null +++ b/rule-engines/openl-tablets/src/main/java/com/baeldung/openltablets/rules/Response.java @@ -0,0 +1,24 @@ +package com.baeldung.openltablets.rules; + +import java.util.HashMap; +import java.util.Map; + +public class Response { + private String result; + private Map map = new HashMap<>(); + + public Response() { } + + public String getResult() { + return result; + } + + public void setResult(final String s) { + result = s; + } + + public Map getMap() { + return map; + } + +} diff --git a/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls b/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls new file mode 100644 index 0000000000..1e85d0ce2d Binary files /dev/null and b/rule-engines/openl-tablets/src/main/resources/openltablets/HelloUser.xls differ diff --git a/rule-engines/rulebook/pom.xml b/rule-engines/rulebook/pom.xml new file mode 100644 index 0000000000..711bee8c91 --- /dev/null +++ b/rule-engines/rulebook/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.baeldung.rulebook + rulebook + 1.0 + + rulebook + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.deliveredtechnologies + rulebook-core + 0.6.2 + + + \ No newline at end of file diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java new file mode 100644 index 0000000000..c09772a3c6 --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/HelloWorldRule.java @@ -0,0 +1,17 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder; +import com.deliveredtechnologies.rulebook.model.RuleBook; + +public class HelloWorldRule { + public RuleBook defineHelloWorldRules() { + + return RuleBookBuilder.create() + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.print("Hello "))) + .addRule(rule -> rule.withNoSpecifiedFactType() + .then(f -> System.out.println("World"))) + .build(); + + } +} diff --git a/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java new file mode 100644 index 0000000000..57965457ec --- /dev/null +++ b/rule-engines/rulebook/src/main/java/com/baeldung/rulebook/Launcher.java @@ -0,0 +1,12 @@ +package com.baeldung.rulebook; + +import com.deliveredtechnologies.rulebook.FactMap; + +public class Launcher { + + public static void main(String[] args) { + HelloWorldRule ruleBook = new HelloWorldRule(); + ruleBook.defineHelloWorldRules() + .run(new FactMap<>()); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java new file mode 100644 index 0000000000..f6cf9fba68 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java @@ -0,0 +1,43 @@ +package com.baelding.rxjava.operator; + +import rx.Observable.Operator; +import rx.Subscriber; + +public class ToCleanString implements Operator { + + public static ToCleanString toCleanString() { + return new ToCleanString(); + } + + private ToCleanString() { + super(); + } + + @Override + public Subscriber call(final Subscriber subscriber) { + return new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String item) { + if (!subscriber.isUnsubscribed()) { + final String result = item.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + } + +} \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java new file mode 100644 index 0000000000..006d59de36 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java @@ -0,0 +1,20 @@ +package com.baelding.rxjava.operator; + +import rx.Observable; +import rx.Observable.Transformer; + +public class ToLength implements Transformer { + + public static ToLength toLength() { + return new ToLength(); + } + + private ToLength() { + super(); + } + + @Override + public Observable call(Observable source) { + return source.map(String::length); + } +} \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java index 040936a67a..458091fd1c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java @@ -34,7 +34,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); source.observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -50,7 +50,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -67,7 +67,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -84,7 +84,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.sample(100, TimeUnit.MILLISECONDS) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java new file mode 100644 index 0000000000..a49103196c --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.rxjava; + +import static com.baelding.rxjava.operator.ToCleanString.toCleanString; +import static com.baelding.rxjava.operator.ToLength.toLength; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import rx.Observable; +import rx.Observable.Operator; +import rx.Observable.Transformer; +import rx.Subscriber; + +import com.baelding.rxjava.operator.ToCleanString; +import com.baelding.rxjava.operator.ToLength; + +public class RxJavaCustomOperatorUnitTest { + + @Test + public void whenUseCleanStringOperator_thenSuccess() { + final List list = Arrays.asList("john_1", "tom-3"); + final List results = new ArrayList<>(); + + final Observable observable = Observable.from(list) + .lift(toCleanString()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("john1", "tom3")); + } + + @Test + public void whenUseToLengthOperator_thenSuccess() { + final List list = Arrays.asList("john", "tom"); + final List results = new ArrayList<>(); + + final Observable observable = Observable.from(list) + .compose(toLength()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(4, 3)); + } + + @Test + public void whenUseFunctionOperator_thenSuccess() { + final Operator cleanStringFn = subscriber -> new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String str) { + if (!subscriber.isUnsubscribed()) { + final String result = str.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + + final List results = new ArrayList<>(); + Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge")) + .lift(cleanStringFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("apple", "orange")); + } + + @Test + public void whenUseFunctionTransformer_thenSuccess() { + final Transformer toLengthFn = source -> source.map(String::length); + + final List results = new ArrayList<>(); + Observable.from(Arrays.asList("apple", "orange")) + .compose(toLengthFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(5, 6)); + } +} diff --git a/selenium-junit-testng/README.md b/selenium-junit-testng/README.md index cc1b728287..29393b956b 100644 --- a/selenium-junit-testng/README.md +++ b/selenium-junit-testng/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) - [Testing a Site with Selenium / Webdriver](http://www.baeldung.com) +- [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md new file mode 100644 index 0000000000..c031a9d10e --- /dev/null +++ b/spring-5-mvc/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) diff --git a/spring-5/README.md b/spring-5/README.md index 510ee45f03..4ce0fd4c79 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -7,4 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) - [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring MVC URL Matching Improvements](http://www.baeldung.com/spring-mvc-url-matching) +- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) +- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) diff --git a/spring-5/src/main/java/com/baeldung/functional/MyService.java b/spring-5/src/main/java/com/baeldung/functional/MyService.java new file mode 100644 index 0000000000..d85a860f06 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/functional/MyService.java @@ -0,0 +1,13 @@ +package com.baeldung.functional; + +import java.util.Random; + +import org.springframework.stereotype.Component; + +public class MyService { + + public int getRandomNumber(){ + return (new Random().nextInt(10)); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationTest.java new file mode 100644 index 0000000000..0b1542dbbc --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.functional; + +import static 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 org.springframework.web.context.support.GenericWebApplicationContext; + +import com.baeldung.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class BeanRegistrationTest { + + @Autowired + private GenericWebApplicationContext context; + + @Test + public void whenRegisterBean_thenOk() { + context.registerBean(MyService.class, () -> new MyService()); + MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); + assertTrue(myService.getRandomNumber() < 10); + } + + @Test + public void whenRegisterBeanWithName_thenOk() { + context.registerBean("mySecondService", MyService.class, () -> new MyService()); + MyService mySecondService = (MyService) context.getBean("mySecondService"); + assertTrue(mySecondService.getRandomNumber() < 10); + } + + @Test + public void whenRegisterBeanWithCallback_thenOk() { + context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false)); + MyService myCallbackService = (MyService) context.getBean("myCallbackService"); + assertTrue(myCallbackService.getRandomNumber() < 10); + } + +} diff --git a/spring-activiti/README.md b/spring-activiti/README.md new file mode 100644 index 0000000000..fc6eea7f87 --- /dev/null +++ b/spring-activiti/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml new file mode 100644 index 0000000000..c5289b20a6 --- /dev/null +++ b/spring-activiti/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + com.example + spring-activiti + 0.0.1-SNAPSHOT + jar + + spring-activiti + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.activiti + activiti-spring-boot-starter-basic + 6.0.0 + + + 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 + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + + + diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java new file mode 100644 index 0000000000..96b551c03c --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -0,0 +1,52 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.task.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class ActivitiController { + private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class); + + @Autowired + private RuntimeService runtimeService; + + @Autowired + private TaskService taskService; + + @GetMapping("/start-process") + public String startProcess() { + runtimeService.startProcessInstanceByKey("my-process"); + return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() + .count(); + } + + @GetMapping("/get-tasks/{processInstanceId}") + public List getTasks(@PathVariable String processInstanceId) { + List usertasks = taskService.createTaskQuery() + .processInstanceId(processInstanceId) + .list(); + + return usertasks.stream() + .map(task -> new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId())) + .collect(Collectors.toList()); + } + + @GetMapping("/complete-task-A/{processInstanceId}") + public void completeTaskA(@PathVariable String processInstanceId) { + Task task = taskService.createTaskQuery() + .processInstanceId(processInstanceId) + .singleResult(); + taskService.complete(task.getId()); + logger.info("Task completed"); + } +} diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java new file mode 100644 index 0000000000..2cfacdcf0d --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java @@ -0,0 +1,11 @@ +package com.example.activitiwithspring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ActivitiWithSpringApplication { + public static void main(String[] args) { + SpringApplication.run(ActivitiWithSpringApplication.class, args); + } +} diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/TaskRepresentation.java b/spring-activiti/src/main/java/com/example/activitiwithspring/TaskRepresentation.java new file mode 100644 index 0000000000..bb1412b057 --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/TaskRepresentation.java @@ -0,0 +1,43 @@ +package com.example.activitiwithspring; + +class TaskRepresentation { + + private String id; + private String name; + private String processInstanceId; + + public TaskRepresentation() { + super(); + } + + public TaskRepresentation(String id, String name, String processInstanceId) { + this.id = id; + this.name = name; + this.processInstanceId = processInstanceId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + +} diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java new file mode 100644 index 0000000000..c11b48f37a --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java @@ -0,0 +1,12 @@ +package com.example.activitiwithspring.servicetasks; + +import org.activiti.engine.delegate.DelegateExecution; +import org.activiti.engine.delegate.JavaDelegate; + +public class SendEmailServiceTask implements JavaDelegate { + + public void execute(DelegateExecution execution) { + //logic to sent email confirmation + } + +} diff --git a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml new file mode 100644 index 0000000000..6f151af458 --- /dev/null +++ b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java new file mode 100644 index 0000000000..65fd33bfc6 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -0,0 +1,117 @@ +package com.example.activitiwithspring; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.runtime.ProcessInstance; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@SpringBootTest +public class ActivitiControllerIntegrationTest { + private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerIntegrationTest.class); + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext wac; + + @Autowired + RuntimeService runtimeService; + + @Before + public void setUp() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); + + for (ProcessInstance instance : runtimeService.createProcessInstanceQuery() + .list()) { + runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes"); + } + } + + @Test + public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception { + + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) + .andReturn() + .getResponse() + .getContentAsString(); + assertEquals("Process started. Number of currently running process instances = 1", responseBody); + + responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) + .andReturn() + .getResponse() + .getContentAsString(); + assertEquals("Process started. Number of currently running process instances = 2", responseBody); + + responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) + .andReturn() + .getResponse() + .getContentAsString(); + assertEquals("Process started. Number of currently running process instances = 3", responseBody); + } + + @Test + public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) + .andReturn() + .getResponse(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery() + .orderByProcessInstanceId() + .desc() + .list() + .get(0); + + logger.info("process instance = " + pi.getId()); + String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId())) + .andReturn() + .getResponse() + .getContentAsString(); + + ObjectMapper mapper = new ObjectMapper(); + List tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class)); + assertEquals(1, tasks.size()); + assertEquals("A", tasks.get(0).getName()); + + } + + @Test + public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) + .andReturn() + .getResponse(); + ProcessInstance pi = runtimeService.createProcessInstanceQuery() + .orderByProcessInstanceId() + .desc() + .list() + .get(0); + + logger.info("process instance = " + pi.getId()); + this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) + .andReturn() + .getResponse() + .getContentAsString(); + + List list = runtimeService.createProcessInstanceQuery().list(); + assertEquals(0, list.size()); + } +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java new file mode 100644 index 0000000000..7460c302d8 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.example.activitiwithspring; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ActivitiWithSpringApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java new file mode 100644 index 0000000000..00afd14590 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationIntegrationTest.java @@ -0,0 +1,65 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngineConfiguration; +import org.activiti.engine.ProcessEngines; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class ProcessEngineCreationIntegrationTest { + + @Test + public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenXMLConfig_whenCreateDefaultConfiguration_thenGotProcessEngine() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault(); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentNameXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("my.activiti.cfg.xml"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java new file mode 100644 index 0000000000..9c35ea413b --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionIntegrationTest.java @@ -0,0 +1,98 @@ +package com.example.activitiwithspring; + + +import org.activiti.engine.ActivitiException; +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngines; +import org.activiti.engine.RepositoryService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ProcessExecutionIntegrationTest { + + @Test + public void givenBPMN_whenDeployProcess_thenDeployed() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + Long count = repositoryService.createProcessDefinitionQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + Long count = runtimeService.createProcessInstanceQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + TaskService taskService = processEngine.getTaskService(); + List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); + + Task task = tasks.get(0); + + Map taskVariables = new HashMap(); + taskVariables.put("vacationApproved", "false"); + taskVariables.put("comments", "We have a tight deadline!"); + taskService.complete(task.getId(), taskVariables); + + Task currentTask = taskService.createTaskQuery().taskName("Modify vacation request").singleResult(); + assertNotNull(currentTask); + } + + @Test(expected = ActivitiException.class) + public void givenProcessDefinition_whenSuspend_thenNoProcessInstanceCreated() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + repositoryService.suspendProcessDefinitionByKey("vacationRequest"); + runtimeService.startProcessInstanceByKey("vacationRequest"); + } +} diff --git a/spring-activiti/src/test/resources/activiti.cfg.xml b/spring-activiti/src/test/resources/activiti.cfg.xml new file mode 100644 index 0000000000..1ee117d936 --- /dev/null +++ b/spring-activiti/src/test/resources/activiti.cfg.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/my.activiti.cfg.xml b/spring-activiti/src/test/resources/my.activiti.cfg.xml new file mode 100644 index 0000000000..07e4206dad --- /dev/null +++ b/spring-activiti/src/test/resources/my.activiti.cfg.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml new file mode 100644 index 0000000000..354c633385 --- /dev/null +++ b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + ${employeeName} would like to take ${numberOfDays} day(s) of vacation (Motivation: ${reason}). + + + + + + + + + + management + + + + + + + + + + Your manager has disapproved your vacation request for ${numberOfDays} days. + Reason: ${comments} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/batch/App.java index 2ce4dae6e6..cea4e8d486 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java similarity index 85% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java index 9973005c7c..7b19935cc8 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java @@ -1,11 +1,8 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; -import java.net.MalformedURLException; -import java.text.ParseException; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.CustomItemProcessor; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.CustomItemProcessor; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; @@ -26,6 +23,9 @@ import org.springframework.core.io.Resource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import java.net.MalformedURLException; +import java.text.ParseException; + public class SpringBatchConfig { @Autowired private JobBuilderFactory jobs; @@ -43,7 +43,7 @@ public class SpringBatchConfig { public ItemReader itemReader() throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputCsv); DefaultLineMapper lineMapper = new DefaultLineMapper(); @@ -71,13 +71,13 @@ public class SpringBatchConfig { @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) { - return steps.get("step1"). chunk(10).reader(reader).processor(processor).writer(writer).build(); + return steps.get("step1").chunk(10).reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java index ed7d302047..35abcb2d16 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import java.net.MalformedURLException; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java index 3b2b9610f2..0ce3a413ab 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.model; +package org.baeldung.batch.model; import java.util.Date; diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java new file mode 100644 index 0000000000..667e013c35 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -0,0 +1,77 @@ +/* + * Copyright 2006-2013 the original author or 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 org.baeldung.batch.partitioner; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.batch.core.partition.support.Partitioner; +import org.springframework.batch.item.ExecutionContext; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +public class CustomMultiResourcePartitioner implements Partitioner { + + private static final String DEFAULT_KEY_NAME = "fileName"; + + private static final String PARTITION_KEY = "partition"; + + private Resource[] resources = new Resource[0]; + + private String keyName = DEFAULT_KEY_NAME; + + /** + * The resources to assign to each partition. In Spring configuration you + * can use a pattern to select multiple resources. + * @param resources the resources to use + */ + public void setResources(Resource[] resources) { + this.resources = resources; + } + + /** + * The name of the key for the file name in each {@link ExecutionContext}. + * Defaults to "fileName". + * @param keyName the value of the key + */ + public void setKeyName(String keyName) { + this.keyName = keyName; + } + + /** + * Assign the filename of each of the injected resources to an + * {@link ExecutionContext}. + * + * @see Partitioner#partition(int) + */ + @Override + public Map partition(int gridSize) { + Map map = new HashMap(gridSize); + int i = 0, k = 1; + for (Resource resource : resources) { + ExecutionContext context = new ExecutionContext(); + Assert.state(resource.exists(), "Resource does not exist: " + resource); + context.putString(keyName, resource.getFilename()); + context.putString("opFileName", "output" + k++ + ".xml"); + + map.put(PARTITION_KEY + i, context); + i++; + } + return map; + } + +} diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java new file mode 100644 index 0000000000..ad3aee4a2e --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -0,0 +1,166 @@ +package org.baeldung.batch.partitioner; + +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.RecordFieldSetMapper; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.launch.support.SimpleJobLauncher; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; +import org.springframework.batch.item.UnexpectedInputException; +import org.springframework.batch.item.file.FlatFileItemReader; +import org.springframework.batch.item.file.mapping.DefaultLineMapper; +import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; +import org.springframework.batch.item.xml.StaxEventItemWriter; +import org.springframework.batch.support.transaction.ResourcelessTransactionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.task.TaskExecutor; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.oxm.Marshaller; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + +@Configuration +@EnableBatchProcessing +public class SpringbatchPartitionConfig { + + @Autowired + ResourcePatternResolver resoursePatternResolver; + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Bean(name = "partitionerJob") + public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { + return jobs.get("partitionerJob") + .start(partitionStep()) + .build(); + } + + @Bean + public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("partitionStep") + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); + } + + @Bean + public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { + return steps.get("slaveStep") + .chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); + } + + @Bean + public CustomMultiResourcePartitioner partitioner() { + CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner(); + Resource[] resources; + try { + resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv"); + } catch (IOException e) { + throw new RuntimeException("I/O problems when resolving the input file pattern.", e); + } + partitioner.setResources(resources); + return partitioner; + } + + @Bean + @StepScope + public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { + FlatFileItemReader reader = new FlatFileItemReader<>(); + DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); + String[] tokens = {"username", "userid", "transactiondate", "amount"}; + tokenizer.setNames(tokens); + reader.setResource(new ClassPathResource("input/partitioner/" + filename)); + DefaultLineMapper lineMapper = new DefaultLineMapper<>(); + lineMapper.setLineTokenizer(tokenizer); + lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); + reader.setLinesToSkip(1); + reader.setLineMapper(lineMapper); + return reader; + } + + @Bean(destroyMethod = "") + @StepScope + public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { + StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); + itemWriter.setMarshaller(marshaller); + itemWriter.setRootTagName("transactionRecord"); + itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); + return itemWriter; + } + + @Bean + public Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setClassesToBeBound(Transaction.class); + return marshaller; + } + + @Bean + public TaskExecutor taskExecutor() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setMaxPoolSize(5); + taskExecutor.setCorePoolSize(5); + taskExecutor.setQueueCapacity(5); + taskExecutor.afterPropertiesSet(); + return taskExecutor; + } + + private JobRepository getJobRepository() throws Exception { + JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); + factory.setDataSource(dataSource()); + factory.setTransactionManager(getTransactionManager()); + // JobRepositoryFactoryBean's methods Throws Generic Exception, + // it would have been better to have a specific one + factory.afterPropertiesSet(); + return factory.getObject(); + } + + private DataSource dataSource() { + EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); + return builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); + } + + private PlatformTransactionManager getTransactionManager() { + return new ResourcelessTransactionManager(); + } + + public JobLauncher getJobLauncher() throws Exception { + SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); + // SimpleJobLauncher's methods Throws Generic Exception, + // it would have been better to have a specific one + jobLauncher.setJobRepository(getJobRepository()); + jobLauncher.afterPropertiesSet(); + return jobLauncher; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java new file mode 100644 index 0000000000..e56afc591c --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -0,0 +1,28 @@ +package org.baeldung.batch.partitioner; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class SpringbatchPartitionerApp { + public static void main(final String[] args) { + // Spring Java config + final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringbatchPartitionConfig.class); + context.refresh(); + + final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); + final Job job = (Job) context.getBean("partitionerJob"); + System.out.println("Starting the batch job"); + try { + final JobExecution execution = jobLauncher.run(job, new JobParameters()); + System.out.println("Job Status : " + execution.getStatus()); + System.out.println("Job succeeded"); + } catch (final Exception e) { + e.printStackTrace(); + System.out.println("Job failed"); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java similarity index 71% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java index ebee1d2802..8ca7892fec 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java index 94f9e7d94e..fa6f0870aa 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java @@ -1,9 +1,9 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; import java.text.ParseException; import java.text.SimpleDateFormat; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/resources/input/partitioner/record1.csv b/spring-batch/src/main/resources/input/partitioner/record1.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record1.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record2.csv b/spring-batch/src/main/resources/input/partitioner/record2.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record2.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record3.csv b/spring-batch/src/main/resources/input/partitioner/record3.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record3.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record4.csv b/spring-batch/src/main/resources/input/partitioner/record4.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record4.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record5.csv b/spring-batch/src/main/resources/input/partitioner/record5.csv new file mode 100644 index 0000000000..e554becb2a --- /dev/null +++ b/spring-batch/src/main/resources/input/partitioner/record5.csv @@ -0,0 +1,4 @@ +username, user_id, transaction_date, transaction_amount +devendra, 1234, 31/10/2015, 10000 +john, 2134, 3/12/2015, 12321 +robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output1.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output2.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output3.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output4.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml new file mode 100644 index 0000000000..194b860813 --- /dev/null +++ b/spring-batch/src/main/resources/output/output5.xml @@ -0,0 +1,21 @@ + + + + 10000.0 + 2015-10-31T00:00:00+05:30 + 1234 + devendra + + + 12321.0 + 2015-12-03T00:00:00+05:30 + 2134 + john + + + 23411.0 + 2015-02-02T00:00:00+05:30 + 2134 + robin + + \ No newline at end of file diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 93606d232f..0f76dd50ff 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="org.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.spring_batch_intro.model.Transaction + org.baeldung.batch.model.Transaction diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md new file mode 100644 index 0000000000..75a2b35be7 --- /dev/null +++ b/spring-boot-bootstrap/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Bootstrap a Simple Application using Spring Boot](http://www.baeldung.com/spring-boot-start) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 697a139eb5..9da37a3261 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -17,6 +17,25 @@ 1.5.3.RELEASE + + UTF-8 diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md index 5b2552ade7..8a598e7a05 100644 --- a/spring-boot-property-exp/README.md +++ b/spring-boot-property-exp/README.md @@ -1,2 +1,18 @@ ## The Module Holds Sources for the Following Articles - - [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot) \ No newline at end of file + - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot) + +### Module property-exp-default-config + This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible. + + In order to execute the Maven example, run the following command: + + `mvn spring-boot:run` + + To execute the Gradle example: + +`gradle bootRun` + + ### Module property-exp-custom-config + This project is not using the standard Spring Boot parent and is configured manually. Run the following command: + + `mvn exec:java` \ No newline at end of file diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index f554bb5b99..0c54d57db1 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -24,8 +24,8 @@ - property-exp-default - property-exp-custom + property-exp-default-config + property-exp-custom-config diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml similarity index 70% rename from spring-boot-property-exp/property-exp-custom/pom.xml rename to spring-boot-property-exp/property-exp-custom-config/pom.xml index 234404a6c0..7822b31cf2 100644 --- a/spring-boot-property-exp/property-exp-custom/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.baeldung - property-exp-custom + property-exp-custom-config 0.0.1-SNAPSHOT jar @@ -40,6 +40,15 @@ **/application*.properties + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + @@ -53,6 +62,14 @@ true + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp + + diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default-config/build.gradle similarity index 96% rename from spring-boot-property-exp/property-exp-default/build.gradle rename to spring-boot-property-exp/property-exp-default-config/build.gradle index f3c5f4a378..ec27de7c41 100644 --- a/spring-boot-property-exp/property-exp-default/build.gradle +++ b/spring-boot-property-exp/property-exp-default-config/build.gradle @@ -27,6 +27,10 @@ repositories { mavenCentral() } +springBoot { + executable = true +} + import org.apache.tools.ant.filters.ReplaceTokens processResources { with copySpec { diff --git a/spring-boot-property-exp/property-exp-default/gradle.properties b/spring-boot-property-exp/property-exp-default-config/gradle.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/gradle.properties rename to spring-boot-property-exp/property-exp-default-config/gradle.properties diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml similarity index 71% rename from spring-boot-property-exp/property-exp-default/pom.xml rename to spring-boot-property-exp/property-exp-default-config/pom.xml index 3629e56111..0625916d32 100644 --- a/spring-boot-property-exp/property-exp-default/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -11,7 +11,7 @@ com.baeldung - property-exp-default + property-exp-default-config 0.0.1-SNAPSHOT jar @@ -30,4 +30,16 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + diff --git a/spring-boot-property-exp/property-exp-default/settings.gradle b/spring-boot-property-exp/property-exp-default-config/settings.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/settings.gradle rename to spring-boot-property-exp/property-exp-default-config/settings.gradle diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 9a4a9f3686..e837c88804 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -23,4 +23,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) - [Testing in Spring Boot](http://www.baeldung.com/spring-boot-testing) - [Guide to @ConfigurationProperties in Spring Boot](http://www.baeldung.com/configuration-properties-in-spring-boot) +- [How to Get All Spring-Managed Beans?](http://www.baeldung.com/spring-show-all-beans) +- [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) + diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 2a1de00039..9d44de64a3 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -40,6 +40,22 @@ spring-boot-starter-security + + com.graphql-java + graphql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphiql-spring-boot-starter + 3.6.0 + + + com.graphql-java + graphql-java-tools + 3.2.0 + + org.springframework.boot spring-boot-starter-tomcat @@ -52,7 +68,7 @@ test - + io.dropwizard.metrics diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java index d54fa5a7c1..774eb69889 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java @@ -16,7 +16,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration; * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) * */ -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") public class SpringBootAnnotatedApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java index 44030f440b..580498e831 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) @ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") public class SpringBootPlainApp { diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index bad39c52c4..95b4a1a191 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -9,9 +9,8 @@ public class AttrListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent - .getServletContext() - .setAttribute("servlet-context-attr", "test"); + servletContextEvent.getServletContext() + .setAttribute("servlet-context-attr", "test"); System.out.println("context init"); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index 3419cd0eaf..a2995d1532 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -16,9 +16,8 @@ public class EchoServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { - Path path = File - .createTempFile("echo", "tmp") - .toPath(); + Path path = File.createTempFile("echo", "tmp") + .toPath(); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(path, response.getOutputStream()); Files.delete(path); diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index dc2368c5b2..650dae9806 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -18,9 +18,8 @@ public class HelloFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse - .getOutputStream() - .print(filterConfig.getInitParameter("msg")); + servletResponse.getOutputStream() + .print(filterConfig.getInitParameter("msg")); filterChain.doFilter(servletRequest, servletResponse); } diff --git a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index aeae7aecc9..3c27b8416f 100644 --- a/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ b/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -8,22 +8,22 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) +@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") }) public class HelloServlet extends HttpServlet { private ServletConfig servletConfig; @Override - public void init(ServletConfig servletConfig){ + public void init(ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { - response - .getOutputStream() - .write(servletConfig.getInitParameter("msg").getBytes()); + response.getOutputStream() + .write(servletConfig.getInitParameter("msg") + .getBytes()); } catch (IOException e) { e.printStackTrace(); } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 09f387902d..6dd127a8c3 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -92,21 +92,19 @@ public class MySQLAutoconfiguration { static class HibernateCondition extends SpringBootCondition { - private static final String[] CLASS_NAMES = { - "org.hibernate.ejb.HibernateEntityManager", - "org.hibernate.jpa.HibernateEntityManager" }; + private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); return Arrays.stream(CLASS_NAMES) - .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) - .map(className -> ConditionOutcome - .match(message.found("class").items(Style.NORMAL, className))) - .findAny() - .orElseGet(() -> ConditionOutcome - .noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) + .map(className -> ConditionOutcome.match(message.found("class") + .items(Style.NORMAL, className))) + .findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes") + .items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); } } diff --git a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java index fa411bc0b8..3d07e515b1 100644 --- a/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java +++ b/spring-boot/src/main/java/com/baeldung/autoconfiguration/example/MyUserRepository.java @@ -2,6 +2,6 @@ package com.baeldung.autoconfiguration.example; import org.springframework.data.jpa.repository.JpaRepository; -public interface MyUserRepository extends JpaRepository{ - +public interface MyUserRepository extends JpaRepository { + } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java index cd015e6554..6cc3f72cf6 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java @@ -10,13 +10,13 @@ public class Application { public static void main(String[] args) { applicationContext = SpringApplication.run(Application.class, args); - + displayAllBeans(); } - + public static void displayAllBeans() { String[] allBeanNames = applicationContext.getBeanDefinitionNames(); - for(String beanName : allBeanNames) { + for (String beanName : allBeanNames) { System.out.println(beanName); } } diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index 9f483b18d1..26f0a60bff 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -12,9 +12,9 @@ import com.baeldung.displayallbeans.service.FooService; public class FooController { @Autowired private FooService fooService; - - @RequestMapping(value="/displayallbeans") - public String getHeaderAndBody (Map model){ + + @RequestMapping(value = "/displayallbeans") + public String getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); return "displayallbeans"; diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java index e29f18c94a..1f3c15ee0e 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java @@ -4,15 +4,13 @@ import org.springframework.stereotype.Service; @Service public class FooService { - + public String getHeader() { return "Display All Beans"; } - + public String getBody() { - return "This is a sample application that displays all beans " - + "in Spring IoC container using ListableBeanFactory interface " - + "and Spring Boot Actuators."; + return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators."; } - + } diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java index d89dfc5fcd..a2b171c156 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java @@ -18,7 +18,10 @@ public class PersistenceConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build(); + EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2) + .addScript("schema-expressions.sql") + .addScript("data-expressions.sql") + .build(); return db; } } diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 9d379cbc09..84c96feb92 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class FailureAnalyzerApplication { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java index 2bbae8944a..04c7fdff9a 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/MyBeanNotOfRequiredTypeFailureAnalyzer.java @@ -4,8 +4,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; -public class MyBeanNotOfRequiredTypeFailureAnalyzer - extends AbstractFailureAnalyzer { +public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer { @Override protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) { @@ -13,16 +12,15 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer } private String getDescription(BeanNotOfRequiredTypeException ex) { - return String.format("The bean %s could not be injected as %s because it is of type %s", - ex.getBeanName(), - ex.getRequiredType().getName(), - ex.getActualType().getName()); + return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType() + .getName(), + ex.getActualType() + .getName()); } private String getAction(BeanNotOfRequiredTypeException ex) { - return String.format("Consider creating a bean with name %s of type %s", - ex.getBeanName(), - ex.getRequiredType().getName()); + return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType() + .getName()); } } diff --git a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java index c077692edb..4655e36f83 100644 --- a/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java +++ b/spring-boot/src/main/java/com/baeldung/git/CommitIdApplication.java @@ -8,7 +8,7 @@ import org.springframework.core.io.ClassPathResource; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class) public class CommitIdApplication { public static void main(String[] args) { SpringApplication.run(CommitIdApplication.class, args); diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot/src/main/java/com/baeldung/graphql/Author.java new file mode 100644 index 0000000000..11e927c564 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.graphql; + +public class Author { + private String id; + private String name; + private String thumbnail; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getThumbnail() { + return thumbnail; + } + + public void setThumbnail(String thumbnail) { + this.thumbnail = thumbnail; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java new file mode 100644 index 0000000000..522732faeb --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java @@ -0,0 +1,18 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.Optional; + +public class AuthorDao { + private List authors; + + public AuthorDao(List authors) { + this.authors = authors; + } + + public Optional getAuthor(String id) { + return authors.stream() + .filter(author -> id.equals(author.getId())) + .findFirst(); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java new file mode 100644 index 0000000000..982c6cebc1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class AuthorResolver implements GraphQLResolver { + private PostDao postDao; + + public AuthorResolver(PostDao postDao) { + this.postDao = postDao; + } + + public List getPosts(Author author) { + return postDao.getAuthorPosts(author.getId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java new file mode 100644 index 0000000000..c5ae8bd772 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.graphql; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class GraphqlConfiguration { + @Bean + public PostDao postDao() { + List posts = new ArrayList<>(); + for (int postId = 0; postId < 10; ++postId) { + for (int authorId = 0; authorId < 10; ++authorId) { + Post post = new Post(); + post.setId("Post" + authorId + postId); + post.setTitle("Post " + authorId + ":" + postId); + post.setText("Post " + postId + " + by author " + authorId); + post.setAuthorId("Author" + authorId); + posts.add(post); + } + } + return new PostDao(posts); + } + + @Bean + public AuthorDao authorDao() { + List authors = new ArrayList<>(); + for (int authorId = 0; authorId < 10; ++authorId) { + Author author = new Author(); + author.setId("Author" + authorId); + author.setName("Author " + authorId); + author.setThumbnail("http://example.com/authors/" + authorId); + authors.add(author); + } + return new AuthorDao(authors); + } + + @Bean + public PostResolver postResolver(AuthorDao authorDao) { + return new PostResolver(authorDao); + } + + @Bean + public AuthorResolver authorResolver(PostDao postDao) { + return new AuthorResolver(postDao); + } + + @Bean + public Query query(PostDao postDao) { + return new Query(postDao); + } + + @Bean + public Mutation mutation(PostDao postDao) { + return new Mutation(postDao); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java new file mode 100644 index 0000000000..5ccc80dad1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java @@ -0,0 +1,26 @@ +package com.baeldung.graphql; + +import java.util.UUID; + +import com.coxautodev.graphql.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + private PostDao postDao; + + public Mutation(PostDao postDao) { + this.postDao = postDao; + } + + public Post writePost(String title, String text, String category, String author) { + Post post = new Post(); + post.setId(UUID.randomUUID() + .toString()); + post.setTitle(title); + post.setText(text); + post.setCategory(category); + post.setAuthorId(author); + postDao.savePost(post); + + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot/src/main/java/com/baeldung/graphql/Post.java new file mode 100644 index 0000000000..14d3084841 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Post.java @@ -0,0 +1,49 @@ +package com.baeldung.graphql; + +public class Post { + private String id; + private String title; + private String text; + private String category; + private String authorId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java new file mode 100644 index 0000000000..f8d243ee3a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java @@ -0,0 +1,29 @@ +package com.baeldung.graphql; + +import java.util.List; +import java.util.stream.Collectors; + +public class PostDao { + private List posts; + + public PostDao(List posts) { + this.posts = posts; + } + + public List getRecentPosts(int count, int offset) { + return posts.stream() + .skip(offset) + .limit(count) + .collect(Collectors.toList()); + } + + public List getAuthorPosts(String author) { + return posts.stream() + .filter(post -> author.equals(post.getAuthorId())) + .collect(Collectors.toList()); + } + + public void savePost(Post post) { + posts.add(0, post); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java new file mode 100644 index 0000000000..dbfde330ea --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.Optional; + +import com.coxautodev.graphql.tools.GraphQLResolver; + +public class PostResolver implements GraphQLResolver { + private AuthorDao authorDao; + + public PostResolver(AuthorDao authorDao) { + this.authorDao = authorDao; + } + + public Optional getAuthor(Post post) { + return authorDao.getAuthor(post.getAuthorId()); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot/src/main/java/com/baeldung/graphql/Query.java new file mode 100644 index 0000000000..7bb625798c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graphql/Query.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import java.util.List; + +import com.coxautodev.graphql.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + private PostDao postDao; + + public Query(PostDao postDao) { + this.postDao = postDao; + } + + public List recentPosts(int count, int offset) { + return postDao.getRecentPosts(count, offset); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java index b743eb4b61..ca56437392 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class InternationalizationApp { @RolesAllowed("*") public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/intro/App.java b/spring-boot/src/main/java/com/baeldung/intro/App.java index 9553d814ac..b865deea29 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/App.java +++ b/spring-boot/src/main/java/com/baeldung/intro/App.java @@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -public class App -{ - public static void main( String[] args ) - { +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +public class App { + public static void main(String[] args) { SpringApplication.run(App.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java index 9109b0a292..2a82e58829 100644 --- a/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java +++ b/spring-boot/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController; public class HomeController { @RequestMapping("/") - public String root(){ + public String root() { return "Index Page"; } - + @RequestMapping("/local") - public String local(){ + public String local() { return "/local"; } } diff --git a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java index 8965e2f013..c8461e4efc 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/ApplicationMain.java @@ -7,7 +7,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class ApplicationMain extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 3d6a10c2ac..2d8298338c 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -26,10 +26,13 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter { configurer.enable(); } - @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + registry.addResourceHandler("/resources/**") + .addResourceLocations("/resources/") + .setCachePeriod(3600) + .resourceChain(true) + .addResolver(new PathResourceResolver()); } @Bean diff --git a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java index 56a6751326..bbab95c41f 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java @@ -9,8 +9,9 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.ConfigurableEnvironment; @Configuration -@ComponentScan(basePackages = { "com.baeldung.*" }) -@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { +@ComponentScan(basePackages = { "com.baeldung.servlets.*" }) +@PropertySource("classpath:custom.properties") +public class PropertySourcesLoader { private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); diff --git a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java index b50a7d5454..358ff5af2d 100644 --- a/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ b/spring-boot/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java @@ -7,14 +7,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(name = "AnnotationServlet", - description = "Example Servlet Using Annotations", - urlPatterns = { "/annotationservlet" }) +@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" }) public class AnnotationServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); + request.getRequestDispatcher("/annotationservlet.jsp") + .forward(request, response); } } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java index 7ea7c11fde..4e75fc6411 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java @@ -2,6 +2,6 @@ package com.baeldung.toggle; import org.springframework.data.repository.CrudRepository; -public interface EmployeeRepository extends CrudRepository{ +public interface EmployeeRepository extends CrudRepository { } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java index 245415a2a0..b05ec2bf52 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java @@ -10,13 +10,15 @@ import org.togglz.core.context.FeatureContext; public enum MyFeatures implements Feature { - @Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, - parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), - @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) + @Label("Employee Management Feature") + @EnabledByDefault + @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"), + @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") }) EMPLOYEE_MANAGEMENT_FEATURE; public boolean isActive() { - return FeatureContext.getFeatureManager().isActive(this); + return FeatureContext.getFeatureManager() + .isActive(this); } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/Application.java b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java similarity index 53% rename from spring-boot/src/main/java/com/baeldung/utils/Application.java rename to spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java index 9d5d75bce2..4b00247c4a 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/Application.java +++ b/spring-boot/src/main/java/com/baeldung/utils/UtilsApplication.java @@ -8,13 +8,13 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) -@ComponentScan(basePackages="com.baeldung.utils") -public class Application { +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@ComponentScan(basePackages = "com.baeldung.utils") +public class UtilsApplication { - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + @RolesAllowed("*") + public static void main(String[] args) { + SpringApplication.run(UtilsApplication.class, args); + } } diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java index 7b4827cdf2..7c66391bd2 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -13,37 +13,37 @@ import org.springframework.web.util.WebUtils; @Controller public class UtilsController { - @GetMapping("/utils") - public String webUtils(Model model) { - return "utils"; - } - - @PostMapping("/setParam") - public String post(HttpServletRequest request, Model model) { - String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); - -// Long param = ServletRequestUtils.getLongParameter(request, "param",1L); -// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); -// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); -// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); -// int param = ServletRequestUtils.getIntParameter(request, "param", 100); - -// try { -// ServletRequestUtils.getRequiredStringParameter(request, "param"); -// } catch (ServletRequestBindingException e) { -// e.printStackTrace(); -// } - - WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); - return "utils"; - } - - @GetMapping("/other") - public String other(HttpServletRequest request, Model model) { - String param = (String) WebUtils.getSessionAttribute(request, "parameter"); - model.addAttribute("parameter", param); - return "other"; - } - + @GetMapping("/utils") + public String webUtils(Model model) { + return "utils"; + } + + @PostMapping("/setParam") + public String post(HttpServletRequest request, Model model) { + String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); + + // Long param = ServletRequestUtils.getLongParameter(request, "param",1L); + // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); + // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); + // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); + // int param = ServletRequestUtils.getIntParameter(request, "param", 100); + + // try { + // ServletRequestUtils.getRequiredStringParameter(request, "param"); + // } catch (ServletRequestBindingException e) { + // e.printStackTrace(); + // } + + WebUtils.setSessionAttribute(request, "parameter", param); + model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter")); + return "utils"; + } + + @GetMapping("/other") + public String other(HttpServletRequest request, Model model) { + String param = (String) WebUtils.getSessionAttribute(request, "parameter"); + model.addAttribute("parameter", param); + return "other"; + } + } diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index 44d48f5f8f..8704b42166 100644 --- a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ b/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class WebjarsdemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/Application.java b/spring-boot/src/main/java/org/baeldung/Application.java index 8b49f4d6ab..1c1e466afc 100644 --- a/spring-boot/src/main/java/org/baeldung/Application.java +++ b/spring-boot/src/main/java/org/baeldung/Application.java @@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContext; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { private static ApplicationContext applicationContext; diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java index 2d83b650ec..cb269f77f1 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -1,11 +1,14 @@ package org.baeldung.boot; +import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; +import org.springframework.context.annotation.Import; -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) +@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java index 235fd43299..4ff8e9fdd4 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java +++ b/spring-boot/src/main/java/org/baeldung/boot/components/FooService.java @@ -10,11 +10,11 @@ public class FooService { @Autowired private FooRepository fooRepository; - + public Foo getFooWithId(Integer id) throws Exception { return fooRepository.findOne(id); } - + public Foo getFooWithName(String name) { return fooRepository.findByName(name); } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java index 1f008440e6..e03b859eab 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/CommonException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class CommonException extends RuntimeException{ +public class CommonException extends RuntimeException { /** * */ private static final long serialVersionUID = 3080004140659213332L; - public CommonException(String message){ + public CommonException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java index 68ef3fa389..0b04bd2759 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ b/spring-boot/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class FooNotFoundException extends RuntimeException{ +public class FooNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 9042200028456133589L; - public FooNotFoundException(String message){ + public FooNotFoundException(String message) { super(message); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java index ac8a8fe429..d373e25b85 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java +++ b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java @@ -21,7 +21,6 @@ public class Foo implements Serializable { this.name = name; } - public Foo(Integer id, String name) { super(); this.id = id; diff --git a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java index 834fa342e2..d400c3bf9e 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java +++ b/spring-boot/src/main/java/org/baeldung/boot/service/FooController.java @@ -18,7 +18,7 @@ public class FooController { public Foo getFooWithId(@PathVariable Integer id) throws Exception { return fooService.getFooWithId(id); } - + @GetMapping("/") public Foo getFooWithName(@RequestParam String name) throws Exception { return fooService.getFooWithName(name); diff --git a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java index 7d1ad7d899..a9e7dee0b7 100644 --- a/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java +++ b/spring-boot/src/main/java/org/baeldung/controller/GenericEntityController.java @@ -39,21 +39,31 @@ public class GenericEntityController { @RequestMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { - return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); + return entityList.stream() + .filter(entity -> entity.getId() + .equals(id)) + .findFirst() + .get(); } @GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbymode/{mode}") public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { - return entityList.stream().findFirst().get(); + return entityList.stream() + .findFirst() + .get(); } @GetMapping("/entity/findbyversion") public ResponseEntity findByVersion(@Version String version) { - return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); + return version != null ? new ResponseEntity(entityList.stream() + .findFirst() + .get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); } } diff --git a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java index 1a175aed48..68fbffda6e 100644 --- a/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ b/spring-boot/src/main/java/org/baeldung/endpoints/MyHealthCheck.java @@ -10,9 +10,13 @@ public class MyHealthCheck implements HealthIndicator { public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { - return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); + return Health.down() + .withDetail("Error Code", errorCode) + .withDetail("Description", "You custom MyHealthCheck endpoint is down") + .build(); } - return Health.up().build(); + return Health.up() + .build(); } public int check() { diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java index 2001340197..cb1b838ca4 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserCombinedSerializer.java @@ -21,8 +21,7 @@ public class UserCombinedSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } @@ -37,7 +36,8 @@ public class UserCombinedSerializer { public static class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java index d18de7e3f1..a310dcba5a 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonDeserializer.java @@ -15,7 +15,8 @@ import java.io.IOException; public class UserJsonDeserializer extends JsonDeserializer { @Override public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { - TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser); + TreeNode treeNode = jsonParser.getCodec() + .readTree(jsonParser); TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor"); return new User(Color.web(favoriteColor.asText())); } diff --git a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java index d90f662a4b..845bc3aac5 100644 --- a/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java +++ b/spring-boot/src/main/java/org/baeldung/jsoncomponent/UserJsonSerializer.java @@ -15,8 +15,7 @@ public class UserJsonSerializer extends JsonSerializer { @Override public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("favoriteColor", - getColorAsWebColor(user.getFavoriteColor())); + jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor())); jsonGenerator.writeEndObject(); } diff --git a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java index 872426d850..2d118b0eae 100644 --- a/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java @@ -20,7 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController -@EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class) +@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class) @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) public class SpringBootApplication { diff --git a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java index 8100e61629..40f36ef924 100644 --- a/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java +++ b/spring-boot/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java @@ -14,7 +14,8 @@ public class MonitoringConfig { @Bean public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry).build(); + JmxReporter reporter = JmxReporter.forRegistry(registry) + .build(); reporter.start(); return reporter; } diff --git a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java index ed0090f8e4..6d89f7f695 100644 --- a/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ b/spring-boot/src/main/java/org/baeldung/service/LoginServiceImpl.java @@ -16,7 +16,8 @@ public class LoginServiceImpl implements LoginService { public boolean login(String userName, char[] password) { boolean success; - if (userName.equals("admin") && "secret".toCharArray().equals(password)) { + if (userName.equals("admin") && "secret".toCharArray() + .equals(password)) { counterService.increment("counter.login.success"); success = true; } else { diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index 9f8dadbe55..c0cc669420 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -10,7 +10,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; import com.baeldung.autoconfiguration.MySQLAutoconfiguration; @EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication(exclude=MySQLAutoconfiguration.class) +@SpringBootApplication(exclude = MySQLAutoconfiguration.class) public class Application { public static void main(String[] args) { System.setProperty("spring.config.name", "exception"); diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 83de888e5e..36d87e6dad 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -14,12 +14,14 @@ public class FooRepositoryImpl implements FooRepository { @Override public void save(Foo foo) { - sessionFactory.getCurrentSession().saveOrUpdate(foo); + sessionFactory.getCurrentSession() + .saveOrUpdate(foo); } @Override public Foo get(Integer id) { - return sessionFactory.getCurrentSession().get(Foo.class, id); + return sessionFactory.getCurrentSession() + .get(Foo.class, id); } } \ No newline at end of file diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java index bcab44870b..2744c49f62 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/Message.java @@ -20,6 +20,5 @@ public class Message { public void setText(String text) { this.text = text; } - - + } diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java index 35bf1827ea..45fbf2b623 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java @@ -17,12 +17,12 @@ import java.lang.reflect.Type; * */ public class MyStompSessionHandler extends StompSessionHandlerAdapter { - + private Logger logger = Logger.getLogger(MyStompSessionHandler.class); - + @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { - logger.info("New session established : "+session.getSessionId()); + logger.info("New session established : " + session.getSessionId()); session.subscribe("/topic/messages", this); logger.info("Subscribed to /topic/messages"); session.send("/app/chat", getSampleMessage()); @@ -41,15 +41,15 @@ public class MyStompSessionHandler extends StompSessionHandlerAdapter { @Override public void handleFrame(StompHeaders headers, Object payload) { - Message msg = (Message)payload; - logger.info("Received : "+ msg.getText()+ " from : "+msg.getFrom()); + Message msg = (Message) payload; + logger.info("Received : " + msg.getText() + " from : " + msg.getFrom()); } - + /** * A sample message instance. * @return instance of Message */ - private Message getSampleMessage(){ + private Message getSampleMessage() { Message msg = new Message(); msg.setFrom("Nicky"); msg.setText("Howdy!!"); diff --git a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java index 71f5471fb1..2bff07186d 100644 --- a/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot/src/main/java/org/baeldung/websocket/client/StompClient.java @@ -19,9 +19,9 @@ public class StompClient { public static void main(String[] args) { WebSocketClient client = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(client); - + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); - + StompSessionHandler sessionHandler = new MyStompSessionHandler(); stompClient.connect(URL, sessionHandler); diff --git a/spring-boot/src/main/resources/graphql/blog.graphqls b/spring-boot/src/main/resources/graphql/blog.graphqls new file mode 100644 index 0000000000..aa0c8757e9 --- /dev/null +++ b/spring-boot/src/main/resources/graphql/blog.graphqls @@ -0,0 +1,24 @@ +type Post { + id: ID! + title: String! + text: String! + category: String + author: Author +} + +type Author { + id: ID! + name: String! + thumbnail: String + posts: [Post]! +} + +# The Root Query for the application +type Query { + recentPosts(count: Int, offset: Int): [Post]! +} + +# The Root Mutation for the application +type Mutation { + writePost(title: String!, text: String!, category: String, author: String!) : Post! +} diff --git a/spring-boot/src/main/webapp/WEB-INF/context.xml b/spring-boot/src/main/webapp/WEB-INF/context.xml index 263bed4430..32f11f78f6 100644 --- a/spring-boot/src/main/webapp/WEB-INF/context.xml +++ b/spring-boot/src/main/webapp/WEB-INF/context.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> - + - + \ No newline at end of file diff --git a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml index ade8e66777..54e62921be 100644 --- a/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml +++ b/spring-boot/src/main/webapp/WEB-INF/dispatcher.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - + diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8d5eb56bf4..b2b14f766e 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -14,7 +14,9 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @@ -22,7 +24,8 @@ import static org.junit.Assert.*; @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; @Test public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { @@ -37,12 +40,12 @@ public class SpringBootWithServletComponentIntegrationTest { FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); assertNotNull(filterRegistration); - assertTrue(filterRegistration - .getServletNameMappings() - .contains("echo servlet")); + assertTrue(filterRegistration.getServletNameMappings() + .contains("echo servlet")); } - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletFilter_whenGetHello_thenRequestFiltered() { @@ -58,8 +61,4 @@ public class SpringBootWithServletComponentIntegrationTest { assertEquals("filtering echo", responseEntity.getBody()); } - - } - - diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 64507ad02c..a13cd250a2 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -14,7 +14,9 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @@ -22,9 +24,11 @@ import static org.junit.Assert.*; @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletContext_whenAccessAttrs_thenNotFound() { @@ -46,5 +50,3 @@ public class SpringBootWithoutServletComponentIntegrationTest { } } - - diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java index dda9d69edd..30ba397b46 100644 --- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java @@ -1,5 +1,8 @@ package com.baeldung.autoconfiguration; +import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; +import com.baeldung.autoconfiguration.example.MyUser; +import com.baeldung.autoconfiguration.example.MyUserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -7,10 +10,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; -import com.baeldung.autoconfiguration.example.MyUser; -import com.baeldung.autoconfiguration.example.MyUserRepository; - @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) @EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 530b8e9cb3..8bd9c20c5e 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -1,15 +1,5 @@ package com.baeldung.displayallbeans; -import static org.assertj.core.api.BDDAssertions.then; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -23,11 +13,19 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.displayallbeans.Application; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = {"management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false"}) +@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" }) public class DisplayBeanIntegrationTest { @LocalServerPort @@ -44,17 +42,15 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.port + "/displayallbeans", String.class); - + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - + @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -62,20 +58,22 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity( - "http://localhost:" + this.mgt + "/springbeans", List.class); + ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); - List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); - List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); + List> allBeans = (List) ((Map) entity.getBody() + .get(0)).get("beans"); + List beanNamesList = allBeans.stream() + .map(x -> (String) x.get("bean")) + .collect(Collectors.toList()); - assertThat( beanNamesList, hasItem("fooController")); - assertThat( beanNamesList, hasItem("fooService")); + assertThat(beanNamesList, hasItem("fooController")); + assertThat(beanNamesList, hasItem("fooService")); } - + @Test public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { String[] beanNames = context.getBeanDefinitionNames(); - + List beanNamesList = Arrays.asList(beanNames); assertTrue(beanNamesList.contains("fooController")); assertTrue(beanNamesList.contains("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index af46fe0423..4856c17c7d 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -26,16 +26,18 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + mvc.perform(MockMvcRequestBuilders.get("/") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + mvc.perform(MockMvcRequestBuilders.get("/local") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index e40678603b..5b70fa3cbe 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -1,9 +1,5 @@ package com.baeldung.toggle; -import static org.junit.Assert.*; -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; @@ -16,6 +12,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) @AutoConfigureMockMvc @@ -35,7 +35,8 @@ public class ToggleIntegrationTest { @Before public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) + .build(); } @Test @@ -45,7 +46,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "false"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5); @@ -58,7 +60,8 @@ public class ToggleIntegrationTest { System.setProperty("employee.feature", "true"); - mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200)); + mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")) + .andExpect(status().is(200)); emp = employeeRepository.findOne(1L); assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5); diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index 829c0a6ac4..5a80e13791 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.utils; +import com.baeldung.utils.controller.UtilsController; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -10,32 +11,27 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.baeldung.utils.controller.UtilsController; - public class UtilsControllerIntegrationTest { - @InjectMocks + @InjectMocks private UtilsController utilsController; - + private MockMvc mockMvc; - + @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + .build(); } - + @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { - String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) - .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + String param = "testparam"; + this.mockMvc.perform(post("/setParam").param("param", param) + .sessionAttr("parameter", param)) + .andExpect(status().isOk()); } - + } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index f30c8ee4e7..4dc4793ce2 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -6,11 +6,6 @@ import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; -/** - * Test class for MyStompSessionHandler - * @author Kalyan - * - */ public class MyStompSessionHandlerIntegrationTest { @Test @@ -19,8 +14,9 @@ public class MyStompSessionHandlerIntegrationTest { StompHeaders mockHeader = Mockito.mock(StompHeaders.class); MyStompSessionHandler sessionHandler = new MyStompSessionHandler(); sessionHandler.afterConnected(mockSession, mockHeader); - Mockito.verify(mockSession).subscribe("/topic/messages", sessionHandler); - Mockito.verify(mockSession).send(Mockito.anyString(), Mockito.anyObject()); + Mockito.verify(mockSession) + .subscribe("/topic/messages", sessionHandler); + Mockito.verify(mockSession) + .send(Mockito.anyString(), Mockito.anyObject()); } } - diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java index c5cca3c5fb..358ba942d9 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java @@ -33,36 +33,56 @@ public class SpringBootApplicationIntegrationTest { @Before public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .build(); } @Test public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$", hasSize(4))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } @Test public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); + mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion") + .header("Version", "1.0.0")) + .andExpect(MockMvcResultMatchers.status() + .isOk()) + .andExpect(MockMvcResultMatchers.content() + .contentType(contentType)) + .andExpect(jsonPath("$.id", equalTo(1))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 10e3d6d60b..0e8a698f41 100644 --- a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -62,11 +62,15 @@ public class SpringBootMailIntegrationTest { } private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { - return wiserMessage.getMimeMessage().getContent().toString().trim(); + return wiserMessage.getMimeMessage() + .getContent() + .toString() + .trim(); } private String getSubject(WiserMessage wiserMessage) throws MessagingException { - return wiserMessage.getMimeMessage().getSubject(); + return wiserMessage.getMimeMessage() + .getSubject(); } private SimpleMailMessage composeEmailMessage() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java index ec599beedf..ebde0e243a 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,9 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +7,10 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @DataJpaTest public class EmployeeRepositoryIntegrationTest { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index 4c3a50f933..9e5613ab10 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,19 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasSize; -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.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.IOException; -import java.util.List; - import org.baeldung.boot.DemoApplication; import org.junit.After; import org.junit.Test; @@ -27,6 +13,20 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +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.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) @AutoConfigureMockMvc diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java index 8038ae4373..9837b02df6 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,10 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +11,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { @@ -46,7 +46,7 @@ public class EmployeeServiceImplIntegrationTest { Mockito.when(employeeRepository.findByName(john.getName())) .thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); + .thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")) .thenReturn(null); Mockito.when(employeeRepository.findById(john.getId())) @@ -61,10 +61,9 @@ public class EmployeeServiceImplIntegrationTest { public void whenValidName_thenEmployeeShouldBeFound() { String name = "alex"; Employee found = employeeService.getEmployeeByName(name); - - assertThat(found.getName()) - .isEqualTo(name); - } + + assertThat(found.getName()).isEqualTo(name); + } @Test public void whenInValidName_thenEmployeeShouldNotBeFound() { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java index 3d532ce54a..36d07164b2 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java @@ -1,12 +1,12 @@ package org.baeldung.boot.boottest; -import java.io.IOException; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; -public class JsonUtil { - public static byte[] toJson(Object object) throws IOException { +import java.io.IOException; + +class JsonUtil { + static byte[] toJson(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.writeValueAsBytes(object); diff --git a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java index 5627855aa3..0f6c13ae1f 100644 --- a/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java @@ -30,7 +30,8 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")) + .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java index c1b4c8912c..ac47c5e5d9 100644 --- a/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/jsoncomponent/UserJsonSerializerIntegrationTest.java @@ -1,6 +1,5 @@ package org.baeldung.jsoncomponent; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.scene.paint.Color; diff --git a/spring-cloud-bus/README.md b/spring-cloud-bus/README.md new file mode 100644 index 0000000000..c5410ca4e2 --- /dev/null +++ b/spring-cloud-bus/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Spring Cloud Bus](http://www.baeldung.com/spring-cloud-bus) diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD index a174fba3dd..164219c185 100644 --- a/spring-cloud/spring-cloud-bootstrap/README.MD +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -2,9 +2,9 @@ - [Spring Cloud – Bootstrapping](http://www.baeldung.com/spring-cloud-bootstrapping) - [Spring Cloud – Securing Services](http://www.baeldung.com/spring-cloud-securing-services) - [Spring Cloud – Tracing Services with Zipkin](http://www.baeldung.com/tracing-services-with-zipkin) +- [Spring Cloud Series – The Gateway Pattern](http://www.baeldung.com/spring-cloud-gateway-pattern) - [Spring Cloud – Adding Angular 4](http://www.baeldung.com/spring-cloud-angular) - - To run the project: - copy the appliction-config folder to c:\Users\{username}\ on Windows or /Users/{username}/ on *nix. Then open a git bash terminal in application-config and run: - git init diff --git a/spring-core/README.md b/spring-core/README.md index 380b3138fe..237f8cd4e9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,3 +6,6 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) +- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) + diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 85cf4573aa..deffaf41db 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -1,141 +1,147 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 + 4.0.0 - com.baeldung - spring-core - 0.0.1-SNAPSHOT - war + com.baeldung + spring-core + 0.0.1-SNAPSHOT + war - spring-core + spring-core - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.mockito - mockito-all - ${mockito.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - com.google.guava - guava - ${guava.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter - 1.5.2.RELEASE - - - org.springframework.boot - spring-boot-test - ${mockito.spring.boot.version} - test - - + + + org.mockito + mockito-all + ${mockito.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.boot + spring-boot-starter + 1.5.2.RELEASE + + + org.springframework.boot + spring-boot-test + ${mockito.spring.boot.version} + test + + + commons-io + commons-io + ${commons.io.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + - + - + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + - - 1.10.19 - 1.4.4.RELEASE - 4.3.4.RELEASE - 1 - 20.0 - 2.6 - 1.16.12 - + + 1.10.19 + 1.4.4.RELEASE + 4.3.4.RELEASE + 1 + 20.0 + 2.6 + 1.16.12 + 2.5 + - - - java.net - https://maven.java.net/content/repositories/releases/ - - + + + java.net + https://maven.java.net/content/repositories/releases/ + + - + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..d9097188b3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -0,0 +1,22 @@ +package com.baeldung.streamutils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.util.StreamUtils; + +public class CopyStream { + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } + + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } +} diff --git a/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..1ce67a075a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -0,0 +1,11 @@ +package com.baeldung.streamutils; + +import java.io.InputStream; + +import org.springframework.util.StreamUtils; + +public class DrainStream { + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java new file mode 100644 index 0000000000..d2cda19ae6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java @@ -0,0 +1,75 @@ +package com.baeldung.valuewithdefaults; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Lists.newArrayList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Lists.newArrayList(1, 2, 3); + Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + + } +} diff --git a/spring-core/src/main/resources/valueswithdefaults.properties b/spring-core/src/main/resources/valueswithdefaults.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9fe2f00a77 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + assertEquals(inputFileContent, content); + } + +} diff --git a/spring-core/src/test/resources/input.txt b/spring-core/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/spring-core/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/spring-core/src/test/resources/output.txt b/spring-core/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/spring-core/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 84d49a3e35..7060ec5b36 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -115,7 +115,7 @@ 4.3.4.RELEASE - 1.9.6.RELEASE + 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java b/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java index 9fba40245b..aae0214d09 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java @@ -8,5 +8,4 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface CascadeSave { - } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java index 6910245b2b..80b177f4c9 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java @@ -1,8 +1,7 @@ package org.baeldung.config; -import java.util.ArrayList; -import java.util.List; - +import com.mongodb.Mongo; +import com.mongodb.MongoClient; import org.baeldung.converter.UserWriterConverter; import org.baeldung.event.CascadeSaveMongoEventListener; import org.baeldung.event.UserCascadeSaveMongoEventListener; @@ -14,8 +13,8 @@ import org.springframework.data.mongodb.core.convert.CustomConversions; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; +import java.util.ArrayList; +import java.util.List; @Configuration @EnableMongoRepositories(basePackages = "org.baeldung.repository") diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java index 6140382f82..9653796d8d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java @@ -1,13 +1,12 @@ package org.baeldung.config; +import com.mongodb.Mongo; +import com.mongodb.MongoClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; - @Configuration @EnableMongoRepositories(basePackages = "org.baeldung.repository") public class SimpleMongoConfig { diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java index 2dedda46ec..4a6970489e 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java @@ -1,11 +1,10 @@ package org.baeldung.converter; -import org.baeldung.model.User; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - import com.mongodb.BasicDBObject; import com.mongodb.DBObject; +import org.baeldung.model.User; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; @Component public class UserWriterConverter implements Converter { diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java index e01a1bc8c0..94cad4566a 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java @@ -12,7 +12,7 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { private Object source; private MongoOperations mongoOperations; - public CascadeCallback(final Object source, final MongoOperations mongoOperations) { + CascadeCallback(final Object source, final MongoOperations mongoOperations) { this.source = source; this.setMongoOperations(mongoOperations); } @@ -35,7 +35,7 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { } - public Object getSource() { + private Object getSource() { return source; } @@ -43,11 +43,11 @@ public class CascadeCallback implements ReflectionUtils.FieldCallback { this.source = source; } - public MongoOperations getMongoOperations() { + private MongoOperations getMongoOperations() { return mongoOperations; } - public void setMongoOperations(final MongoOperations mongoOperations) { + private void setMongoOperations(final MongoOperations mongoOperations) { this.mongoOperations = mongoOperations; } } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java index 79840fb570..acc377011d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java @@ -3,6 +3,7 @@ package org.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; import org.springframework.util.ReflectionUtils; public class CascadeSaveMongoEventListener extends AbstractMongoEventListener { @@ -11,7 +12,8 @@ public class CascadeSaveMongoEventListener extends AbstractMongoEventListener event) { + final Object source = event.getSource(); ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations)); } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java index 423df59b95..ade20bcc1d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -4,14 +4,16 @@ import org.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener { @Autowired private MongoOperations mongoOperations; @Override - public void onBeforeConvert(final Object source) { - if (source instanceof User && ((User) source).getEmailAddress() != null) { + public void onBeforeConvert(final BeforeConvertEvent event) { + final Object source = event.getSource(); + if ((source instanceof User) && (((User) source).getEmailAddress() != null)) { mongoOperations.save(((User) source).getEmailAddress()); } } diff --git a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java index 7d51f7b6cc..8e442e8b7f 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,12 +1,12 @@ package org.baeldung.repository; -import java.util.List; - import org.baeldung.model.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import java.util.List; + public interface UserRepository extends MongoRepository, QueryDslPredicateExecutor { @Query("{ 'name' : ?0 }") List findUsersByName(String name); @@ -26,10 +26,10 @@ public interface UserRepository extends MongoRepository, QueryDslP List findByNameStartingWith(String regexp); List findByNameEndingWith(String regexp); - - @Query(value="{}", fields="{name : 1}") + + @Query(value = "{}", fields = "{name : 1}") List findNameAndId(); - - @Query(value="{}", fields="{_id : 0}") + + @Query(value = "{}", fields = "{_id : 0}") List findNameAndAgeExcludeId(); } diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java index a25a904758..5686465c19 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -1,17 +1,10 @@ package org.baeldung.aggregation; -import static org.junit.Assert.*; -import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.DBObject; +import com.mongodb.MongoClient; +import com.mongodb.util.JSON; import org.baeldung.aggregation.model.StatePopulation; import org.baeldung.config.MongoConfig; import org.junit.AfterClass; @@ -33,18 +26,30 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBObject; -import com.mongodb.MongoClient; -import com.mongodb.util.JSON; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.project; +import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class ZipsAggregationLiveTest { private static MongoClient client; - + @Autowired private MongoTemplate mongoTemplate; @@ -58,7 +63,7 @@ public class ZipsAggregationLiveTest { InputStream zipsJsonStream = ZipsAggregationLiveTest.class.getResourceAsStream("/zips.json"); BufferedReader reader = new BufferedReader(new InputStreamReader(zipsJsonStream)); reader.lines() - .forEach(line -> zipsCollection.insert((DBObject) JSON.parse(line))); + .forEach(line -> zipsCollection.insert((DBObject) JSON.parse(line))); reader.close(); } @@ -95,7 +100,7 @@ public class ZipsAggregationLiveTest { * decreasing population */ List actualList = StreamSupport.stream(result.spliterator(), false) - .collect(Collectors.toList()); + .collect(Collectors.toList()); List expectedList = new ArrayList<>(actualList); Collections.sort(expectedList, (sp1, sp2) -> sp2.getStatePop() - sp1.getStatePop()); @@ -111,7 +116,7 @@ public class ZipsAggregationLiveTest { GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop"); SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop")); ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state") - .andExpression("avgCityPop").as("statePop"); + .andExpression("avgCityPop").as("statePop"); LimitOperation limitToOnlyFirstDoc = limit(1); Aggregation aggregation = newAggregation(sumTotalCityPop, averageStatePop, sortByAvgPopAsc, limitToOnlyFirstDoc, projectToMatchModel); @@ -121,7 +126,7 @@ public class ZipsAggregationLiveTest { assertEquals("ND", smallestState.getState()); assertTrue(smallestState.getStatePop() - .equals(1645)); + .equals(1645)); } @Test @@ -130,8 +135,8 @@ public class ZipsAggregationLiveTest { GroupOperation sumZips = group("state").count().as("zipCount"); SortOperation sortByCount = sort(Direction.ASC, "zipCount"); GroupOperation groupFirstAndLast = group().first("_id").as("minZipState") - .first("zipCount").as("minZipCount").last("_id").as("maxZipState") - .last("zipCount").as("maxZipCount"); + .first("zipCount").as("minZipCount").last("_id").as("maxZipState") + .last("zipCount").as("maxZipCount"); Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast); diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java index 3853a406fb..88205ba7fd 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java @@ -1,19 +1,8 @@ package org.baeldung.gridfs; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.baeldung.config.MongoConfig; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.gridfs.GridFSDBFile; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,9 +16,18 @@ import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.gridfs.GridFSDBFile; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; @ContextConfiguration("file:src/main/resources/mongoConfig.xml") @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java index df3ebcb2d2..729b0f6dfa 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -1,11 +1,5 @@ package org.baeldung.mongotemplate; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.util.Iterator; -import java.util.List; - import org.baeldung.config.MongoConfig; import org.baeldung.model.EmailAddress; import org.baeldung.model.User; @@ -23,6 +17,12 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.util.Iterator; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class DocumentQueryLiveTest { diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 61115faede..2d2117afbb 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -1,9 +1,5 @@ package org.baeldung.mongotemplate; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import org.baeldung.config.SimpleMongoConfig; import org.baeldung.model.User; import org.junit.After; @@ -16,6 +12,10 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SimpleMongoConfig.class) public class MongoTemplateProjectionLiveTest { @@ -42,14 +42,14 @@ public class MongoTemplateProjectionLiveTest { final Query query = new Query(); query.fields() - .include("name"); + .include("name"); mongoTemplate.find(query, User.class) - .forEach(user -> { - assertNotNull(user.getName()); - assertTrue(user.getAge() - .equals(0)); - }); + .forEach(user -> { + assertNotNull(user.getName()); + assertTrue(user.getAge() + .equals(0)); + }); } @Test @@ -59,13 +59,13 @@ public class MongoTemplateProjectionLiveTest { final Query query = new Query(); query.fields() - .exclude("_id"); + .exclude("_id"); mongoTemplate.find(query, User.class) - .forEach(user -> { - assertNull(user.getId()); - assertNotNull(user.getAge()); - }); + .forEach(user -> { + assertNull(user.getId()); + assertNotNull(user.getAge()); + }); } diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index 76162c6096..b7ce0cafae 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -1,11 +1,5 @@ package org.baeldung.mongotemplate; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.hamcrest.Matchers.nullValue; - -import java.util.List; - import org.baeldung.config.MongoConfig; import org.baeldung.model.EmailAddress; import org.baeldung.model.User; @@ -26,6 +20,12 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class MongoTemplateQueryLiveTest { diff --git a/spring-hibernate5/pom.xml b/spring-hibernate5/pom.xml index e3309ff10b..dac43c4dd3 100644 --- a/spring-hibernate5/pom.xml +++ b/spring-hibernate5/pom.xml @@ -120,6 +120,12 @@ hsqldb ${hsqldb.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + com.h2database @@ -167,7 +173,7 @@ - 4.3.5.RELEASE + 4.3.10.RELEASE 1.10.6.RELEASE @@ -177,7 +183,8 @@ 5.2.10.Final - 8.5.15 + 8.0.7-dmr + 9.0.0.M26 1.1 2.3.4 1.4.195 diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java new file mode 100644 index 0000000000..f1ad30b090 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java @@ -0,0 +1,86 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinTable; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Employee") +public class Employee implements Serializable { + @Id + @Column(name = "employee_id") + @GeneratedValue + private Long employeeId; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @ManyToMany(cascade = { CascadeType.ALL }) + @JoinTable( + name = "Employee_Project", + joinColumns = { @JoinColumn(name = "employee_id") }, + inverseJoinColumns = { @JoinColumn(name = "project_id") } + ) + Set projects = new HashSet(); + + + public Employee() { + super(); + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Employee(String firstName, String lastName, Set projects) { + this.firstName = firstName; + this.lastName = lastName; + this.projects = projects; + } + + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + 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 Set getProjects() { + return projects; + } + + public void setProjects(Set projects) { + this.projects = projects; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java new file mode 100644 index 0000000000..d6c049f33e --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Project") +public class Project implements Serializable { + + @Id + @Column(name = "project_id") + @GeneratedValue + private Long projectId; + + @Column(name = "title") + private String title; + + @ManyToMany(mappedBy = "projects") + private Set employees = new HashSet(); + + public Project() { + super(); + } + + public Project(String title) { + this.title = title; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Set getEmployees() { + return employees; + } + + public void setEmployees(Set employees) { + this.employees = employees; + } + + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java new file mode 100644 index 0000000000..5f489dd027 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.manytomany.util; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + Configuration configuration = new Configuration(); + configuration.addAnnotatedClass(Employee.class); + configuration.addAnnotatedClass(Project.class); + configuration.configure("manytomany.cfg.xml"); + System.out.println("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + System.out.println("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + + return sessionFactory; + } catch (Throwable ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + ex.printStackTrace(); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); + return sessionFactory; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java new file mode 100644 index 0000000000..6f359054b6 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java @@ -0,0 +1,70 @@ +package com.baeldung.manytomany.spring; + +import java.util.Properties; +import javax.sql.DataSource; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + + + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-mysql.properties" }) +@ComponentScan({ "com.baeldung.hibernate.manytomany" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + //hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", "true"); + + return hibernateProperties; + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java new file mode 100644 index 0000000000..d619807b64 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IEmployeeDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java new file mode 100644 index 0000000000..4a55714f8d --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java @@ -0,0 +1,8 @@ +package com.baeldung.persistence.manytomany.dao; + +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.IOperations; + +public interface IProjectDao extends IOperations{ + +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java new file mode 100644 index 0000000000..b062c00ff9 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java @@ -0,0 +1,16 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IEmployeeDao; + +@Repository +public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { + + public EmployeeDao() { + super(); + + setClazz(Employee.class); + } +} diff --git a/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java new file mode 100644 index 0000000000..772026fbc1 --- /dev/null +++ b/spring-hibernate5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java @@ -0,0 +1,17 @@ +package com.baeldung.persistence.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.persistence.dao.common.AbstractHibernateDao; +import com.baeldung.persistence.manytomany.dao.IProjectDao; + + +@Repository +public class ProjectDao extends AbstractHibernateDao implements IProjectDao { + + public ProjectDao() { + super(); + + setClazz(Project.class); + } +} diff --git a/spring-hibernate5/src/main/resources/manytomany.cfg.xml b/spring-hibernate5/src/main/resources/manytomany.cfg.xml new file mode 100644 index 0000000000..8a10fc1580 --- /dev/null +++ b/spring-hibernate5/src/main/resources/manytomany.cfg.xml @@ -0,0 +1,27 @@ + + + + + + com.mysql.jdbc.Driver + + + buddhinisam123 + + + jdbc:mysql://localhost:3306/spring_hibernate_many_to_many + + + root + + + org.hibernate.dialect.MySQLDialect + + + thread + + true + + diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java new file mode 100644 index 0000000000..61d821e85e --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.manytomany; + + +import java.util.HashSet; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +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.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; +import com.baeldung.manytomany.spring.PersistenceConfig; + + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + + @Before + public final void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @After + public final void after() { + session.getTransaction().commit(); + session.close(); + } + + @Test + public final void whenEntitiesAreCreated_thenNoExceptions() { + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); + } + +} diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java new file mode 100644 index 0000000000..9a536a0f80 --- /dev/null +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.hibernate.manytomany; + +import static org.junit.Assert.assertNotNull; +import static junit.framework.TestCase.assertEquals; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.manytomany.util.HibernateUtil; +import com.baeldung.hibernate.manytomany.model.Employee; +import com.baeldung.hibernate.manytomany.model.Project; + +public class HibernateManyToManyAnnotationMainIntegrationTest { + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreatesMtoMrelationship() { + String[] employeeData = { "Peter Oven", "Allan Norman" }; + String[] projectData = { "IT Project", "Networking Project" }; + Set projects = new HashSet(); + + for (String proj : projectData) { + projects.add(new Project(proj)); + } + + for (String emp : employeeData) { + Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); + assertEquals(0, employee.getProjects().size()); + employee.setProjects(projects); + session.persist(employee); + assertNotNull(employee); + } + } + + @Test + public void givenSession_whenRead_thenReturnsMtoMdata() { + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + for(Employee employee : employeeList) { + assertNotNull(employee.getProjects()); + } + } + + @After + public void tearDown() { + session.getTransaction() + .commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} diff --git a/spring-jpa/pom.xml b/spring-jpa/pom.xml index 1a1e6b3152..6a67d44b48 100644 --- a/spring-jpa/pom.xml +++ b/spring-jpa/pom.xml @@ -102,6 +102,7 @@ javax.servlet servlet-api + provided ${javax.servlet.servlet-api.version} diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 16d4879f10..05baf8c66d 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung @@ -97,6 +97,18 @@ test + + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java new file mode 100644 index 0000000000..726fa53b02 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java @@ -0,0 +1,55 @@ +package com.baeldung.ldap.data.repository; + +import javax.naming.Name; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +@Entry(base = "ou=users", objectClasses = { "person", "inetOrgPerson", "top" }) +public class User { + + @Id + private Name id; + + private @Attribute(name = "cn") String username; + private @Attribute(name = "sn") String password; + + public User() { + } + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + public Name getId() { + return id; + } + + public void setId(Name id) { + this.id = id; + } + + 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; + } + + @Override + public String toString() { + return username; + } + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java new file mode 100644 index 0000000000..12dc0f7f14 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.ldap.data.repository; + +import java.util.List; + +import org.springframework.data.ldap.repository.LdapRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends LdapRepository { + + User findByUsername(String username); + + User findByUsernameAndPassword(String username, String password); + + List findByUsernameLikeIgnoreCase(String username); + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java new file mode 100644 index 0000000000..1b04edb35b --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -0,0 +1,87 @@ +package com.baeldung.ldap.data.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapNameBuilder; + +import javax.naming.Name; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.List; + +public class LdapClient { + + @Autowired + private Environment env; + + @Autowired + private ContextSource contextSource; + + @Autowired + private LdapTemplate ldapTemplate; + + public void authenticate(final String username, final String password) { + contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password); + } + + public List search(final String username) { + return ldapTemplate.search( + "ou=users", + "cn=" + username, + (AttributesMapper) attrs -> (String) attrs + .get("cn") + .get()); + } + + public void create(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextAdapter context = new DirContextAdapter(dn); + + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.bind(context); + } + + public void modify(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextOperations context = ldapTemplate.lookupContext(dn); + + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.modifyAttributes(context); + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64 + .getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java new file mode 100644 index 0000000000..54954e3c9d --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -0,0 +1,63 @@ +package com.baeldung.ldap.data.service; + +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.stereotype.Service; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public Boolean authenticate(final String username, final String password) { + User user = userRepository.findByUsernameAndPassword(username, password); + return user != null; + } + + public List search(final String username) { + List userList = userRepository.findByUsernameLikeIgnoreCase(username); + if (userList == null) { + return Collections.emptyList(); + } + + return userList.stream() + .map(User::getUsername) + .collect(Collectors.toList()); + } + + public void create(final String username, final String password) { + User newUser = new User(username,digestSHA(password)); + newUser.setId(LdapUtils.emptyLdapName()); + userRepository.save(newUser); + + } + + public void modify(final String username, final String password) { + User user = userRepository.findByUsername(username); + user.setPassword(password); + userRepository.save(user); + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64.getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 8572e5d1be..fb3000b2bd 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -7,15 +8,15 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) @Profile("default") +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index ec0dc2469a..32b78577ee 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -7,13 +7,13 @@ - - + + - + - + \ No newline at end of file diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java index b65588dc38..f5b74d64c6 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.ldap.client; -import java.util.List; - +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; @@ -13,11 +12,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapClientLiveTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java new file mode 100644 index 0000000000..9f38af9263 --- /dev/null +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -0,0 +1,67 @@ +package com.baeldung.ldap.client; + +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("testlive") +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class LdapDataRepositoryTest { + + private static final String USER2 = "TEST02"; + private static final String USER3 = "TEST03"; + private static final String USER4 = "TEST04"; + + private static final String USER2_PWD = "TEST02"; + private static final String USER3_PWD = "TEST03"; + private static final String USER4_PWD = "TEST04"; + + private static final String SEARCH_STRING = "TEST*"; + + @Autowired + private UserService userService; + + @Test + public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { + Boolean isValid = userService.authenticate(USER3, USER3_PWD); + assertEquals(true, isValid); + } + + @Test + public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { + Boolean isValid = userService.authenticate(USER3, USER2_PWD); + assertEquals(false, isValid); + } + + @Test + public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { + List userList = userService.search(SEARCH_STRING); + assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); + } + + @Test + public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { + userService.create(USER4, USER4_PWD); + userService.authenticate(USER4, USER4_PWD); + } + + @Test + public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { + userService.modify(USER2, USER3_PWD); + userService.authenticate(USER2, USER3_PWD); + } + +} diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index e2968e977c..c6293982da 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -8,15 +9,15 @@ import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:test_application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired diff --git a/spring-mustache/.gitignore b/spring-mustache/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-mustache/.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-mustache/pom.xml b/spring-mustache/pom.xml new file mode 100644 index 0000000000..45fee6b10e --- /dev/null +++ b/spring-mustache/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung + spring-mustache + 0.0.1-SNAPSHOT + jar + + spring-mustache + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-mustache + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.webjars + bootstrap + 3.3.7 + + + org.fluttercode.datafactory + datafactory + 0.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java new file mode 100644 index 0000000000..addd1fa088 --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -0,0 +1,34 @@ +package com.baeldung.springmustache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; + +import com.samskivert.mustache.Mustache; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.baeldung"}) +public class SpringMustacheApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMustacheApplication.class, args); + } + + @Bean + public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { + + MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); + collector.setEnvironment(environment); + + Mustache.Compiler compiler = Mustache.compiler() + .defaultValue("Some Default Value") + .withLoader(templateLoader) + .withCollector(collector); + return compiler; + + } +} + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java new file mode 100644 index 0000000000..b24625e7d5 --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -0,0 +1,48 @@ +package com.baeldung.springmustache.controller; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.IntStream; + +import org.fluttercode.datafactory.impl.DataFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.springmustache.model.Article; + +@Controller +public class ArticleController { + + @RequestMapping("/article") + public ModelAndView displayArticle(Map model) { + + List
articles = new LinkedList<>(); + IntStream.range(0, 10) + .forEach(count -> { + articles.add(generateArticle("Article Title " + count)); + }); + + Map modelMap = new HashMap<>(); + modelMap.put("articles", articles); + + return new ModelAndView("index", modelMap); + } + + private Article generateArticle(String title) { + Article article = new Article(); + DataFactory factory = new DataFactory(); + article.setTitle(title); + article.setBody( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); + article.setPublishDate(factory.getBirthDate().toString()); + article.setAuthor(factory.getName()); + return article; + } +} + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java new file mode 100644 index 0000000000..78b08f877f --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java @@ -0,0 +1,41 @@ +package com.baeldung.springmustache.model; + +public class Article { + private String title; + private String body; + private String author; + private String publishDate; + + 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; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getPublishDate() { + return publishDate; + } + + public void setPublishDate(String publishDate) { + this.publishDate = publishDate; + } + +} diff --git a/spring-mustache/src/main/resources/application.properties b/spring-mustache/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mustache/src/main/resources/templates/error/error.html b/spring-mustache/src/main/resources/templates/error/error.html new file mode 100644 index 0000000000..fa29db41c4 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/error/error.html @@ -0,0 +1,9 @@ + + + + + + Something went wrong: {{status}} {{error}} + + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/index.html b/spring-mustache/src/main/resources/templates/index.html new file mode 100644 index 0000000000..bda60f9d8f --- /dev/null +++ b/spring-mustache/src/main/resources/templates/index.html @@ -0,0 +1,9 @@ +{{>layout/header}} + +
{{>layout/article}}
+ + + + +{{>layout/footer}} diff --git a/spring-mustache/src/main/resources/templates/layout/article.html b/spring-mustache/src/main/resources/templates/layout/article.html new file mode 100644 index 0000000000..9d573580d3 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/article.html @@ -0,0 +1,8 @@ +
+ {{#articles}} +

{{title}}

+

{{publishDate}}

+

{{author}}

+

{{body}}

+ {{/articles}} +
\ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/footer.html b/spring-mustache/src/main/resources/templates/layout/footer.html new file mode 100644 index 0000000000..04f34cac54 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/footer.html @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/header.html b/spring-mustache/src/main/resources/templates/layout/header.html new file mode 100644 index 0000000000..d203ef800b --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/header.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java new file mode 100644 index 0000000000..9138dfe92b --- /dev/null +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java @@ -0,0 +1,30 @@ +package com.baeldung.springmustache; + +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringMustacheApplicationTests { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void givenIndexPageWhenContainsArticleThenTrue() { + + ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); + + Assert.assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); + Assert.assertTrue(entity.getBody().contains("Article Title 0")); + } + +} diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index c40abdb4bf..9228054878 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -21,16 +21,17 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-mail - + - - org.apache.tomcat.embed - tomcat-embed-jasper - javax.servlet jstl diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java index f146ee1d04..bc5d6b3151 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java @@ -2,10 +2,11 @@ package com.baeldung.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 504cfcdcc7..d42efa7ff6 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -23,3 +23,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Uploading and Displaying Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) +- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index eb8e1455a7..b939f0496d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -5,7 +5,6 @@ spring-mvc-java 0.1-SNAPSHOT spring-mvc-java - war com.baeldung diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml new file mode 100644 index 0000000000..264cf49817 --- /dev/null +++ b/spring-mvc-kotlin/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + spring-mvc-kotlin + 0.1-SNAPSHOT + + spring-mvc-kotlin + + war + + + + org.jetbrains.kotlin + kotlin-stdlib-jre8 + 1.1.4 + + + + org.springframework + spring-web + 4.3.10.RELEASE + + + org.springframework + spring-webmvc + 4.3.10.RELEASE + + + org.thymeleaf + thymeleaf + 3.0.7.RELEASE + + + + org.thymeleaf + thymeleaf-spring4 + 3.0.7.RELEASE + + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + kotlin-maven-plugin + org.jetbrains.kotlin + 1.1.4 + + + + compile + compile + + compile + + + + + test-compile + test-compile + + test-compile + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt new file mode 100644 index 0000000000..ec1c4e9511 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt @@ -0,0 +1,60 @@ +package com.baeldung.kotlin.mvc + +import org.springframework.context.ApplicationContext +import org.springframework.context.ApplicationContextAware +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.servlet.config.annotation.EnableWebMvc +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter +import org.thymeleaf.spring4.SpringTemplateEngine +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver +import org.thymeleaf.spring4.view.ThymeleafViewResolver +import org.thymeleaf.templatemode.TemplateMode + + + + + +@EnableWebMvc +@Configuration +open class ApplicationWebConfig: WebMvcConfigurerAdapter(), ApplicationContextAware { + + private var applicationContext: ApplicationContext? = null + + override fun setApplicationContext(applicationContext: ApplicationContext?) { + this.applicationContext = applicationContext + } + + override fun addViewControllers(registry: ViewControllerRegistry?) { + super.addViewControllers(registry) + + registry!!.addViewController("/welcome.html") + } + + @Bean + open fun templateResolver(): SpringResourceTemplateResolver { + val templateResolver = SpringResourceTemplateResolver() + templateResolver.prefix = "/WEB-INF/view/" + templateResolver.suffix = ".html" + templateResolver.templateMode = TemplateMode.HTML + templateResolver.setApplicationContext(this.applicationContext); + return templateResolver + } + + @Bean + open fun templateEngine(): SpringTemplateEngine { + val templateEngine = SpringTemplateEngine() + templateEngine.setTemplateResolver(templateResolver()) + return templateEngine + } + + @Bean + open fun viewResolver(): ThymeleafViewResolver { + val viewResolver = ThymeleafViewResolver() + viewResolver.templateEngine = templateEngine() + viewResolver.order = 1 + return viewResolver + } + +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt new file mode 100644 index 0000000000..a4d1614271 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin.mvc + +import com.baeldung.kotlin.mvc.ApplicationWebConfig +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer + +class ApplicationWebInitializer: AbstractAnnotationConfigDispatcherServletInitializer() { + + override fun getRootConfigClasses(): Array>? { + return null + } + + override fun getServletMappings(): Array { + return arrayOf("/") + } + + override fun getServletConfigClasses(): Array> { + return arrayOf(ApplicationWebConfig::class.java) + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 0000000000..c7f110ea94 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..3f68f128bc --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,7 @@ + + Welcome + + +

This is the body of the welcome view

+ + \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 0000000000..cbee6a1b11 --- /dev/null +++ b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + Spring Kotlin MVC Application + + + spring-web-mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + contextConfigLocation + /WEB-INF/spring-web-config.xml + + + + + spring-web-mvc + / + + + \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 0cfb3e6dee..8a51c04113 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -15,14 +15,19 @@
- 4.3.4.RELEASE - 2.6 + 4.3.10.RELEASE + 3.1.0 1.2 2.3.1 3.1.0 - 5.3.3.Final + 5.4.1.Final enter-location-of-server 1.3.2 + 1.8 + 3.0.7.RELEASE + 2.4.12 + 2.3.23 + 1.2.5 @@ -79,6 +84,45 @@ commons-fileupload ${fileupload.version}
+ + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + org.springframework + spring-context-support + ${springframework.version} + + + + + org.codehaus.groovy + groovy-templates + ${groovy.version} + + + + + de.neuland-bfi + spring-jade4j + ${jade.version} + + @@ -94,6 +138,14 @@ ${deploy-path} + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + springMvcSimple diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 9ace968bbe..b62ccae465 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.springmvcforms") +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) class ApplicationConfiguration extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java new file mode 100644 index 0000000000..e43238f8a6 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class FreemarkerConfiguration { + @Bean + public FreeMarkerConfigurer freemarkerConfig() { + FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); + freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/"); + return freeMarkerConfigurer; + } + + @Bean + public FreeMarkerViewResolver freemarkerViewResolver() { + FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); + resolver.setCache(true); + resolver.setPrefix(""); + resolver.setSuffix(".ftl"); + return resolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java new file mode 100644 index 0000000000..b7a9256fc0 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; +import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class GroovyConfiguration { + + @Bean + public GroovyMarkupConfigurer groovyMarkupConfigurer() { + GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); + configurer.setResourceLoaderPath("/WEB-INF/views/"); + return configurer; + } + + @Bean + public GroovyMarkupViewResolver thymeleafViewResolver() { + GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver(); + viewResolver.setSuffix(".tpl"); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java new file mode 100644 index 0000000000..10345bac58 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import de.neuland.jade4j.JadeConfiguration; +import de.neuland.jade4j.spring.template.SpringTemplateLoader; +import de.neuland.jade4j.spring.view.JadeViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class JadeTemplateConfiguration { + @Bean + public SpringTemplateLoader templateLoader() { + SpringTemplateLoader templateLoader = new SpringTemplateLoader(); + templateLoader.setBasePath("/WEB-INF/views/"); + templateLoader.setSuffix(".jade"); + return templateLoader; + } + + @Bean + public JadeConfiguration jadeConfiguration() { + JadeConfiguration configuration = new JadeConfiguration(); + configuration.setCaching(false); + configuration.setTemplateLoader(templateLoader()); + return configuration; + } + + @Bean + public ViewResolver viewResolver() { + JadeViewResolver viewResolver = new JadeViewResolver(); + viewResolver.setConfiguration(jadeConfiguration()); + return viewResolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java new file mode 100644 index 0000000000..257dbc718a --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class ThymeleafConfiguration { + @Bean + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(thymeleafTemplateResolver()); + return templateEngine; + } + + @Bean + public SpringResourceTemplateResolver thymeleafTemplateResolver() { + SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + public ThymeleafViewResolver thymeleafViewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index d6bbf5eabd..d57d2c621a 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -15,6 +15,10 @@ public class WebInitializer implements WebApplicationInitializer { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ApplicationConfiguration.class); + //ctx.register(ThymeleafConfiguration.class); + //ctx.register(FreemarkerConfiguration.class); + //ctx.register(GroovyConfiguration.class); + //ctx.register(JadeTemplateConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java new file mode 100644 index 0000000000..b402a376c0 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.domain.User; + +@Controller +public class UserController { + + @GetMapping("/registration") + public String getRegistration(Model model) { + model.addAttribute("user", new User()); + return "registration"; + } + + @GetMapping("/registration-thymeleaf") + public String getRegistrationThymeleaf(Model model) { + model.addAttribute("user", new User()); + return "registration-thymeleaf"; + } + + @GetMapping("/registration-freemarker") + public String getRegistrationFreemarker(Model model) { + model.addAttribute("user", new User()); + return "registration-freemarker"; + } + + @GetMapping("/registration-groovy") + public String getRegistrationGroovy(Model model) { + model.addAttribute("user", new User()); + return "registration-groovy"; + } + + @GetMapping("/registration-jade") + public String getRegistrationJade(Model model) { + model.addAttribute("user", new User()); + return "registration-jade"; + } + + @PostMapping("/register") + @ResponseBody + public void register(User user){ + System.out.println(user.getEmail()); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java new file mode 100644 index 0000000000..8016f98d85 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.domain; + +public class User { + private String email; + private String password; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl new file mode 100644 index 0000000000..8dce9a88c9 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl @@ -0,0 +1,15 @@ +<#import "/spring.ftl" as spring/> + + + +User Registration + + +
+ <@spring.bind path="user" /> + Email:<@spring.formInput "user.email"/>
+ Password:<@spring.formPasswordInput "user.password"/>
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl new file mode 100644 index 0000000000..291077fc2e --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl @@ -0,0 +1,18 @@ +yieldUnescaped '' +html(lang:'en') { + head { + meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"') + title('User Registration') + } + body { + form (id:'userForm', action:'register', method:'post') { + label (for:'email', 'Email') + input (name:'email', type:'text', value:user.email?:'') + label (for:'password', 'Password') + input (name:'password', type:'password', value:user.password?:'') + div (class:'form-actions') { + input (type:'submit', value:'Submit') + } + } + } +} \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade new file mode 100644 index 0000000000..44b6293ff0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade @@ -0,0 +1,11 @@ +doctype html +html + head + title User Registration + body + form(action="register" method="post" ) + label(for="email") Emailaaaaaaaa: + input(type="text" name="email") + label(for="password") Password: + input(type="password" name="password") + input(type="submit" value="Submit") \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html new file mode 100644 index 0000000000..c98f3283c0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html @@ -0,0 +1,13 @@ + + + +User Registration + + +
+ Email:
+ Password:
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp new file mode 100644 index 0000000000..7c2d9c73b1 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp @@ -0,0 +1,18 @@ +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +User Registration + + + + Email: + +
+ Password: + +
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b6f1065cad..0000000000 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - spring - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - classpath*:spring-servlet_RequestMappingHandlerAdapter.xml - - 1 - - - spring - / - - \ No newline at end of file diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index 0b751d1fc9..b40f77eb50 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -33,6 +33,7 @@ remoting-hessian-burlap remoting-amqp remoting-jms + spring-remoting-rmi \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/pom.xml b/spring-remoting/spring-remoting-rmi/pom.xml new file mode 100644 index 0000000000..723158775f --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/pom.xml @@ -0,0 +1,19 @@ + + + + spring-remoting + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + pom + + remoting-rmi-server + remoting-rmi-client + + spring-remoting-rmi + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml new file mode 100644 index 0000000000..003976dc7b --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/remoting-rmi-client/pom.xml @@ -0,0 +1,30 @@ + + + + spring-remoting-rmi + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-rmi-client + + + + org.springframework.boot + spring-boot-starter-activemq + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + com.baeldung + api + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java b/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java new file mode 100644 index 0000000000..a568b749f9 --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java @@ -0,0 +1,26 @@ +package com.baeldung.client; + +import com.baeldung.api.Booking; +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.remoting.rmi.RmiProxyFactoryBean; + +@SpringBootApplication public class RmiClient { + + @Bean RmiProxyFactoryBean service() { + RmiProxyFactoryBean rmiProxyFactory = new RmiProxyFactoryBean(); + rmiProxyFactory.setServiceUrl("rmi://localhost:1099/CabBookingService"); + rmiProxyFactory.setServiceInterface(CabBookingService.class); + return rmiProxyFactory; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(RmiClient.class, args).getBean(CabBookingService.class); + Booking bookingOutcome = service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"); + System.out.println(bookingOutcome); + } + +} diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml new file mode 100644 index 0000000000..5ce3f7f949 --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/pom.xml @@ -0,0 +1,40 @@ + + + + spring-remoting-rmi + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-rmi-server + + + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + com.baeldung + api + + + com.baeldung + api + ${project.version} + + + + \ No newline at end of file diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java new file mode 100644 index 0000000000..55ec9c5733 --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java @@ -0,0 +1,16 @@ +package com.baeldung.server; + +import com.baeldung.api.Booking; +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; + +import static java.lang.Math.random; +import static java.util.UUID.randomUUID; + +public class CabBookingServiceImpl implements CabBookingService { + + @Override public Booking bookRide(String pickUpLocation) throws BookingException { + if (random() < 0.3) throw new BookingException("Cab unavailable"); + return new Booking(randomUUID().toString()); + } +} diff --git a/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java new file mode 100644 index 0000000000..7778c65e85 --- /dev/null +++ b/spring-remoting/spring-remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java @@ -0,0 +1,34 @@ +package com.baeldung.server; + +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.remoting.rmi.RmiServiceExporter; + +@SpringBootApplication public class RmiServer { + + @Bean CabBookingService bookingService() { + return new CabBookingServiceImpl(); + } + + @Bean RmiServiceExporter exporter(CabBookingService implementation) { + + // Expose a service via RMI. Remote obect URL is: + // rmi://:/ + // 1099 is the default port + + Class serviceInterface = CabBookingService.class; + RmiServiceExporter exporter = new RmiServiceExporter(); + exporter.setServiceInterface(serviceInterface); + exporter.setService(implementation); + exporter.setServiceName(serviceInterface.getSimpleName()); + exporter.setRegistryPort(1099); + return exporter; + } + + public static void main(String[] args) { + SpringApplication.run(RmiServer.class, args); + } + +} diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index 0912023fb7..f2ac9d0f82 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -28,9 +28,17 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.li import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.util.StringUtils.collectionToDelimitedString; diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index 1af626d03b..c02c0c27f8 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -1,8 +1,6 @@ package com.example; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -14,21 +12,19 @@ import org.springframework.restdocs.RestDocumentation; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) diff --git a/spring-rest/README.md b/spring-rest/README.md index 66c893e45f..2cea315188 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -15,3 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) +- [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) diff --git a/spring-rest/difference-uri-url-rest/pom.xml b/spring-rest/difference-uri-url-rest/pom.xml deleted file mode 100644 index 5ab6e63240..0000000000 --- a/spring-rest/difference-uri-url-rest/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - 4.0.0 - org.baeldung.springboot.rest - difference-uri-url-rest - 0.0.1-SNAPSHOT - war - - - 1.8 - - - - org.springframework.boot - spring-boot-starter-parent - 1.5.2.RELEASE - - - - - - org.springframework.boot - spring-boot-starter-web - compile - - - org.springframework.boot - spring-boot-starter-test - test - - - - \ No newline at end of file diff --git a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/Greeting.java b/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/Greeting.java deleted file mode 100644 index cc166587df..0000000000 --- a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/Greeting.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.springboot.rest; - -public class Greeting { - private static final long serialVersionUID = 1L; - - private Integer id = null; - private String content = null; - - public Greeting(Integer id) { - this.id = id; - this.content = "Hello World"; - } - - public Integer getId() { - return id; - } - - public String getContent() { - return content; - } -} \ No newline at end of file diff --git a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/GreetingController.java b/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/GreetingController.java deleted file mode 100644 index 3fca9a1a76..0000000000 --- a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/GreetingController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.springboot.rest; - -import java.util.concurrent.atomic.AtomicLong; - -import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -@RestController("/") -@Component -public class GreetingController { - - private final AtomicLong counter = new AtomicLong(); - - @RequestMapping(value = "/greetings", method = RequestMethod.GET) - public Greeting greeting() { - - return new Greeting(new Integer((int) counter.incrementAndGet())); - } -} \ No newline at end of file diff --git a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/SpringBootWebApplication.java b/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/SpringBootWebApplication.java deleted file mode 100644 index 08d4c2c65e..0000000000 --- a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/SpringBootWebApplication.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.springboot.rest; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@EnableAutoConfiguration -@SpringBootApplication -public class SpringBootWebApplication extends SpringBootServletInitializer { - - // method for explicit deployment on Application Server - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(SpringBootWebApplication.class); - } - - // run it as standalone JAVA application - public static void main(String[] args) throws Exception { - SpringApplication.run(SpringBootWebApplication.class, args); - } - - //Samples - // http://localhost:8080/greetings - // http://localhost:8989/difference-uri-url-rest/greetings -} \ No newline at end of file diff --git a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/ApplicationClient.java b/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/ApplicationClient.java deleted file mode 100644 index 2d92c890c5..0000000000 --- a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/ApplicationClient.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.springboot.rest.client; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.client.RestTemplate; - -public class ApplicationClient { - //private static final Logger log = LoggerFactory.getLogger(ApplicationClient.class); - final static String URI_STRING = "http://localhost:8080/difference-uri-url-rest/greetings"; - - - public ApplicationClient() { - super(); - } - - public Greeting init() { - RestTemplate restTemplate = new RestTemplate(); - Greeting greeting = restTemplate.getForObject(ApplicationClient.URI_STRING, Greeting.class); - //log.info(greeting.toString()); - return greeting; - } - public static void main(String args[]) { - Greeting greeting = new ApplicationClient().init(); - System.out.println(greeting.toString()); - } - -} diff --git a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/Greeting.java b/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/Greeting.java deleted file mode 100644 index 7d1119d155..0000000000 --- a/spring-rest/difference-uri-url-rest/src/main/java/com/baeldung/springboot/rest/client/Greeting.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.springboot.rest.client; - -import java.io.Serializable; - -public class Greeting implements Serializable { - private static final long serialVersionUID = 1L; - - private Integer id = null; - private String content = null; - - /** Default constructor is mandatory for client */ - public Greeting() { - super(); - } - - public Greeting(Integer id) { - this.id = id; - this.content = "Hello World"; - } - - public Integer getId() { - return id; - } - - public String getContent() { - return content; - } - - @Override - public String toString() { - return "Id: " + getId().toString() + " Content: " + getContent(); - } -} \ No newline at end of file diff --git a/spring-rest/difference-uri-url-rest/src/test/java/com/baeldung/springboot/rest/test/DifferenceURIURLRESTTest.java b/spring-rest/difference-uri-url-rest/src/test/java/com/baeldung/springboot/rest/test/DifferenceURIURLRESTTest.java deleted file mode 100644 index 4397f8e088..0000000000 --- a/spring-rest/difference-uri-url-rest/src/test/java/com/baeldung/springboot/rest/test/DifferenceURIURLRESTTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.springboot.rest.test; - -import static org.junit.Assert.assertNotNull; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.web.client.RestTemplate; - -import com.baeldung.springboot.rest.client.Greeting; - -public class DifferenceURIURLRESTTest { - final static String URI_STRING = "http://localhost:8080/difference-uri-url-rest/greetings"; - static RestTemplate restTemplate; - Greeting greeting; - - @BeforeClass - public static void setupTest() { - restTemplate = new RestTemplate(); - } - - @Test - public void givenRestTenplate_whenIsNotNull_thenSuccess() { - assertNotNull("Rest Template not null", restTemplate); - } - - @Test - public void givenWiredConstructorParam_whenIsNotNull_thenSuccess() { - greeting = restTemplate.getForObject(URI_STRING, Greeting.class); - assertNotNull("Greeting class is not null", greeting); - } - -} diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index c12028149d..6065d7e529 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,321 +1,329 @@ - 4.0.0 - com.baeldung - spring-rest - 0.1-SNAPSHOT - spring-rest - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-rest + 0.1-SNAPSHOT + spring-rest + war - - parent-boot-4 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-4 - + + parent-boot-4 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-4 + - + - + - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-test - + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-test + - + - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - org.springframework - spring-oxm - + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - javax.servlet - javax.servlet-api - provided - + + javax.servlet + javax.servlet-api + provided + - - javax.servlet - jstl - runtime - + + javax.servlet + jstl + runtime + - + - - com.fasterxml.jackson.core - jackson-databind - + + com.fasterxml.jackson.core + jackson-databind + - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + com.thoughtworks.xstream + xstream + ${xstream.version} + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - - org.mockito - mockito-core - test - + + org.mockito + mockito-core + test + - - org.springframework - spring-test - + + org.springframework + spring-test + - - - com.google.protobuf - protobuf-java - ${protobuf-java.version} - - - com.googlecode.protobuf-java-format - protobuf-java-format - ${protobuf-java-format.version} - + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + - - com.esotericsoftware - kryo - ${kryo.version} - + + com.esotericsoftware + kryo + ${kryo.version} + - - com.jayway.jsonpath - json-path - + + com.jayway.jsonpath + json-path + - - - spring-rest - - - src/main/resources - true - - + + + commons-io + commons-io + 2.4 + - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - org.apache.maven.plugins - maven-war-plugin - + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8082 - - - - + + spring-rest + + + src/main/resources + true + + - + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + org.apache.maven.plugins + maven-war-plugin + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + - + - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - - - - - + - -
- + - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + + - - - + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - 1.3.2 - 4.0.0 - 1.4 - 3.1.0 - 3.5 - 1.4.9 + + + - - 20.0 + - - 1.6.0 - 3.0.4 + + 1.3.2 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 - - 3.4.1 + + 20.0 - 2.2.0 - + + 1.6.0 + 3.0.4 + + + 3.4.1 + + 2.2.0 + diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java b/spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java index 6f34bdb9ae..ab233a8b60 100644 --- a/spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java +++ b/spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java @@ -17,7 +17,7 @@ public class DataProducerController { return "Hello world"; } - @GetMapping(value = "/get-image") + @GetMapping("/get-image") public @ResponseBody byte[] getImage() throws IOException { final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg"); return IOUtils.toByteArray(in); diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java new file mode 100644 index 0000000000..41042008ef --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.web.log.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung.web.log") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java new file mode 100644 index 0000000000..b154f3665f --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java @@ -0,0 +1,44 @@ +package com.baeldung.web.log.app; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import com.baeldung.web.log.util.RequestLoggingUtil; + +@Component +public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { + + private final static Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String postData; + HttpServletRequest requestCacheWrapperObject = null; + try { + // Uncomment to produce the stream closed issue + // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); + + // To overcome request stream closed issue + requestCacheWrapperObject = new ContentCachingRequestWrapper(request); + requestCacheWrapperObject.getParameterMap(); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); + LOGGER.info("REQUEST DATA: " + postData); + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + LOGGER.info("RESPONSE: " + response.getStatus()); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java new file mode 100644 index 0000000000..bc9ad1cf84 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CommonsRequestLoggingFilter; + +@Configuration +public class RequestLoggingFilterConfig { + + @Bean + public CommonsRequestLoggingFilter logFilter() { + CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); + filter.setIncludeQueryString(true); + filter.setIncludePayload(true); + filter.setMaxPayloadLength(10000); + filter.setIncludeHeaders(false); + filter.setAfterMessagePrefix("REQUEST DATA : "); + return filter; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java new file mode 100644 index 0000000000..f433b4f3c7 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.web.log.config; + +import com.baeldung.web.log.app.TaxiFareRequestInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { + + @Autowired + private TaxiFareRequestInterceptor taxiFareRequestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java new file mode 100644 index 0000000000..7de88d44a8 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java @@ -0,0 +1,42 @@ +package com.baeldung.web.log.controller; + +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.web.log.data.RateCard; +import com.baeldung.web.log.data.TaxiRide; +import com.baeldung.web.log.service.TaxiFareCalculatorService; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class TaxiFareController { + + @Autowired + private TaxiFareCalculatorService taxiFareCalculatorService; + + private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class); + + @GetMapping("/taxifare/get/") + public RateCard getTaxiFare() { + LOGGER.debug("getTaxiFare() - START"); + return new RateCard(); + } + + @PostMapping("/taxifare/calculate/") + public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { + LOGGER.debug("calculateTaxiFare() - START"); + String totalFare = taxiFareCalculatorService.calculateFare(taxiRide); + LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare); + LOGGER.debug("calculateTaxiFare() - END"); + return totalFare; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java new file mode 100644 index 0000000000..c7955b561b --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java @@ -0,0 +1,31 @@ +package com.baeldung.web.log.data; + +public class RateCard { + + private String nightSurcharge; + private String ratePerMile; + + public RateCard() { + nightSurcharge = "Extra $ 100"; + ratePerMile = "$ 10 Per Mile"; + } + + + public String getNightSurcharge() { + return nightSurcharge; + } + + public void setNightSurcharge(String nightSurcharge) { + this.nightSurcharge = nightSurcharge; + } + + public String getRatePerMile() { + return ratePerMile; + } + + public void setRatePerMile(String ratePerMile) { + this.ratePerMile = ratePerMile; + } + + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java new file mode 100644 index 0000000000..2e0f33f02b --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java @@ -0,0 +1,33 @@ +package com.baeldung.web.log.data; + +public class TaxiRide { + + private Boolean isNightSurcharge; + private Long distanceInMile; + + public TaxiRide() { + } + + public TaxiRide(Boolean isNightSurcharge, Long distanceInMile) { + this.isNightSurcharge = isNightSurcharge; + this.distanceInMile = distanceInMile; + } + + + public Boolean getIsNightSurcharge() { + return isNightSurcharge; + } + + public void setIsNightSurcharge(Boolean isNightSurcharge) { + this.isNightSurcharge = isNightSurcharge; + } + + public Long getDistanceInMile() { + return distanceInMile; + } + + public void setDistanceInMile(Long distanceInMile) { + this.distanceInMile = distanceInMile; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java new file mode 100644 index 0000000000..1176b31e4c --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java @@ -0,0 +1,14 @@ +package com.baeldung.web.log.service; + +import com.baeldung.web.log.data.TaxiRide; +import org.springframework.stereotype.Service; + +@Service +public class TaxiFareCalculatorService { + + public String calculateFare(TaxiRide taxiRide) { + return String.valueOf((Long) (taxiRide.getIsNightSurcharge() + ? taxiRide.getDistanceInMile() * 10 + 100 + : taxiRide.getDistanceInMile() * 10)); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..c13d35b55c --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.web.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java b/spring-rest/src/main/java/org/baeldung/config/MainApplication.java index e31fdfaaa9..36b021a537 100644 --- a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java +++ b/spring-rest/src/main/java/org/baeldung/config/MainApplication.java @@ -12,5 +12,4 @@ public class MainApplication extends WebMvcConfigurerAdapter { public static void main(final String[] args) { SpringApplication.run(MainApplication.class, args); } - } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index 3661b2c561..f42c3cb283 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -1,15 +1,7 @@ package org.baeldung.config; -import java.text.SimpleDateFormat; -import java.util.List; - import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; -import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -26,30 +18,30 @@ public class WebConfig extends WebMvcConfigurerAdapter { } // + /* + @Override + public void configureMessageConverters(final List> messageConverters) { + final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); + builder.indentOutput(true) + .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); + messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); + // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); - @Override - public void configureMessageConverters(final List> messageConverters) { - final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); - builder.indentOutput(true) - .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); - messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); - // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); + // messageConverters.add(createXmlHttpMessageConverter()); + // messageConverters.add(new MappingJackson2HttpMessageConverter()); - // messageConverters.add(createXmlHttpMessageConverter()); - // messageConverters.add(new MappingJackson2HttpMessageConverter()); + // messageConverters.add(new ProtobufHttpMessageConverter()); + super.configureMessageConverters(messageConverters); + } - // messageConverters.add(new ProtobufHttpMessageConverter()); - super.configureMessageConverters(messageConverters); - } + private HttpMessageConverter createXmlHttpMessageConverter() { + final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - private HttpMessageConverter createXmlHttpMessageConverter() { - final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); - - final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); - xmlConverter.setMarshaller(xstreamMarshaller); - xmlConverter.setUnmarshaller(xstreamMarshaller); - - return xmlConverter; - } + final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); + xmlConverter.setMarshaller(xstreamMarshaller); + xmlConverter.setUnmarshaller(xstreamMarshaller); + return xmlConverter; + } + */ } diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java index 4ed5c21b83..e4eb6d8875 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java @@ -1,11 +1,11 @@ package org.baeldung.repository; -import java.util.Map; - import org.baeldung.web.dto.HeavyResource; import org.baeldung.web.dto.HeavyResourceAddressOnly; -public class HeavyResourceRepository { +import java.util.Map; + +public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { } @@ -21,6 +21,7 @@ public class HeavyResourceRepository { public void save(HeavyResource heavyResource, String id) { } + public void save(HeavyResourceAddressOnly partialUpdate, String id) { } diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java index 061213a3e9..251e0b23e7 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java @@ -32,7 +32,7 @@ public class MyFooController { // API - read - @RequestMapping(method = RequestMethod.GET) + @RequestMapping(method = RequestMethod.GET, produces = { "application/json" }) @ResponseBody public Collection findAll() { return myfoos.values(); diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java index 472c0c8bf5..59868593a3 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java @@ -1,11 +1,15 @@ package org.baeldung.web.controller.redirect; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; @@ -49,4 +53,16 @@ public class RedirectController { model.addAttribute("redirectionAttribute", flashAttribute); return new ModelAndView("redirection", model); } + + @RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST) + public ModelAndView redirectPostToPost(HttpServletRequest request) { + request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); + return new ModelAndView("redirect:/redirectedPostToPost"); + } + + @RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST) + public ModelAndView redirectedPostToPost() { + return new ModelAndView("redirection"); + } + } \ No newline at end of file diff --git a/spring-rest/src/main/resources/logback.xml b/spring-rest/src/main/resources/logback.xml index ec0dc2469a..3496a4a03c 100644 --- a/spring-rest/src/main/resources/logback.xml +++ b/spring-rest/src/main/resources/logback.xml @@ -6,6 +6,10 @@ + + + + diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index d133bcea22..7e7d820836 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -19,12 +19,11 @@ --> - + + - diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index a439de8a05..1b8b767ae3 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -19,10 +19,10 @@ org.baeldung.config - + api diff --git a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java new file mode 100644 index 0000000000..398e3c04e9 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java @@ -0,0 +1,33 @@ +package com.baeldung.web.log.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.baeldung.web.log.data.TaxiRide; + +public class TestTaxiFareController { + + private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/"; + + @Test + public void givenRequest_whenFetchTaxiFareRateCard_thanOK() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTaxiRide_whenCalculatedFare_thanStatus200() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + TaxiRide taxiRide = new TaxiRide(true, 10l); + String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class); + + assertThat(fare, equalTo("200")); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index 2d12262e85..7bcaab6a07 100644 --- a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -42,7 +42,7 @@ public class RestTemplateBasicLiveTest { @Before public void beforeTest() { restTemplate = new RestTemplate(); - restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); + // restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); } // GET @@ -78,7 +78,6 @@ public class RestTemplateBasicLiveTest { @Test public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); - assertTrue(httpHeaders.getContentType() .includes(MediaType.APPLICATION_JSON)); } @@ -248,4 +247,5 @@ public class RestTemplateBasicLiveTest { clientHttpRequestFactory.setConnectTimeout(timeout * 1000); return clientHttpRequestFactory; } + } diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 06c295fcd7..37d8c34c5a 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -3,6 +3,7 @@ package org.baeldung.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -10,7 +11,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories("org.baeldung.repository") @ComponentScan("org.baeldung") @EntityScan("org.baeldung.entity") -public class App { +public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index f2b6b766eb..e6452ea70b 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -57,7 +57,7 @@ - 1.5.7 + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 4bcb255046..5936aa30ef 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -1,8 +1,9 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,17 +12,22 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * class to run up a Jetty Server (on http://localhost:8080) * */ -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class SampleLDAPApplication extends WebMvcConfigurerAdapter { +@SpringBootApplication +public class SampleLDAPApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SampleLDAPApplication.class, args); } - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login").setViewName("login"); + @Bean + public WebMvcConfigurerAdapter adapter() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } + }; } } \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java index 843f5f4dcd..64698072bc 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAccessDeniedHandler.java @@ -25,7 +25,7 @@ public class CustomAccessDeniedHandler implements AccessDeniedHandler { if (auth != null) { LOG.warn("User: " + auth.getName() + " attempted to access the protected URL: " + request.getRequestURI()); } - + response.sendRedirect(request.getContextPath() + "/accessDenied"); } diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java index b68e7eab50..1472a1f89c 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java @@ -1,17 +1,14 @@ package org.baeldung.spring; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -@Configuration +//@Configuration //@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" }) -@EnableWebSecurity -@Profile("!https") +//@EnableWebSecurity +//@Profile("!https") public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { public RedirectionSecurityConfig() { @@ -20,25 +17,23 @@ public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1") - .password("user1Pass") - .roles("USER"); + auth.inMemoryAuthentication() + .withUser("user1") + .password("user1Pass") + .roles("USER"); } @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/login*") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin() - .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); - //.successHandler(new RefererAuthenticationSuccessHandler()) + http.authorizeRequests() + .antMatchers("/login*") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); + // .successHandler(new RefererAuthenticationSuccessHandler()) } } diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 7331d7bb18..d9a43d48d0 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -65,9 +65,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } - + @Bean - public AccessDeniedHandler accessDeniedHandler(){ + public AccessDeniedHandler accessDeniedHandler() { return new CustomAccessDeniedHandler(); } diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java index 1d7fae8b60..2b7a8ce5b9 100644 --- a/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -29,65 +29,58 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WebAppConfiguration public class RedirectionSecurityIntegrationTest { - @Autowired private WebApplicationContext context; + @Autowired + private WebApplicationContext context; - @Autowired private UserDetailsService userDetailsService; + @Autowired + private UserDetailsService userDetailsService; private MockMvc mvc; private UserDetails userDetails; @Before public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .apply(springSecurity()) - .build(); + mvc = MockMvcBuilders.webAppContextSetup(context) + .apply(springSecurity()) + .build(); userDetails = userDetailsService.loadUserByUsername("user1"); } @Test public void givenSecuredResource_whenAccessUnauthenticated_thenRequiresAuthentication() throws Exception { - mvc - .perform(get("/secured")) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/login")); + mvc.perform(get("/secured")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/login")); } @Test public void givenCredentials_whenAccessSecuredResource_thenSuccess() throws Exception { - mvc - .perform(get("/secured").with(user(userDetails))) - .andExpect(status().isOk()); + mvc.perform(get("/secured").with(user(userDetails))) + .andExpect(status().isOk()); } @Test public void givenAccessSecuredResource_whenAuthenticated_thenRedirectedBack() throws Exception { MockHttpServletRequestBuilder securedResourceAccess = get("/secured"); - MvcResult unauthenticatedResult = mvc - .perform(securedResourceAccess) - .andExpect(status().is3xxRedirection()) - .andReturn(); + MvcResult unauthenticatedResult = mvc.perform(securedResourceAccess) + .andExpect(status().is3xxRedirection()) + .andReturn(); - MockHttpSession session = (MockHttpSession) unauthenticatedResult - .getRequest() - .getSession(); - String loginUrl = unauthenticatedResult - .getResponse() - .getRedirectedUrl(); - mvc - .perform(post(loginUrl) - .param("username", userDetails.getUsername()) + MockHttpSession session = (MockHttpSession) unauthenticatedResult.getRequest() + .getSession(); + String loginUrl = unauthenticatedResult.getResponse() + .getRedirectedUrl(); + mvc.perform(post(loginUrl).param("username", userDetails.getUsername()) .param("password", userDetails.getPassword()) .session(session) .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrlPattern("**/secured")) - .andReturn(); + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrlPattern("**/secured")) + .andReturn(); - mvc - .perform(securedResourceAccess.session(session)) - .andExpect(status().isOk()); + mvc.perform(securedResourceAccess.session(session)) + .andExpect(status().isOk()); } diff --git a/spring-security-mvc-socket/README.md b/spring-security-mvc-socket/README.md index 2144765a04..5ae9d4f4cd 100644 --- a/spring-security-mvc-socket/README.md +++ b/spring-security-mvc-socket/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Intro to Security and WebSockets](http://www.baeldung.com/intro-to-security-and-websockets) \ No newline at end of file +- [Intro to Security and WebSockets](http://www.baeldung.com/spring-security-websockets) diff --git a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java index 608e8a6819..ed57088c56 100644 --- a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java +++ b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class SpringOpenidApplication { +public class SpringOpenidApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringOpenidApplication.class, args); diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index c329bd1cb8..77a58a56d8 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -33,12 +33,6 @@ org.springframework spring-core - - - commons-logging - commons-logging - - org.springframework @@ -79,6 +73,12 @@ spring-oxm + + commons-logging + commons-logging + ${commons-logging.version} + + @@ -105,24 +105,11 @@ org.apache.httpcomponents httpcore - ${httpcore.version} - - - commons-logging - commons-logging - - org.apache.httpcomponents httpclient - - - commons-logging - commons-logging - - @@ -213,7 +200,7 @@ 19.0 3.5 - + 1.2 4.4.5 4.5.2 diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java index 2d3ad7b13f..e7456f1667 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java @@ -37,7 +37,7 @@ public abstract class AbstractDiscoverabilityLiveTest ex // Then final String allowHeader = res.getHeader(HttpHeaders.ALLOW); - assertThat(allowHeader, AnyOf. anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); + assertThat(allowHeader, AnyOf.anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); } @Test diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index be9b7cf27e..6e70f979c8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -31,7 +31,7 @@ public abstract class CsrfAbstractIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected MockMvc mvc; + MockMvc mvc; // @@ -40,15 +40,15 @@ public abstract class CsrfAbstractIntegrationTest { mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); } - protected RequestPostProcessor testUser() { + RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } - protected RequestPostProcessor testAdmin() { + RequestPostProcessor testAdmin() { return user("admin").password("adminPass").roles("USER", "ADMIN"); } - protected String createFoo() throws JsonProcessingException { + String createFoo() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index 392e101193..a899d387ab 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -33,10 +33,6 @@ public final class JacksonMarshaller implements IMarshaller { String entityAsJSON = null; try { entityAsJSON = objectMapper.writeValueAsString(resource); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -51,10 +47,6 @@ public final class JacksonMarshaller implements IMarshaller { T entity = null; try { entity = objectMapper.readValue(resourceAsString, clazz); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -76,10 +68,6 @@ public final class JacksonMarshaller implements IMarshaller { } else { entities = objectMapper.readValue(resourcesAsString, List.class); } - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java index 84fb63a321..85ab623e5f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java @@ -10,21 +10,21 @@ public final class IDUtil { // API - public final static String randomPositiveLongAsString() { + public static String randomPositiveLongAsString() { return Long.toString(randomPositiveLong()); } - public final static String randomNegativeLongAsString() { + public static String randomNegativeLongAsString() { return Long.toString(randomNegativeLong()); } - public final static long randomPositiveLong() { + public static long randomPositiveLong() { long id = new Random().nextLong() * 10000; id = (id < 0) ? (-1 * id) : id; return id; } - public final static long randomNegativeLong() { + private static long randomNegativeLong() { long id = new Random().nextLong() * 10000; id = (id > 0) ? (-1 * id) : id; return id; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 7dcaec5a12..44dc860e62 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -27,6 +27,7 @@ public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; + @Autowired MockHttpSession session; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..29f1c91ca3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,10 +1,5 @@ package org.baeldung.web.util; -import java.util.List; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; - public final class HTTPLinkHeaderUtil { private HTTPLinkHeaderUtil() { @@ -13,23 +8,6 @@ public final class HTTPLinkHeaderUtil { // - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", ; rel="last" - */ - public static List extractAllURIs(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - - final List linkHeaders = Lists.newArrayList(); - final String[] links = linkHeader.split(", "); - for (final String link : links) { - final int positionOfSeparator = link.indexOf(';'); - linkHeaders.add(link.substring(1, positionOfSeparator - 1)); - } - - return linkHeaders; - } - public static String extractURIByRel(final String linkHeader, final String rel) { if (linkHeader == null) { return null; @@ -37,7 +15,7 @@ public final class HTTPLinkHeaderUtil { String uriWithSpecifiedRel = null; final String[] links = linkHeader.split(", "); - String linkRelation = null; + String linkRelation; for (final String link : links) { final int positionOfSeparator = link.indexOf(';'); linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); @@ -50,20 +28,9 @@ public final class HTTPLinkHeaderUtil { return uriWithSpecifiedRel; } - static Object extractTypeOfRelation(final String linkRelation) { + private static Object extractTypeOfRelation(final String linkRelation) { final int positionOfEquals = linkRelation.indexOf('='); return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); } - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next" - */ - public static String extractSingleURI(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - final int positionOfSeparator = linkHeader.indexOf(';'); - - return linkHeader.substring(1, positionOfSeparator - 1); - } - } diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 64c0160e1f..13db431ae3 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -307,7 +307,7 @@ 2.9.0 - 2.6.1 + 2.7.0 4.4.5 4.5.2 diff --git a/spring-security-sso/README.md b/spring-security-sso/README.md new file mode 100644 index 0000000000..11b5f011d5 --- /dev/null +++ b/spring-security-sso/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Simple Single Sign On with Spring Security OAuth2](http://www.baeldung.com/sso-spring-security-oauth2) diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..c0ad5eb690 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,14 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { +public class UiApplication extends SpringBootServletInitializer { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..5dbe9ada34 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..e186046e83 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,25 +2,13 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; -@EnableOAuth2Sso -@SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } +@SpringBootApplication +public class UiApplication extends SpringBootServletInitializer { @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..f9119e20f5 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,22 @@ +package org.baeldung.config; + +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableOAuth2Sso +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index 6c551b53b2..462e9e8c21 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java index 62c364f864..9c5efdbfc2 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class LayoutDialectControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 3d8ddfdd5c..4f6480e3b2 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -41,7 +41,7 @@ public class CsrfEnabledIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-vertx/README.md b/spring-vertx/README.md new file mode 100644 index 0000000000..05d059e1b2 --- /dev/null +++ b/spring-vertx/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Vert.x Spring Integration](http://www.baeldung.com/spring-vertx) diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java index 625e5439ee..b8eda25960 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,11 +2,12 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication -public class UiApplication { +public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java new file mode 100644 index 0000000000..ed72602f99 --- /dev/null +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java @@ -0,0 +1,17 @@ +package com.baeldung.pmd; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CntTest { + + private Cnt service; + + @Test + public void whenSecondParamIsZeroShouldReturnIntMax(){ + service = new Cnt(); + int answer = service.d(100,0); + assertEquals(Integer.MAX_VALUE, answer); + } +} diff --git a/structurizr/README.md b/structurizr/README.md new file mode 100644 index 0000000000..e596dfa458 --- /dev/null +++ b/structurizr/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Structurizr](http://www.baeldung.com/structurizr) diff --git a/testing/README.md b/testing/README.md index 6338a52f3d..a691737e4f 100644 --- a/testing/README.md +++ b/testing/README.md @@ -12,3 +12,4 @@ - [Testing with Google Truth](http://www.baeldung.com/google-truth) - [Testing with JGoTesting](http://www.baeldung.com/jgotesting) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) +- [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) diff --git a/testing/pom.xml b/testing/pom.xml index aa10392aa8..72ec2b2f0c 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -13,6 +13,11 @@ + + com.insightfullogic + lambda-behave + 0.4 + com.google.guava guava @@ -45,6 +50,12 @@ test + + info.cukes + cucumber-java8 + ${cucumber.version} + test + org.pitest diff --git a/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java new file mode 100644 index 0000000000..b194dce500 --- /dev/null +++ b/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java @@ -0,0 +1,24 @@ +package com.baeldung.lambdabehave; + +public class Calculator { + + private int x; + private int y; + + Calculator(int x, int y) { + this.x = x; + this.y = y; + } + + public int add() { + return this.x + this.y; + } + + public int divide(int a, int b) { + return a / b; + } + + public int add(int a, int b) { + return a + b; + } +} diff --git a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index 8ab49309cd..f1659437ec 100644 --- a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -1,20 +1,20 @@ package com.baeldung.junitparams; -import static org.junit.Assert.assertEquals; - import junitparams.FileParameters; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; +import static org.junit.Assert.assertEquals; + @RunWith(JUnitParamsRunner.class) public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) + @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -26,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test @@ -36,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test diff --git a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java index d318345a56..08a472502e 100644 --- a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; } public static Object[] provideEdgeCaseData() { - return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; + return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; } } diff --git a/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java new file mode 100644 index 0000000000..d179c6eb0e --- /dev/null +++ b/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java @@ -0,0 +1,54 @@ +package com.baeldung.lambdabehave; + +import com.insightfullogic.lambdabehave.JunitSuiteRunner; +import com.insightfullogic.lambdabehave.Suite; +import com.insightfullogic.lambdabehave.generators.Generator; +import com.insightfullogic.lambdabehave.generators.SourceGenerator; +import org.junit.runner.RunWith; + +@RunWith(JunitSuiteRunner.class) +public class CalculatorTest { + + private Calculator calculator; + + { + Suite.describe("Lambda behave example tests", it -> { + + it.isSetupWith(() -> { + calculator = new Calculator(1, 2); + }); + it.should("Add the given numbers", expect -> { + expect.that(calculator.add()).is(3); + }); + it.should("Throw an exception if divide by 0", expect -> { + expect.exception(ArithmeticException.class, () -> { + calculator.divide(1, 0); + }); + }); + it.uses(2, 3, 5) + .and(23, 10, 33) + .toShow("%d + %d = %d", (expect, a, b, c) -> { + expect.that(calculator.add(a, b)).is(c); + }); + it.requires(2) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + it.requires(2) + .withSource(SourceGenerator.deterministicNumbers(5626689007407L)) + .example(Generator.asciiStrings()) + .toShow("Reversing a String twice returns the original String", (expect, str) -> { + String same = new StringBuilder(str).reverse() + .reverse() + .toString(); + expect.that(same) + .isEqualTo(str); + }); + }); + } +} diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java index 1cdb92090a..20bd62396c 100644 --- a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java +++ b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java @@ -1,15 +1,14 @@ package com.baeldung.testing.calculator; -import org.junit.runner.RunWith; - import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( - features={"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} - , plugin = { "pretty", "json:target/reports/json/calculator.json" } - , glue = {"com.baeldung.cucumber.calculator"} + features = {"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} + , plugin = {"pretty", "json:target/reports/json/calculator.json"} + , glue = {"com.baeldung.cucumber.calculator"} ) public class CalculatorIntegrationTest { } diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java new file mode 100644 index 0000000000..7bf8641ed6 --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java @@ -0,0 +1,12 @@ +package com.baeldung.testing.shopping; + +import org.junit.runner.RunWith; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; + +@RunWith(Cucumber.class) +@CucumberOptions(features = { "classpath:features/shopping.feature" }) +public class ShoppingIntegrationTest { + +} diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java new file mode 100644 index 0000000000..2c4bf2eeae --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java @@ -0,0 +1,22 @@ +package com.baeldung.testing.shopping; + +import static org.junit.Assert.assertEquals; +import cucumber.api.java8.En; + +public class ShoppingStepsDef implements En { + + private int budget = 0; + + public ShoppingStepsDef() { + + Given("I have (\\d+) in my wallet", (Integer money) -> budget = money); + + When("I buy .* with (\\d+)", (Integer price) -> budget -= price); + + Then("I should have (\\d+) in my wallet", (Integer finalBudget) -> { + assertEquals(budget, finalBudget.intValue()); + }); + + } + +} \ No newline at end of file diff --git a/testing/src/test/resources/features/shopping.feature b/testing/src/test/resources/features/shopping.feature new file mode 100644 index 0000000000..d1ce43df75 --- /dev/null +++ b/testing/src/test/resources/features/shopping.feature @@ -0,0 +1,11 @@ +Feature: Shopping + + Scenario: Track my budget + Given I have 100 in my wallet + When I buy milk with 10 + Then I should have 90 in my wallet + + Scenario: Track my budget + Given I have 200 in my wallet + When I buy rice with 20 + Then I should have 180 in my wallet diff --git a/undertow/pom.xml b/undertow/pom.xml new file mode 100644 index 0000000000..33bac57178 --- /dev/null +++ b/undertow/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + com.baeldung.undertow + undertow + jar + 1.0-SNAPSHOT + undertow + http://maven.apache.org + + + 1.8 + 1.8 + + + + + io.undertow + undertow-servlet + 1.4.18.Final + + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + \ No newline at end of file diff --git a/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java new file mode 100644 index 0000000000..7f869746be --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/SimpleServer.java @@ -0,0 +1,16 @@ +package com.baeldung.undertow; + +import io.undertow.Undertow; +import io.undertow.util.Headers; + +public class SimpleServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(exchange -> { + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); + exchange.getResponseSender().send("Hello Baeldung"); + }).build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java new file mode 100644 index 0000000000..f5cdb827a6 --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/ftp/FileServer.java @@ -0,0 +1,20 @@ +package com.baeldung.undertow.ftp; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.PathResourceManager; + +import java.nio.file.Paths; + +import static io.undertow.Handlers.resource; + +public class FileServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100)) + .setDirectoryListingEnabled(true)) + .build(); + server.start(); + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java new file mode 100644 index 0000000000..491941261a --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/CustomIdentityManager.java @@ -0,0 +1,73 @@ +package com.baeldung.undertow.secure; + +import java.security.Principal; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import io.undertow.security.idm.Account; +import io.undertow.security.idm.Credential; +import io.undertow.security.idm.IdentityManager; +import io.undertow.security.idm.PasswordCredential; + +public class CustomIdentityManager implements IdentityManager { + + private final Map users; + + CustomIdentityManager(final Map users) { + this.users = users; + } + + @Override + public Account verify(Account account) { + return account; + } + + @Override + public Account verify(Credential credential) { + return null; + } + + @Override + public Account verify(String id, Credential credential) { + Account account = getAccount(id); + if (account != null && verifyCredential(account, credential)) { + return account; + } + return null; + } + + private boolean verifyCredential(Account account, Credential credential) { + if (credential instanceof PasswordCredential) { + char[] password = ((PasswordCredential) credential).getPassword(); + char[] expectedPassword = users.get(account.getPrincipal().getName()); + + return Arrays.equals(password, expectedPassword); + } + return false; + } + + private Account getAccount(final String id) { + if (users.containsKey(id)) { + return new Account() { + + private static final long serialVersionUID = 1L; + + private final Principal principal = () -> id; + + @Override + public Principal getPrincipal() { + return principal; + } + + @Override + public Set getRoles() { + return Collections.emptySet(); + } + }; + } + return null; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java new file mode 100644 index 0000000000..6532c3ed7c --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/secure/SecureServer.java @@ -0,0 +1,54 @@ +package com.baeldung.undertow.secure; + +import io.undertow.Undertow; +import io.undertow.io.IoCallback; +import io.undertow.security.api.AuthenticationMechanism; +import io.undertow.security.api.AuthenticationMode; +import io.undertow.security.api.SecurityContext; +import io.undertow.security.handlers.AuthenticationCallHandler; +import io.undertow.security.handlers.AuthenticationConstraintHandler; +import io.undertow.security.handlers.AuthenticationMechanismsHandler; +import io.undertow.security.handlers.SecurityInitialHandler; +import io.undertow.security.idm.IdentityManager; +import io.undertow.security.impl.BasicAuthenticationMechanism; +import io.undertow.server.HttpHandler; +import io.undertow.server.HttpServerExchange; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SecureServer { + + public static void main(String[] args) { + final Map users = new HashMap<>(2); + users.put("root", "password".toCharArray()); + users.put("admin", "password".toCharArray()); + + final IdentityManager idm = new CustomIdentityManager(users); + + Undertow server = Undertow.builder() + .addHttpListener(8080, "localhost") + .setHandler(addSecurity(SecureServer::setExchange, idm)).build(); + + server.start(); + } + + private static void setExchange(HttpServerExchange exchange) { + final SecurityContext context = exchange.getSecurityContext(); + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE); + } + + private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { + HttpHandler handler = toWrap; + handler = new AuthenticationCallHandler(handler); + handler = new AuthenticationConstraintHandler(handler); + final List mechanisms = Collections + .singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); + handler = new AuthenticationMechanismsHandler(handler, mechanisms); + handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); + return handler; + } + +} diff --git a/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java new file mode 100644 index 0000000000..295586e16f --- /dev/null +++ b/undertow/src/main/java/com/baeldung/undertow/socket/SocketServer.java @@ -0,0 +1,40 @@ +package com.baeldung.undertow.socket; + +import io.undertow.Undertow; +import io.undertow.server.handlers.resource.ClassPathResourceManager; +import io.undertow.websockets.core.AbstractReceiveListener; +import io.undertow.websockets.core.BufferedTextMessage; +import io.undertow.websockets.core.WebSocketChannel; +import io.undertow.websockets.core.WebSockets; + +import static io.undertow.Handlers.path; +import static io.undertow.Handlers.resource; +import static io.undertow.Handlers.websocket; + +public class SocketServer { + + public static void main(String[] args) { + Undertow server = Undertow.builder().addHttpListener(8080, "localhost") + .setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> { + channel.getReceiveSetter().set(getListener()); + channel.resumeReceives(); + })).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(), + SocketServer.class.getPackage())).addWelcomeFiles("index.html"))) + .build(); + + server.start(); + } + + private static AbstractReceiveListener getListener() { + return new AbstractReceiveListener() { + @Override + protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { + final String messageData = message.getData(); + for (WebSocketChannel session : channel.getPeerConnections()) { + WebSockets.sendText(messageData, session, null); + } + } + }; + } + +} diff --git a/vaadin/pom.xml b/vaadin/pom.xml new file mode 100644 index 0000000000..6d3512ba2d --- /dev/null +++ b/vaadin/pom.xml @@ -0,0 +1,173 @@ + + + 4.0.0 + + org.test + vaadin-app + war + 1.0-SNAPSHOT + vaadin-app + + + 3 + + + + 7.7.10 + 8.0.6 + 9.3.9.v20160517 + UTF-8 + 1.8 + 1.8 + local + mytheme + + + + + vaadin-addons + http://maven.vaadin.com/vaadin-addons + + + + + + + com.vaadin + vaadin-bom + ${vaadin.version} + pom + import + + + + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + com.vaadin + vaadin-server + + + com.vaadin + vaadin-push + + + com.vaadin + vaadin-client-compiled + + + com.vaadin + vaadin-themes + + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + false + + WEB-INF/classes/VAADIN/widgetsets/WEB-INF/** + + + + com.vaadin + vaadin-maven-plugin + ${vaadin.plugin.version} + + + + update-theme + update-widgetset + compile + + compile-theme + + + + + + org.apache.maven.plugins + maven-clean-plugin + 3.0.0 + + + + + src/main/webapp/VAADIN/themes + + **/styles.css + **/styles.scss.cache + + + + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.plugin.version} + + 2 + + + + + + + + + vaadin-prerelease + + false + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + + diff --git a/vaadin/src/main/java/com/baeldung/introduction/BindData.java b/vaadin/src/main/java/com/baeldung/introduction/BindData.java new file mode 100644 index 0000000000..299554c039 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/BindData.java @@ -0,0 +1,20 @@ +package com.baeldung.introduction; + +public class BindData { + + private String bindName; + + public BindData(String bindName){ + this.bindName = bindName; + } + + public String getBindName() { + return bindName; + } + + public void setBindName(String bindName) { + this.bindName = bindName; + } + + +} diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java new file mode 100644 index 0000000000..1b3733ad74 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -0,0 +1,281 @@ +package com.baeldung.introduction; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.servlet.annotation.WebServlet; + +import com.vaadin.annotations.Push; +import com.vaadin.annotations.Theme; +import com.vaadin.annotations.VaadinServletConfiguration; +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.fieldgroup.BeanFieldGroup; +import com.vaadin.data.validator.StringLengthValidator; +import com.vaadin.server.ExternalResource; +import com.vaadin.server.FontAwesome; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinServlet; +import com.vaadin.ui.Button; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.ComboBox; +import com.vaadin.ui.DateField; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.Grid; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.InlineDateField; +import com.vaadin.ui.Label; +import com.vaadin.ui.Link; +import com.vaadin.ui.ListSelect; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.NativeSelect; +import com.vaadin.ui.Panel; +import com.vaadin.ui.PasswordField; +import com.vaadin.ui.RichTextArea; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.TextField; +import com.vaadin.ui.TwinColSelect; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; + +@SuppressWarnings("serial") +@Push +@Theme("mytheme") +public class VaadinUI extends UI { + + private Label currentTime; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + protected void init(VaadinRequest vaadinRequest) { + final VerticalLayout verticalLayout = new VerticalLayout(); + verticalLayout.setSpacing(true); + verticalLayout.setMargin(true); + final GridLayout gridLayout = new GridLayout(3, 2); + gridLayout.setSpacing(true); + gridLayout.setMargin(true); + final HorizontalLayout horizontalLayout = new HorizontalLayout(); + horizontalLayout.setSpacing(true); + horizontalLayout.setMargin(true); + final FormLayout formLayout = new FormLayout(); + formLayout.setSpacing(true); + formLayout.setMargin(true); + final GridLayout buttonLayout = new GridLayout(3, 5); + buttonLayout.setMargin(true); + buttonLayout.setSpacing(true); + + final Label label = new Label(); + label.setId("Label"); + label.setValue("Label Value"); + label.setCaption("Label"); + gridLayout.addComponent(label); + + final Link link = new Link("Baeldung", new ExternalResource("http://www.baeldung.com/")); + link.setId("Link"); + link.setTargetName("_blank"); + gridLayout.addComponent(link); + + final TextField textField = new TextField(); + textField.setId("TextField"); + textField.setCaption("TextField:"); + textField.setValue("TextField Value"); + textField.setIcon(FontAwesome.USER); + gridLayout.addComponent(textField); + + final TextArea textArea = new TextArea(); + textArea.setCaption("TextArea"); + textArea.setId("TextArea"); + textArea.setValue("TextArea Value"); + gridLayout.addComponent(textArea); + + final DateField dateField = new DateField("DateField", new Date(0)); + dateField.setId("DateField"); + gridLayout.addComponent(dateField); + + final PasswordField passwordField = new PasswordField(); + passwordField.setId("PasswordField"); + passwordField.setCaption("PasswordField:"); + passwordField.setValue("password"); + gridLayout.addComponent(passwordField); + + final RichTextArea richTextArea = new RichTextArea(); + richTextArea.setCaption("Rich Text Area"); + richTextArea.setValue("

RichTextArea

"); + richTextArea.setSizeFull(); + + Panel richTextPanel = new Panel(); + richTextPanel.setContent(richTextArea); + + final InlineDateField inlineDateField = new InlineDateField(); + inlineDateField.setValue(new Date(0)); + inlineDateField.setCaption("Inline Date Field"); + horizontalLayout.addComponent(inlineDateField); + + Button normalButton = new Button("Normal Button"); + normalButton.setId("NormalButton"); + normalButton.addClickListener(e -> { + label.setValue("CLICK"); + }); + buttonLayout.addComponent(normalButton); + + Button tinyButton = new Button("Tiny Button"); + tinyButton.addStyleName("tiny"); + buttonLayout.addComponent(tinyButton); + + Button smallButton = new Button("Small Button"); + smallButton.addStyleName("small"); + buttonLayout.addComponent(smallButton); + + Button largeButton = new Button("Large Button"); + largeButton.addStyleName("large"); + buttonLayout.addComponent(largeButton); + + Button hugeButton = new Button("Huge Button"); + hugeButton.addStyleName("huge"); + buttonLayout.addComponent(hugeButton); + + Button disabledButton = new Button("Disabled Button"); + disabledButton.setDescription("This button cannot be clicked"); + disabledButton.setEnabled(false); + buttonLayout.addComponent(disabledButton); + + Button dangerButton = new Button("Danger Button"); + dangerButton.addStyleName("danger"); + buttonLayout.addComponent(dangerButton); + + Button friendlyButton = new Button("Friendly Button"); + friendlyButton.addStyleName("friendly"); + buttonLayout.addComponent(friendlyButton); + + Button primaryButton = new Button("Primary Button"); + primaryButton.addStyleName("primary"); + buttonLayout.addComponent(primaryButton); + + NativeButton nativeButton = new NativeButton("Native Button"); + buttonLayout.addComponent(nativeButton); + + Button iconButton = new Button("Icon Button"); + iconButton.setIcon(FontAwesome.ALIGN_LEFT); + buttonLayout.addComponent(iconButton); + + Button borderlessButton = new Button("BorderLess Button"); + borderlessButton.addStyleName("borderless"); + buttonLayout.addComponent(borderlessButton); + + Button linkButton = new Button("Link Button"); + linkButton.addStyleName("link"); + buttonLayout.addComponent(linkButton); + + Button quietButton = new Button("Quiet Button"); + quietButton.addStyleName("quiet"); + buttonLayout.addComponent(quietButton); + + horizontalLayout.addComponent(buttonLayout); + + final CheckBox checkbox = new CheckBox("CheckBox"); + checkbox.setValue(true); + checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); + formLayout.addComponent(checkbox); + + List numbers = new ArrayList(); + numbers.add("One"); + numbers.add("Ten"); + numbers.add("Eleven"); + ComboBox comboBox = new ComboBox("ComboBox"); + comboBox.addItems(numbers); + formLayout.addComponent(comboBox); + + ListSelect listSelect = new ListSelect("ListSelect"); + listSelect.addItems(numbers); + listSelect.setRows(2); + formLayout.addComponent(listSelect); + + NativeSelect nativeSelect = new NativeSelect("NativeSelect"); + nativeSelect.addItems(numbers); + formLayout.addComponent(nativeSelect); + + TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); + twinColSelect.addItems(numbers); + + Grid grid = new Grid("Grid"); + grid.setColumns("Column1", "Column2", "Column3"); + grid.addRow("Item1", "Item2", "Item3"); + grid.addRow("Item4", "Item5", "Item6"); + + Panel panel = new Panel("Panel"); + panel.setContent(grid); + panel.setSizeUndefined(); + + Panel serverPushPanel = new Panel("Server Push"); + FormLayout timeLayout = new FormLayout(); + timeLayout.setSpacing(true); + timeLayout.setMargin(true); + currentTime = new Label("No TIME..."); + timeLayout.addComponent(currentTime); + serverPushPanel.setContent(timeLayout); + serverPushPanel.setSizeUndefined(); + ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); + Runnable task = () -> { + currentTime.setValue("Current Time : " + Instant.now()); + }; + scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); + + FormLayout dataBindingLayout = new FormLayout(); + dataBindingLayout.setSpacing(true); + dataBindingLayout.setMargin(true); + + BindData bindData = new BindData("BindData"); + BeanFieldGroup beanFieldGroup = new BeanFieldGroup(BindData.class); + beanFieldGroup.setItemDataSource(bindData); + TextField bindedTextField = (TextField) beanFieldGroup.buildAndBind("BindName", "bindName"); + bindedTextField.setWidth("250px"); + dataBindingLayout.addComponent(bindedTextField); + + FormLayout validatorLayout = new FormLayout(); + validatorLayout.setSpacing(true); + validatorLayout.setMargin(true); + + HorizontalLayout textValidatorLayout = new HorizontalLayout(); + textValidatorLayout.setSpacing(true); + textValidatorLayout.setMargin(true); + + TextField stringValidator = new TextField(); + stringValidator.setNullSettingAllowed(true); + stringValidator.setNullRepresentation(""); + stringValidator.addValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5, true)); + stringValidator.setValidationVisible(false); + textValidatorLayout.addComponent(stringValidator); + Button buttonStringValidator = new Button("Validate String"); + buttonStringValidator.addClickListener(e -> { + try { + stringValidator.setValidationVisible(false); + stringValidator.validate(); + } catch (InvalidValueException err) { + stringValidator.setValidationVisible(true); + } + }); + textValidatorLayout.addComponent(buttonStringValidator); + + validatorLayout.addComponent(textValidatorLayout); + verticalLayout.addComponent(gridLayout); + verticalLayout.addComponent(richTextPanel); + verticalLayout.addComponent(horizontalLayout); + verticalLayout.addComponent(formLayout); + verticalLayout.addComponent(twinColSelect); + verticalLayout.addComponent(panel); + verticalLayout.addComponent(serverPushPanel); + verticalLayout.addComponent(dataBindingLayout); + verticalLayout.addComponent(validatorLayout); + setContent(verticalLayout); + } + + @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) + public static class MyUIServlet extends VaadinServlet { + } +} diff --git a/vaadin/src/main/resources/README b/vaadin/src/main/resources/README new file mode 100644 index 0000000000..faabc74ad5 --- /dev/null +++ b/vaadin/src/main/resources/README @@ -0,0 +1 @@ +Please add your static resources here diff --git a/vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss new file mode 100644 index 0000000000..a5670b70c7 --- /dev/null +++ b/vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss @@ -0,0 +1,7 @@ +/* This file is automatically managed and will be overwritten from time to time. */ +/* Do not manually edit this file. */ + +/* Import and include this mixin into your project theme to include the addon themes */ +@mixin addons { +} + diff --git a/vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico b/vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico new file mode 100644 index 0000000000..ffb34a65c7 Binary files /dev/null and b/vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico differ diff --git a/vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss new file mode 100644 index 0000000000..2c5fb8b944 --- /dev/null +++ b/vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss @@ -0,0 +1,38 @@ +// If you edit this file you need to compile the theme. See README.md for details. + +// Global variable overrides. Must be declared before importing Valo. + +// Defines the plaintext font size, weight and family. Font size affects general component sizing. +//$v-font-size: 16px; +//$v-font-weight: 300; +//$v-font-family: "Open Sans", sans-serif; + +// Defines the border used by all components. +//$v-border: 1px solid (v-shade 0.7); +//$v-border-radius: 4px; + +// Affects the color of some component elements, e.g Button, Panel title, etc +//$v-background-color: hsl(210, 0%, 98%); +// Affects the color of content areas, e.g Panel and Window content, TextField input etc +//$v-app-background-color: $v-background-color; + +// Affects the visual appearance of all components +//$v-gradient: v-linear 8%; +//$v-bevel-depth: 30%; +//$v-shadow-opacity: 5%; + +// Defines colors for indicating status (focus, success, failure) +//$v-focus-color: valo-focus-color(); // Calculates a suitable color automatically +//$v-friendly-color: #2c9720; +//$v-error-indicator-color: #ed473b; + +// For more information, see: https://vaadin.com/book/-/page/themes.valo.html +// Example variants can be copy/pasted from https://vaadin.com/wiki/-/wiki/Main/Valo+Examples + +@import "../valo/valo.scss"; + +@mixin mytheme { + @include valo; + + // Insert your own theme rules here +} diff --git a/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css new file mode 100644 index 0000000000..75bf26f498 --- /dev/null +++ b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css @@ -0,0 +1,12986 @@ +/** + * Checks if a list contains a certain value. + * + * @param {list} $list - the list to check + * @param {value} $var - the value to search for + * @param {bool} $recursive (false) - should any contained lists be checked for the value + * + * @return {bool} true if the value is found from the list, false otherwise + * + * @group lists + */ + +/** + * Cross-browser opacity. + * + * @param {number} $value - opacity value from 0 to 1 + * @param {bool} $important (false) - should the property value be declared with !important + * + * @group util + */ + +@-webkit-keyframes valo-animate-in-fade { + 0% { + opacity: 0; + } + } + +@-moz-keyframes valo-animate-in-fade { + 0% { + opacity: 0; + } + } + +@keyframes valo-animate-in-fade { + 0% { + opacity: 0; + } + } + +@-webkit-keyframes valo-animate-out-fade { + 100% { + opacity: 0; + } + } + +@-moz-keyframes valo-animate-out-fade { + 100% { + opacity: 0; + } + } + +@keyframes valo-animate-out-fade { + 100% { + opacity: 0; + } + } + +@-webkit-keyframes valo-animate-in-slide-down { + 0% { + -webkit-transform: translateY(-100%); + } + } + +@-moz-keyframes valo-animate-in-slide-down { + 0% { + -moz-transform: translateY(-100%); + } + } + +@keyframes valo-animate-in-slide-down { + 0% { + -webkit-transform: translateY(-100%); + -moz-transform: translateY(-100%); + -ms-transform: translateY(-100%); + -o-transform: translateY(-100%); + transform: translateY(-100%); + } + } + +@-webkit-keyframes valo-animate-in-slide-up { + 0% { + -webkit-transform: translateY(100%); + } + } + +@-moz-keyframes valo-animate-in-slide-up { + 0% { + -moz-transform: translateY(100%); + } + } + +@keyframes valo-animate-in-slide-up { + 0% { + -webkit-transform: translateY(100%); + -moz-transform: translateY(100%); + -ms-transform: translateY(100%); + -o-transform: translateY(100%); + transform: translateY(100%); + } + } + +@-webkit-keyframes valo-animate-in-slide-left { + 0% { + -webkit-transform: translateX(100%); + } + } + +@-moz-keyframes valo-animate-in-slide-left { + 0% { + -moz-transform: translateX(100%); + } + } + +@keyframes valo-animate-in-slide-left { + 0% { + -webkit-transform: translateX(100%); + -moz-transform: translateX(100%); + -ms-transform: translateX(100%); + -o-transform: translateX(100%); + transform: translateX(100%); + } + } + +@-webkit-keyframes valo-animate-in-slide-right { + 0% { + -webkit-transform: translateX(-100%); + } + } + +@-moz-keyframes valo-animate-in-slide-right { + 0% { + -moz-transform: translateX(-100%); + } + } + +@keyframes valo-animate-in-slide-right { + 0% { + -webkit-transform: translateX(-100%); + -moz-transform: translateX(-100%); + -ms-transform: translateX(-100%); + -o-transform: translateX(-100%); + transform: translateX(-100%); + } + } + +@-webkit-keyframes valo-animate-out-slide-down { + 100% { + -webkit-transform: translateY(100%); + } + } + +@-moz-keyframes valo-animate-out-slide-down { + 100% { + -moz-transform: translateY(100%); + } + } + +@keyframes valo-animate-out-slide-down { + 100% { + -webkit-transform: translateY(100%); + -moz-transform: translateY(100%); + -ms-transform: translateY(100%); + -o-transform: translateY(100%); + transform: translateY(100%); + } + } + +@-webkit-keyframes valo-animate-out-slide-up { + 100% { + -webkit-transform: translateY(-100%); + } + } + +@-moz-keyframes valo-animate-out-slide-up { + 100% { + -moz-transform: translateY(-100%); + } + } + +@keyframes valo-animate-out-slide-up { + 100% { + -webkit-transform: translateY(-100%); + -moz-transform: translateY(-100%); + -ms-transform: translateY(-100%); + -o-transform: translateY(-100%); + transform: translateY(-100%); + } + } + +@-webkit-keyframes valo-animate-out-slide-left { + 100% { + -webkit-transform: translateX(-100%); + } + } + +@-moz-keyframes valo-animate-out-slide-left { + 100% { + -moz-transform: translateX(-100%); + } + } + +@keyframes valo-animate-out-slide-left { + 100% { + -webkit-transform: translateX(-100%); + -moz-transform: translateX(-100%); + -ms-transform: translateX(-100%); + -o-transform: translateX(-100%); + transform: translateX(-100%); + } + } + +@-webkit-keyframes valo-animate-out-slide-right { + 100% { + -webkit-transform: translateX(100%); + } + } + +@-moz-keyframes valo-animate-out-slide-right { + 100% { + -moz-transform: translateX(100%); + } + } + +@keyframes valo-animate-out-slide-right { + 100% { + -webkit-transform: translateX(100%); + -moz-transform: translateX(100%); + -ms-transform: translateX(100%); + -o-transform: translateX(100%); + transform: translateX(100%); + } + } + +@-webkit-keyframes valo-overlay-animate-in { + 0% { + -webkit-transform: translatey(-4px); + opacity: 0; + } + } + +@-moz-keyframes valo-overlay-animate-in { + 0% { + -moz-transform: translatey(-4px); + opacity: 0; + } + } + +@keyframes valo-overlay-animate-in { + 0% { + -webkit-transform: translatey(-4px); + -moz-transform: translatey(-4px); + -ms-transform: translatey(-4px); + -o-transform: translatey(-4px); + transform: translatey(-4px); + opacity: 0; + } + } + +@-webkit-keyframes valo-animate-out-slide-down-fade { + 100% { + opacity: 0; + -webkit-transform: translatey(30%); + } + } + +@-moz-keyframes valo-animate-out-slide-down-fade { + 100% { + opacity: 0; + -moz-transform: translatey(30%); + } + } + +@keyframes valo-animate-out-slide-down-fade { + 100% { + opacity: 0; + -webkit-transform: translatey(30%); + -moz-transform: translatey(30%); + -ms-transform: translatey(30%); + -o-transform: translatey(30%); + transform: translatey(30%); + } + } + +/** + * Outputs cross-browser Valo-specific linear gradient background-image declarations. + * + * @group style + * + * @param {color} $color ($v-background-color) - The base color for the gradient color stops + * @param {list} $gradient ($v-gradient) - Valo-specific gradient value. See the documentation for $v-gradient. + * @param {color} $fallback (null) - A fallback color for browser which do not support linear gradients (IE8 and IE9 in particular). If null, the base $color is used instead. + * @param {string} $direction (to bottom) - the direction of the linear gradient. The color stops are by default so that a lighter shade is at the start and a darker shade is at the end. + */ + +/** + * Computes a CSS border property value for the given base color. + * + * @group style + * + * @param {list} $border ($v-border) - CSS border value which can contain any of the color keywords + * @param {color} $color ($v-background-color) - the base color to which the color keywords are applied to + * @param {color} $context (null) - context/surrounding color where the border is expected to appear. The color of the final border is the darker of the two parameters passed to this function. + * @param {number} $strength (1) - adjustment for the border contrast + * + * @return {list} The input $border value with any color keyword replaced with the corresponding actual color + */ + +/** + * Ouput selectors and properties to vertically center elements inside their parent. + * + * @param {string} $to-align (()) - The selector to match the elements which you wish to align vertically. The targeted elements should be inline or inline-block elements. + * @param {string} $align (middle) - The vertical-align value, e.g. top, middle, bottom + * @param {string} $pseudo-element (after) - Which pseudo element to use for the vertical align guide + * + * @group util + */ + +@font-face { + font-family: ThemeIcons; + font-weight: normal; + font-style: normal; + src: url(../valo/util/bourbon/css3/../../../../base/fonts/themeicons-webfont.eot); + src: url(../valo/util/bourbon/css3/../../../../base/fonts/themeicons-webfont.eot?#iefix) format("embedded-opentype"), url(../valo/util/bourbon/css3/../../../../base/fonts/themeicons-webfont.woff) format("woff"), url(../valo/util/bourbon/css3/../../../../base/fonts/themeicons-webfont.ttf) format("truetype"), url(../valo/util/bourbon/css3/../../../../base/fonts/themeicons-webfont.svg#ThemeIcons) format("svg"); +} + +.ThemeIcons { + font-family: ThemeIcons; + font-style: normal; + font-weight: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + display: inline-block; + text-align: center; +} + +@font-face { + font-family: FontAwesome; + font-weight: normal; + font-style: normal; + src: url(../valo/util/bourbon/css3/../../../../base/fonts/fontawesome-webfont.eot); + src: url(../valo/util/bourbon/css3/../../../../base/fonts/fontawesome-webfont.eot?#iefix) format("embedded-opentype"), url(../valo/util/bourbon/css3/../../../../base/fonts/fontawesome-webfont.woff) format("woff"), url(../valo/util/bourbon/css3/../../../../base/fonts/fontawesome-webfont.ttf) format("truetype"), url(../valo/util/bourbon/css3/../../../../base/fonts/fontawesome-webfont.svg#FontAwesome) format("svg"); +} + +.FontAwesome { + font-family: FontAwesome; + font-style: normal; + font-weight: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + display: inline-block; + text-align: center; +} + +@font-face { + font-family: "Open Sans"; + src: url(../valo/fonts/open-sans/OpenSans-Light-webfont.eot); + src: url(../valo/fonts/open-sans/OpenSans-Light-webfont.eot?#iefix) format("embedded-opentype"), url(../valo/fonts/open-sans/OpenSans-Light-webfont.woff) format("woff"), url(../valo/fonts/open-sans/OpenSans-Light-webfont.ttf) format("truetype"); + font-weight: 300; + font-style: normal; +} + +@font-face { + font-family: "Open Sans"; + src: url(../valo/fonts/open-sans/OpenSans-Regular-webfont.eot); + src: url(../valo/fonts/open-sans/OpenSans-Regular-webfont.eot?#iefix) format("embedded-opentype"), url(../valo/fonts/open-sans/OpenSans-Regular-webfont.woff) format("woff"), url(../valo/fonts/open-sans/OpenSans-Regular-webfont.ttf) format("truetype"); + font-weight: 400; + font-style: normal; +} + +@font-face { + font-family: "Open Sans"; + src: url(../valo/fonts/open-sans/OpenSans-Semibold-webfont.eot); + src: url(../valo/fonts/open-sans/OpenSans-Semibold-webfont.eot?#iefix) format("embedded-opentype"), url(../valo/fonts/open-sans/OpenSans-Semibold-webfont.woff) format("woff"), url(../valo/fonts/open-sans/OpenSans-Semibold-webfont.ttf) format("truetype"); + font-weight: 600; + font-style: normal; +} + +@-webkit-keyframes v-rotate-360 { + to { + -webkit-transform: rotate(360deg); + } + } + +@-moz-keyframes v-rotate-360 { + to { + -moz-transform: rotate(360deg); + } + } + +@-o-keyframes v-rotate-360 { + to { + -o-transform: rotate(360deg); + } + } + +@keyframes v-rotate-360 { + to { + transform: rotate(360deg); + } + } + +@-webkit-keyframes v-progress-start { + 0% { + width: 0%; + } + 100% { + width: 50%; + } + } + +@-moz-keyframes v-progress-start { + 0% { + width: 0%; + } + 100% { + width: 50%; + } + } + +@keyframes v-progress-start { + 0% { + width: 0%; + } + 100% { + width: 50%; + } + } + +@-webkit-keyframes v-progress-delay { + 0% { + width: 50%; + } + 100% { + width: 90%; + } + } + +@-moz-keyframes v-progress-delay { + 0% { + width: 50%; + } + 100% { + width: 90%; + } + } + +@keyframes v-progress-delay { + 0% { + width: 50%; + } + 100% { + width: 90%; + } + } + +@-webkit-keyframes v-progress-wait { + 0% { + width: 90%; + height: 4px; + } + 3% { + width: 91%; + height: 7px; + } + 100% { + width: 96%; + height: 7px; + } + } + +@-moz-keyframes v-progress-wait { + 0% { + width: 90%; + height: 4px; + } + 3% { + width: 91%; + height: 7px; + } + 100% { + width: 96%; + height: 7px; + } + } + +@keyframes v-progress-wait { + 0% { + width: 90%; + height: 4px; + } + 3% { + width: 91%; + height: 7px; + } + 100% { + width: 96%; + height: 7px; + } + } + +@-webkit-keyframes v-progress-wait-pulse { + 0% { + opacity: 1; + } + 50% { + opacity: 0.1; + } + 100% { + opacity: 1; + } + } + +@-moz-keyframes v-progress-wait-pulse { + 0% { + opacity: 1; + } + 50% { + opacity: 0.1; + } + 100% { + opacity: 1; + } + } + +@keyframes v-progress-wait-pulse { + 0% { + opacity: 1; + } + 50% { + opacity: 0.1; + } + 100% { + opacity: 1; + } + } + +/** + * Outputs the context menu selectors and styles, which is used by Table and Tree for instance. + * + * @requires {mixin} valo-selection-item-style + * @requires {mixin} valo-selection-item-selected-style + */ + +/** + * The background color for overlay elements. + * + * @type color + * @group overlay + */ + +.v-shadow, .v-shadow-window { + display: none; +} + +.v-ie8 .v-shadow, .v-ie8 .v-shadow-window { + display: block; +} + +.v-ie8 .v-shadow .top, .v-ie8 .v-shadow-window .top { + position: absolute; + top: -6px; + right: 10px; + bottom: 6px; + left: -10px; + background: black; + filter: alpha(opacity=5) progid:DXImageTransform.Microsoft.blur(pixelradius=10, makeShadow=false); +} + +.v-ie8 .v-shadow .top-left, .v-ie8 .v-shadow-window .top-left { + position: absolute; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; + background: black; + filter: alpha(opacity=9) progid:DXImageTransform.Microsoft.blur(pixelradius=0, makeShadow=false); +} + +/** + * The backgound color for tooltips. + * + * @type color + * @group tooltip + */ + +/** + * + * + * @param {string} $primary-stylename (v-absolutelayout) - + * + * @group absolutelayout + */ + +/** + * Outputs the selectors and properties for the Accordion component. + * + * @param {string} $primary-stylename (v-accordion) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * @group accordion + */ + +/** + * Outputs the selectors and properties for the Button component. + * + * @param {string} $primary-stylename (v-button) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group button + */ + +/** + * A list of colors for custom event colors. Can be an empty list of you don't + * need any custom event colors. + * + * @example javascript + * // Java code + * // 'event' is an instance of EditableCalendarEvent + * event.setStyleName("color1"); // 1st color in the list + * event.setStyleName("color2"); // 2nd color in the list + * // etc. + * + * @group calendar + */ + +/** + * Outputs the selectors and properties for the CheckBox component. + * + * @param {string} $primary-stylename (v-checkbox) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group checkbox + */ + +/** + * Outputs the global selectors and properties for the ColorPicker component - styles which are + * considered mandatory for the component to work properly. + * + * @param {string} $primary-stylename (v-colorpicker) - the primary style name for the selectors + * + * @group colorpicker + */ + +/** + * Outputs the selectors and properties for the ComboBox component. + * + * @param {string} $primary-stylename (v-filterselect) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group combobox + */ + +/** + * The amount of spacing between different widgets in a component group. + * If null, a computed value is used ($v-border size * -1, or 1px if $v-border size is 0) + * + * @group csslayout + */ + +/** + * + * + * @param {string} $primary-stylename (v-customcomponent) - + * + * @group customcomponent + */ + +/** + * + * + * @param {string} $primary-stylename (v-customlayout) - + * + * @group customlayout + */ + +/** + * Outputs the selectors and properties for the DateField component. + * + * @param {string} $primary-stylename (v-datefield) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group datefield + */ + +/** + * Outputs the styles and selectors for the DragAndDropWrapper component. + * + * @param {string} $primary-stylename (v-ddwrapper) - the primary style name for the selectors + * + * @group drag-n-drop + */ + +/** + * + * + * @param {string} $primary-stylename (v-form) - + * + * @group form + */ + +/** + * Outputs the selectors and properties for the FormLayout component. + * + * @param {string} $primary-stylename (v-formlayout) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group formlayout + */ + +/** + * + * @group table + */ + +@-webkit-keyframes valo-grid-editor-footer-animate-in { + 0% { + margin-top: -37px; + } + } + +@-moz-keyframes valo-grid-editor-footer-animate-in { + 0% { + margin-top: -37px; + } + } + +@keyframes valo-grid-editor-footer-animate-in { + 0% { + margin-top: -37px; + } + } + +@-webkit-keyframes valo-grid-editor-footer-animate-in-alt { + 0% { + margin-bottom: -38px; + } + 100% { + margin-bottom: -1px; + } + } + +@-moz-keyframes valo-grid-editor-footer-animate-in-alt { + 0% { + margin-bottom: -38px; + } + 100% { + margin-bottom: -1px; + } + } + +@keyframes valo-grid-editor-footer-animate-in-alt { + 0% { + margin-bottom: -38px; + } + 100% { + margin-bottom: -1px; + } + } + +/** + * + * + * @param {string} $primary-stylename (v-gridlayout) - + * + * @group gridlayout + */ + +/** + * The font weight for headers. + * + * @group label + */ + +/** + * + * @group link + */ + +/** + * + * + * @param {string} $primary-stylename (v-loginform) - + * + * @group loginform + */ + +/** + * + * + * @param {string} $primary-stylename (v-menubar) - + * @param {bool} $include-additional-styles - + * + * @group menubar + */ + +/** + * + * + * @param {string} $primary-stylename (v-nativebutton) - + * + * @group nativebutton + */ + +/** + * + * + * @param {string} $primary-stylename (v-select) - + * + * @group nativeselect + */ + +/** + * + * @group notification + */ + +/** + * + * + * @param {string} $primary-stylename (v-select-optiongroup) - + * @param {bool} $include-additional-styles - + * + * @group optiongroup + */ + +/** + * + * + * + * @group orderedlayout + */ + +/** + * + * @group panel + */ + +@-webkit-keyframes v-popupview-animate-in { + 0% { + -webkit-transform: scale(0); + } + } + +@-moz-keyframes v-popupview-animate-in { + 0% { + -moz-transform: scale(0); + } + } + +@keyframes v-popupview-animate-in { + 0% { + -webkit-transform: scale(0); + -moz-transform: scale(0); + -ms-transform: scale(0); + -o-transform: scale(0); + transform: scale(0); + } + } + +/** + * + * @group progressbar + */ + +/** + * + * @group richtextarea + */ + +/** + * + * @group slider + */ + +/** + * + * + * @param {string} $primary-stylename (v-splitpanel) - + * @param {bool} $include-additional-styles - + * + * @group splitpanel + */ + +/** + * + * @group table + */ + +/** + * Should the tabsheet content changes be animated. + * + * @group tabsheet + */ + +/** + * The background color for text fields. + * @group textfield + */ + +/** + * Outputs the selectors and properties for the TextArea component. + * + * @param {string} $primary-stylename (v-textarea) - the primary style name for the selectors + * @param {bool} $include-additional-styles - should the mixin output all the different style variations of the component + * + * @group textarea + */ + +/** + * + * @group tree + */ + +/** + * + * + * @param {string} $primary-stylename (v-treetable) - + * + * @group treetable + */ + +/** + * + * + * @param {string} $primary-stylename (v-select-twincol) - + * + * @group twin-column-select + */ + +/** + * + * + * @param {string} $primary-stylename (v-upload) - + * + * @group upload + */ + +/** + * + */ + +/** + * @group window + */ + +@-webkit-keyframes valo-modal-window-indication { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } + } + +@-moz-keyframes valo-modal-window-indication { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } + } + +@keyframes valo-modal-window-indication { + 0% { + opacity: 0; + } + 100% { + opacity: 1; + } + } + +@-webkit-keyframes valo-animate-out-scale-down-fade { + 100% { + -webkit-transform: scale(0.8); + opacity: 0; + } + } + +@-moz-keyframes valo-animate-out-scale-down-fade { + 100% { + -moz-transform: scale(0.8); + opacity: 0; + } + } + +@keyframes valo-animate-out-scale-down-fade { + 100% { + -webkit-transform: scale(0.8); + -moz-transform: scale(0.8); + -ms-transform: scale(0.8); + -o-transform: scale(0.8); + transform: scale(0.8); + opacity: 0; + } + } + +/** + * @group valo-menu + */ + +.v-vaadin-version:after { + content: "7.7.10"; +} + +.v-widget { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + display: inline-block; + vertical-align: top; + text-align: left; + white-space: normal; +} + +.v-generated-body { + overflow: hidden; + margin: 0; + padding: 0; + border: 0; +} + +.v-app { + height: 100%; + -webkit-tap-highlight-color: transparent; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.v-app input[type="text"], .v-app .v-slot > .v-caption, .v-app .v-gridlayout-slot > .v-caption, .v-app .v-has-caption > .v-caption, .v-app .v-formlayout-captioncell > .v-caption, .v-app .v-csslayout > .v-caption { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} + +.v-app input::-ms-clear { + display: none; +} + +.v-ui { + position: relative; +} + +.v-ui.v-ui-embedded { + margin-top: -1px; + border-top: 1px solid transparent; +} + +.v-ui:focus { + outline: none; +} + +.v-overlay-container { + width: 0; + height: 0; +} + +.v-drag-element { + z-index: 60000; + position: absolute !important; + cursor: default; +} + +.v-clip { + overflow: hidden; +} + +.v-scrollable { + overflow: auto; +} + +.v-scrollable > .v-widget { + vertical-align: middle; + overflow: hidden; +} + +.v-ios.v-webkit .v-scrollable { + -webkit-overflow-scrolling: touch; +} + +.v-ios5.v-webkit .v-scrollable { + -webkit-overflow-scrolling: none; +} + +.v-webkit.v-ios .v-browserframe { + -webkit-overflow-scrolling: touch; + overflow: auto; +} + +.v-assistive-device-only { + position: absolute; + top: -2000px; + left: -2000px; + width: 10px; + overflow: hidden; +} + +.v-icon { + cursor: inherit; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.v-icon, .v-errorindicator, .v-required-field-indicator { + display: inline-block; + line-height: inherit; +} + +.v-caption { + display: inline-block; + white-space: nowrap; + line-height: 1.55; +} + +.v-captiontext { + display: inline-block; + line-height: inherit; +} + +div.v-layout.v-horizontal.v-widget { + white-space: nowrap; +} + +.v-layout.v-vertical > .v-expand, .v-layout.v-horizontal > .v-expand { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 100%; + height: 100%; +} + +.v-slot, .v-spacing { + display: inline-block; + white-space: nowrap; + vertical-align: top; +} + +.v-vertical > .v-slot:after { + display: inline-block; + clear: both; + width: 0; + height: 0; + overflow: hidden; +} + +.v-vertical > .v-slot, .v-vertical > .v-expand > .v-slot { + display: block; + clear: both; +} + +.v-horizontal > .v-slot, .v-horizontal > .v-expand > .v-slot { + height: 100%; +} + +.v-horizontal > .v-expand > .v-slot { + position: relative; +} + +.v-vertical > .v-spacing, .v-vertical > .v-expand > .v-spacing { + width: 0 !important; + display: block; + clear: both; +} + +.v-horizontal > .v-spacing, .v-horizontal > .v-expand > .v-spacing { + height: 0 !important; +} + +.v-align-middle:before, .v-align-bottom:before, .v-expand > .v-align-middle:before, .v-expand > .v-align-bottom:before { + content: ""; + display: inline-block; + height: 100%; + vertical-align: middle; + width: 0; +} + +.v-align-middle, .v-align-bottom { + white-space: nowrap; +} + +.v-align-middle > .v-widget, .v-align-bottom > .v-widget { + display: inline-block; +} + +.v-align-middle, .v-align-middle > .v-widget { + vertical-align: middle; +} + +.v-align-bottom, .v-align-bottom > .v-widget { + vertical-align: bottom; +} + +.v-align-center { + text-align: center; +} + +.v-align-center > .v-widget { + margin-left: auto; + margin-right: auto; +} + +.v-align-right { + text-align: right; +} + +.v-align-right > .v-widget { + margin-left: auto; +} + +.v-has-caption, .v-has-caption > .v-caption { + display: inline-block; +} + +.v-caption-on-left, .v-caption-on-right { + white-space: nowrap; +} + +.v-caption-on-top > .v-caption, .v-caption-on-bottom > .v-caption { + display: block; +} + +.v-caption-on-left > .v-caption { + padding-right: 0.5em; +} + +.v-caption-on-left > .v-widget, .v-caption-on-right > .v-widget { + display: inline-block; +} + +.v-has-caption.v-has-width > .v-widget { + width: 100% !important; +} + +.v-has-caption.v-has-height > .v-widget { + height: 100% !important; +} + +.v-gridlayout { + position: relative; +} + +.v-gridlayout-slot { + position: absolute; + line-height: 1.55; +} + +.v-gridlayout-spacing-on { + overflow: hidden; +} + +.v-gridlayout-spacing, .v-gridlayout-spacing-off { + padding-left: 0; + padding-top: 0; +} + +.v-gridlayout-spacing-off { + overflow: hidden; +} + +.v-calendar-month-day-scrollable { + overflow-y: scroll; +} + +.v-calendar-week-wrapper { + position: relative; + overflow: hidden; +} + +.v-calendar-current-time { + position: absolute; + left: 0; + width: 100%; + height: 1px; + background: red; + z-index: 2; +} + +.v-calendar-event-resizetop, .v-calendar-event-resizebottom { + position: absolute; + height: 5%; + min-height: 3px; + width: 100%; + z-index: 1; +} + +.v-calendar-event-resizetop { + cursor: row-resize; + top: 0; +} + +.v-calendar-event-resizebottom { + cursor: row-resize; + bottom: 0; +} + +.v-calendar-header-month td:first-child { + padding-left: 20px; +} + +.v-calendar-month-sizedheight .v-calendar-month-day { + height: 100px; +} + +.v-calendar-month-sizedwidth .v-calendar-month-day { + width: 100px; +} + +.v-calendar-header-month-Hsized .v-calendar-header-day { + width: 101px; +} + +.v-calendar-header-month-Hsized td:first-child { + padding-left: 21px; +} + +.v-calendar-header-day-Hsized { + width: 200px; +} + +.v-calendar-week-numbers-Vsized .v-calendar-week-number { + height: 100px; + line-height: 100px; +} + +.v-calendar-week-wrapper-Vsized { + height: 400px; + overflow-x: hidden !important; +} + +.v-calendar-times-Vsized .v-calendar-time { + height: 38px; +} + +.v-calendar-times-Hsized .v-calendar-time { + width: 42px; +} + +.v-calendar-day-times-Vsized .v-datecellslot, .v-calendar-day-times-Vsized .v-datecellslot-even { + height: 18px; +} + +.v-calendar-day-times-Hsized, .v-calendar-day-times-Hsized .v-datecellslot, .v-calendar-day-times-Hsized .v-datecellslot-even { + width: 200px; +} + +.v-colorpicker-popup.v-window { + min-width: 220px !important; +} + +.v-colorpicker-gradient-container { + overflow: visible !important; +} + +.v-colorpicker-gradient-clicklayer { + opacity: 0; + filter: alpha(opacity=0) ; +} + +.rgb-gradient .v-colorpicker-gradient-background { + background: url(../valo/components/img/colorpicker/gradient2.png); +} + +.hsv-gradient .v-colorpicker-gradient-foreground { + background: url(../valo/components/img/colorpicker/gradient.png); +} + +.v-colorpicker-gradient-higherbox:before { + content: ""; + width: 11px; + height: 11px; + border-radius: 7px; + border: 1px solid #fff; + -webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(0, 0, 0, 0.3); + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(0, 0, 0, 0.3); + position: absolute; + bottom: -6px; + left: -6px; +} + +.v-colorpicker-popup .v-slider.v-slider-red:before { + background-color: red; +} + +.v-colorpicker-popup .v-slider.v-slider-green:before { + background-color: green; +} + +.v-colorpicker-popup .v-slider.v-slider-blue:before { + background-color: blue; +} + +.v-colorpicker-popup .v-slider.hue-slider:before { + background: url(../valo/components/img/colorpicker/slider_hue_bg.png); +} + +.v-colorpicker-popup input.v-textfield-dark { + color: #fff; +} + +.v-colorpicker-popup input.v-textfield-light { + color: #000; +} + +.v-colorpicker-grid { + height: 319px; +} + +.v-colorpicker-popup .colorselect td { + line-height: 15px; +} + +.v-table-header table, .v-table-footer table, .v-table-table { + border-spacing: 0; + border-collapse: separate; + margin: 0; + padding: 0; + border: 0; + line-height: 1.55; +} + +.v-table-resizer, .v-table-sort-indicator { + float: right; +} + +.v-table-caption-container-align-center { + text-align: center; +} + +.v-table-caption-container-align-right { + text-align: right; +} + +.v-table-header td, .v-table-footer td, .v-table-cell-content { + padding: 0; +} + +.v-table-sort-indicator { + width: 0; +} + +.v-tabsheet-hidetabs > .v-tabsheet-tabcontainer, .v-tabsheet-spacertd, .v-disabled .v-tabsheet-scroller, .v-tabsheet .v-disabled .v-tabsheet-caption-close { + display: none; +} + +.v-tabsheet { + overflow: visible !important; + position: relative; +} + +.v-tabsheet-tabcontainer table, .v-tabsheet-tabcontainer tbody, .v-tabsheet-tabcontainer tr { + display: inline-block; + border-spacing: 0; + border-collapse: collapse; + vertical-align: top; +} + +.v-tabsheet-tabcontainer td { + display: inline-block; + padding: 0; +} + +.v-tabsheet-tabs { + white-space: nowrap; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.v-tabsheet-content { + position: relative; +} + +.v-tabsheet-content > div > .v-scrollable > .v-margin-top { + padding-top: 12px; +} + +.v-tabsheet-content > div > .v-scrollable > .v-margin-right { + padding-right: 12px; +} + +.v-tabsheet-content > div > .v-scrollable > .v-margin-bottom { + padding-bottom: 12px; +} + +.v-tabsheet-content > div > .v-scrollable > .v-margin-left { + padding-left: 12px; +} + +.v-splitpanel-vertical, .v-splitpanel-horizontal { + overflow: hidden; + white-space: nowrap; +} + +.v-splitpanel-hsplitter { + z-index: 100; + cursor: e-resize; + cursor: col-resize; +} + +.v-splitpanel-vsplitter { + z-index: 100; + cursor: s-resize; + cursor: row-resize; +} + +.v-splitpanel-hsplitter:after, .v-splitpanel-vsplitter:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.v-splitpanel-hsplitter div, .v-splitpanel-vsplitter div { + width: inherit; + height: inherit; + overflow: hidden; + position: relative; +} + +.v-splitpanel-hsplitter div:before, .v-splitpanel-vsplitter div:before { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.v-disabled [class$="splitter"] div { + cursor: default; +} + +.v-disabled [class$="splitter"] div:before { + display: none; +} + +.v-splitpanel-horizontal > div > .v-splitpanel-second-container { + position: static !important; + display: inline-block; + vertical-align: top; +} + +.v-splitpanel-horizontal > div > .v-splitpanel-first-container { + display: inline-block; + vertical-align: top; +} + +.mytheme.v-app, .mytheme.v-app-loading { + font: 300 16px/1.55 "Open Sans", sans-serif; + color: #464646; + background-color: #fafafa; + cursor: default; +} + +.mytheme .v-app-loading { + width: 100%; + height: 100%; + background: #fafafa; +} + +.mytheme .v-app-loading:before { + content: ""; + position: fixed; + z-index: 100; + top: 45%; + left: 50%; + width: 28px; + height: 28px; + padding: 9px; + margin-top: -24px; + margin-left: -24px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50%; + border-radius: 4px; +} + +.mytheme .v-loading-indicator { + position: fixed !important; + z-index: 99999; + left: 0; + right: auto; + top: 0; + width: 50%; + opacity: 1; + height: 4px; + background-color: #197de1; + pointer-events: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + -webkit-animation: v-progress-start 1000ms 200ms both; + -moz-animation: v-progress-start 1000ms 200ms both; + animation: v-progress-start 1000ms 200ms both; +} + +.mytheme .v-loading-indicator[style*="none"] { + display: block !important; + width: 100% !important; + opacity: 0; + -webkit-animation: none; + -moz-animation: none; + animation: none; + -webkit-transition: opacity 500ms 300ms, width 300ms; + -moz-transition: opacity 500ms 300ms, width 300ms; + transition: opacity 500ms 300ms, width 300ms; +} + +.mytheme .v-loading-indicator-delay { + width: 90%; + -webkit-animation: v-progress-delay 3.8s forwards; + -moz-animation: v-progress-delay 3.8s forwards; + animation: v-progress-delay 3.8s forwards; +} + +.v-ff .mytheme .v-loading-indicator-delay { + width: 50%; +} + +.mytheme .v-loading-indicator-wait { + width: 96%; + -webkit-animation: v-progress-wait 5s forwards, v-progress-wait-pulse 1s 4s infinite backwards; + -moz-animation: v-progress-wait 5s forwards, v-progress-wait-pulse 1s 4s infinite backwards; + animation: v-progress-wait 5s forwards, v-progress-wait-pulse 1s 4s infinite backwards; +} + +.v-ff .mytheme .v-loading-indicator-wait { + width: 90%; +} + +.v-ie8 .mytheme .v-loading-indicator, .v-ie8 .mytheme .v-loading-indicator-delay, .v-ie8 .mytheme .v-loading-indicator-wait, .v-ie9 .mytheme .v-loading-indicator, .v-ie9 .mytheme .v-loading-indicator-delay, .v-ie9 .mytheme .v-loading-indicator-wait { + width: 28px !important; + height: 28px; + padding: 9px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50%; + border-radius: 4px; + top: 9px; + right: 9px; + left: auto; + filter: alpha(opacity=50); +} + +.v-ie8 .mytheme .v-loading-indicator[style*="none"], .v-ie8 .mytheme .v-loading-indicator-delay[style*="none"], .v-ie8 .mytheme .v-loading-indicator-wait[style*="none"], .v-ie9 .mytheme .v-loading-indicator[style*="none"], .v-ie9 .mytheme .v-loading-indicator-delay[style*="none"], .v-ie9 .mytheme .v-loading-indicator-wait[style*="none"] { + display: none !important; +} + +.v-ie8 .mytheme .v-loading-indicator-wait, .v-ie9 .mytheme .v-loading-indicator-wait { + filter: alpha(opacity=100); +} + +.mytheme .v-scrollable:focus { + outline: none; +} + +.mytheme img.v-icon { + vertical-align: middle; +} + +.mytheme .v-caption { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; +} + +.mytheme .v-caption-on-left .v-caption, .mytheme .v-caption-on-right .v-caption { + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-icon + .v-captiontext, .mytheme .v-icon + span { + margin-left: 7px; +} + +.mytheme .v-icon + .v-captiontext:empty, .mytheme .v-icon + span:empty { + margin-left: 0; +} + +.mytheme .v-errorindicator { + color: #ed473b; + font-weight: 600; + width: 19px; + text-align: center; +} + +.mytheme .v-errorindicator:before { + content: "!"; +} + +.mytheme .v-required-field-indicator { + color: #ed473b; + padding: 0 0.2em; +} + +.mytheme select { + font: inherit; + font-weight: 400; + line-height: inherit; + padding: 5px; + margin: 0; + border-radius: 4px; + border: 1px solid #c5c5c5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + color: #464646; +} + +.mytheme select:focus { + outline: none; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme button { + font: inherit; + font-weight: 400; + line-height: 1.55; +} + +.mytheme a { + cursor: pointer; + color: #197de1; + text-decoration: underline; + font-weight: inherit; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme a:hover { + color: #4396ea; +} + +.mytheme a.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-disabled { + cursor: default !important; +} + +.mytheme .v-drag-element { + background: #fafafa; + color: #464646; + -webkit-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); + border-radius: 4px; + overflow: hidden; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-tooltip { + background-color: #323232; + background-color: rgba(50, 50, 50, 0.9); + -webkit-box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2); + color: white; + padding: 5px 9px; + border-radius: 3px; + max-width: 35em; + overflow: hidden !important; + font-size: 14px; +} + +.mytheme .v-tooltip div[style*="width"] { + width: auto !important; +} + +.mytheme .v-tooltip .v-errormessage { + background-color: white; + background-color: #fff; + color: #ed473b; + margin: -5px -9px; + padding: 5px 9px; + max-height: 10em; + overflow: auto; + font-weight: 400; +} + +.mytheme .v-tooltip .v-errormessage h2:only-child { + font: inherit; + line-height: inherit; +} + +.mytheme .v-tooltip .v-tooltip-text { + max-height: 10em; + overflow: auto; + margin-top: 10px; +} + +.mytheme .v-tooltip .v-errormessage[aria-hidden="true"] + .v-tooltip-text { + margin-top: 0; +} + +.mytheme .v-tooltip h1, .mytheme .v-tooltip h2, .mytheme .v-tooltip h3, .mytheme .v-tooltip h4 { + color: inherit; +} + +.mytheme .v-contextmenu { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + padding: 4px 4px; +} + +.mytheme .v-contextmenu[class*="animate-in"] { + -webkit-animation: valo-overlay-animate-in 120ms; + -moz-animation: valo-overlay-animate-in 120ms; + animation: valo-overlay-animate-in 120ms; +} + +.mytheme .v-contextmenu[class*="animate-out"] { + -webkit-animation: valo-animate-out-fade 120ms; + -moz-animation: valo-animate-out-fade 120ms; + animation: valo-animate-out-fade 120ms; +} + +.mytheme .v-contextmenu table { + border-spacing: 0; +} + +.mytheme .v-contextmenu .gwt-MenuItem { + cursor: pointer; + line-height: 27px; + padding: 0 20px 0 10px; + border-radius: 3px; + font-weight: 400; + white-space: nowrap; + position: relative; + display: block; +} + +.mytheme .v-contextmenu .gwt-MenuItem:active:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: #0957a6; + opacity: 0.15; + filter: alpha(opacity=15.0) ; + pointer-events: none; + border-radius: inherit; +} + +.mytheme .v-contextmenu .gwt-MenuItem .v-icon { + max-height: 27px; + margin-right: 5px; + min-width: 1em; +} + +.mytheme .v-contextmenu .gwt-MenuItem-selected { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-reconnect-dialog { + color: white; + top: 12px; + right: 12px; + max-width: 100%; + border-radius: 0; + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + padding: 12px 15px; + background-color: #444; + background-color: rgba(68, 68, 68, 0.9); + line-height: 22px; + text-align: center; +} + +.mytheme .v-reconnect-dialog .text { + display: inline-block; + padding-left: 10px; +} + +.mytheme .v-reconnect-dialog .spinner { + height: 24px !important; + width: 24px !important; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: 2px solid rgba(25, 125, 225, 0.2); + border-top-color: #197de1; + border-right-color: #197de1; + border-radius: 100%; + -webkit-animation: v-rotate-360 500ms infinite linear; + -moz-animation: v-rotate-360 500ms infinite linear; + animation: v-rotate-360 500ms infinite linear; + pointer-events: none; + display: none; + vertical-align: middle; +} + +.v-ie8 .mytheme .v-reconnect-dialog .spinner, .v-ie9 .mytheme .v-reconnect-dialog .spinner { + border: none; + border-radius: 4px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50% 50%; + background-size: 80%; +} + +.v-ie8 .mytheme .v-reconnect-dialog .spinner { + min-width: 30px; + min-height: 30px; +} + +.mytheme .v-reconnect-dialog.active .spinner { + display: inline-block; +} + +.mytheme .v-absolutelayout-wrapper { + position: absolute; +} + +.mytheme .v-absolutelayout-margin, .mytheme .v-absolutelayout-canvas { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-absolutelayout.v-has-height > div, .mytheme .v-absolutelayout.v-has-height .v-absolutelayout-margin { + height: 100%; +} + +.mytheme .v-absolutelayout.v-has-height > div, .mytheme .v-absolutelayout.v-has-width .v-absolutelayout-margin { + width: 100%; +} + +.mytheme .v-margin-top { + padding-top: 37px; +} + +.mytheme .v-margin-right { + padding-right: 37px; +} + +.mytheme .v-margin-bottom { + padding-bottom: 37px; +} + +.mytheme .v-margin-left { + padding-left: 37px; +} + +.mytheme .v-spacing { + width: 12px; + height: 12px; +} + +.mytheme .v-verticallayout-well, .mytheme .v-horizontallayout-well { + background: #f5f5f5; + color: #454545; + -webkit-box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + border-radius: 4px; + border: 1px solid #c5c5c5; +} + +.mytheme .v-verticallayout-well > div > [class*="-caption"], .mytheme .v-horizontallayout-well > div > [class*="-caption"] { + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-verticallayout-well > .v-margin-top, .mytheme .v-horizontallayout-well > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-verticallayout-well > .v-margin-right, .mytheme .v-horizontallayout-well > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-verticallayout-well > .v-margin-bottom, .mytheme .v-horizontallayout-well > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-verticallayout-well > .v-margin-left, .mytheme .v-horizontallayout-well > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-verticallayout-card, .mytheme .v-horizontallayout-card { + background: white; + color: #474747; + border-radius: 4px; + border: 1px solid #d5d5d5; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); +} + +.mytheme .v-verticallayout-card > .v-margin-top, .mytheme .v-horizontallayout-card > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-verticallayout-card > .v-margin-right, .mytheme .v-horizontallayout-card > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-verticallayout-card > .v-margin-bottom, .mytheme .v-horizontallayout-card > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-verticallayout-card > .v-margin-left, .mytheme .v-horizontallayout-card > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-horizontallayout-wrapping { + white-space: normal !important; +} + +.mytheme .v-horizontallayout-wrapping > .v-spacing + .v-slot, .mytheme .v-horizontallayout-wrapping > .v-slot:first-child { + margin-bottom: 12px; +} + +.mytheme .v-horizontallayout-wrapping > .v-slot:first-child:last-child { + margin-bottom: 0; +} + +.mytheme .v-button { + position: relative; + text-align: center; + white-space: nowrap; + outline: none; + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-button:before { + content: ""; + display: inline-block; + width: 0; + height: 100%; + vertical-align: middle; +} + +.mytheme .v-button > div { + vertical-align: middle; +} + +.v-sa .mytheme .v-button:before { + height: 110%; +} + +.v-ff .mytheme .v-button:before { + height: 107%; +} + +.v-ie .mytheme .v-button:before { + margin-top: 4px; +} + +.mytheme .v-button:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; +} + +.mytheme .v-button:focus:after { + -webkit-transition: none; + -moz-transition: none; + transition: none; +} + +.mytheme .v-button.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-button.v-disabled:after { + display: none; +} + +.mytheme .v-button:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-button:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-button:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-button-primary { + height: 37px; + padding: 0 16px; + color: #ecf2f8; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #1362b1; + border-top-color: #156ab3; + border-bottom-color: #1156a8; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + -webkit-box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); + padding: 0 19px; + font-weight: bold; + min-width: 81px; +} + +.mytheme .v-button-primary:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-primary:hover:after { + background-color: rgba(90, 163, 237, 0.1); +} + +.mytheme .v-button-primary:focus:after { + border: inherit; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-button-primary:active:after { + background-color: rgba(2, 62, 122, 0.2); +} + +.v-ie8 .mytheme .v-button-primary { + min-width: 43px; +} + +.mytheme .v-button-friendly { + height: 37px; + padding: 0 16px; + color: #eaf4e9; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #227719; + border-top-color: #257d1a; + border-bottom-color: #1e6b15; + background-color: #2c9720; + background-image: -webkit-linear-gradient(top, #2f9f22 2%, #26881b 98%); + background-image: linear-gradient(to bottom,#2f9f22 2%, #26881b 98%); + -webkit-box-shadow: inset 0 1px 0 #46b33a, inset 0 -1px 0 #26811b, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 #46b33a, inset 0 -1px 0 #26811b, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-button-friendly:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-friendly:hover:after { + background-color: rgba(65, 211, 48, 0.1); +} + +.mytheme .v-button-friendly:focus:after { + border: inherit; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-button-friendly:active:after { + background-color: rgba(14, 86, 6, 0.2); +} + +.mytheme .v-button-danger { + height: 37px; + padding: 0 16px; + color: #f9f0ef; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #bb382e; + border-top-color: #bc3c31; + border-bottom-color: #b13028; + background-color: #ed473b; + background-image: -webkit-linear-gradient(top, #ee4c3f 2%, #e13e33 98%); + background-image: linear-gradient(to bottom,#ee4c3f 2%, #e13e33 98%); + -webkit-box-shadow: inset 0 1px 0 #ef786f, inset 0 -1px 0 #da3c31, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 #ef786f, inset 0 -1px 0 #da3c31, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-button-danger:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-danger:hover:after { + background-color: rgba(243, 137, 129, 0.1); +} + +.mytheme .v-button-danger:focus:after { + border: inherit; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-button-danger:active:after { + background-color: rgba(146, 12, 2, 0.2); +} + +.mytheme .v-button-borderless { + border: none; + -webkit-box-shadow: none; + box-shadow: none; + background: transparent; + color: inherit; +} + +.mytheme .v-button-borderless:hover:after { + background: transparent; +} + +.mytheme .v-button-borderless:active { + opacity: 0.7; + filter: alpha(opacity=70) ; +} + +.mytheme .v-button-borderless:active:after { + background: transparent; +} + +.mytheme .v-button-borderless-colored { + border: none; + -webkit-box-shadow: none; + box-shadow: none; + background: transparent; + color: #197de1; +} + +.mytheme .v-button-borderless-colored:hover { + color: #4396ea; +} + +.mytheme .v-button-borderless-colored:hover:after { + background: transparent; +} + +.mytheme .v-button-borderless-colored:active { + opacity: 0.7; + filter: alpha(opacity=70) ; +} + +.mytheme .v-button-borderless-colored:active:after { + background: transparent; +} + +.mytheme .v-button-quiet { + visibility: hidden; +} + +.mytheme .v-button-quiet:focus, .mytheme .v-button-quiet:hover { + visibility: visible; +} + +.mytheme .v-button-quiet [class*="wrap"] { + visibility: visible; +} + +.mytheme .v-button-quiet [class*="caption"] { + display: inline-block; +} + +.mytheme .v-button-link { + border: none; + -webkit-box-shadow: none; + box-shadow: none; + background: transparent; + color: inherit; + cursor: pointer; + color: #197de1; + text-decoration: underline; + font-weight: inherit; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-button-link:hover:after { + background: transparent; +} + +.mytheme .v-button-link:active { + opacity: 0.7; + filter: alpha(opacity=70) ; +} + +.mytheme .v-button-link:active:after { + background: transparent; +} + +.mytheme .v-button-link:hover { + color: #4396ea; +} + +.mytheme .v-button-link.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-button-tiny { + height: 28px; + padding: 0 13px; + + + font-size: 12px; + + border-radius: 4px; +} + +.mytheme .v-button-tiny:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-small { + height: 31px; + padding: 0 14px; + + + font-size: 14px; + + border-radius: 4px; +} + +.mytheme .v-button-small:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-large { + height: 44px; + padding: 0 19px; + + + font-size: 20px; + + border-radius: 4px; +} + +.mytheme .v-button-large:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-huge { + height: 59px; + padding: 0 26px; + + + font-size: 26px; + + border-radius: 4px; +} + +.mytheme .v-button-huge:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-button-icon-align-right [class*="wrap"] { + display: inline-block; +} + +.mytheme .v-button-icon-align-right .v-icon { + float: right; + margin-left: 13px; +} + +.mytheme .v-button-icon-align-right .v-icon + span:not(:empty) { + margin-left: 0; +} + +.mytheme .v-button-icon-align-top { + height: auto; + padding-top: 5px; + padding-bottom: 5px; +} + +.mytheme .v-button-icon-align-top [class*="wrap"] { + display: inline-block; +} + +.mytheme .v-button-icon-align-top .v-icon { + display: block; + margin-left: auto; + margin-right: auto; +} + +.mytheme .v-button-icon-align-top .v-icon + span:not(:empty) { + margin-top: 7px; + margin-left: 0; +} + +.mytheme .v-button-icon-only { + width: 37px; + padding: 0; +} + +.mytheme .v-button-icon-only.v-button-tiny { + width: 28px; +} + +.mytheme .v-button-icon-only.v-button-small { + width: 31px; +} + +.mytheme .v-button-icon-only.v-button-large { + width: 44px; +} + +.mytheme .v-button-icon-only.v-button-huge { + width: 59px; +} + +.mytheme .v-button-icon-only .v-button-caption { + display: none; +} + +.mytheme .v-checkbox { + position: relative; + line-height: 19px; + white-space: nowrap; +} + +.mytheme .v-checkbox.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-checkbox { + padding-left: 25px; +} + +:root .mytheme .v-checkbox label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-checkbox > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-checkbox > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-checkbox > input ~ label:before, :root .mytheme .v-checkbox > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 19px; + height: 19px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 13px; + text-align: center; +} + +:root .mytheme .v-checkbox > input ~ label:before { + height: 18.5px; + padding: 0 9px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 19px; +} + +:root .mytheme .v-checkbox > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-checkbox > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-checkbox > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-checkbox > .v-icon, .mytheme .v-checkbox > label .v-icon { + margin: 0 6px 0 3px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-checkbox.v-disabled > label, .mytheme .v-checkbox.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-checkbox.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-checkbox.v-readonly > label, .mytheme .v-checkbox.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-checkbox.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-checkbox.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-checkbox-small { + position: relative; + line-height: 16px; + white-space: nowrap; + font-size: 14px; +} + +.mytheme .v-checkbox-small.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-checkbox-small { + padding-left: 21px; +} + +:root .mytheme .v-checkbox-small label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-checkbox-small > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-checkbox-small > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-checkbox-small > input ~ label:before, :root .mytheme .v-checkbox-small > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 16px; + height: 16px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 11px; + text-align: center; +} + +:root .mytheme .v-checkbox-small > input ~ label:before { + height: 15.5px; + padding: 0 7px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 16px; +} + +:root .mytheme .v-checkbox-small > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-checkbox-small > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-checkbox-small > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-checkbox-small > .v-icon, .mytheme .v-checkbox-small > label .v-icon { + margin: 0 5px 0 3px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-checkbox-small.v-disabled > label, .mytheme .v-checkbox-small.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-checkbox-small.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox-small.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-checkbox-small.v-readonly > label, .mytheme .v-checkbox-small.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-checkbox-small.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox-small.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-checkbox-small.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-checkbox-large { + position: relative; + line-height: 22px; + white-space: nowrap; + font-size: 20px; +} + +.mytheme .v-checkbox-large.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-checkbox-large { + padding-left: 29px; +} + +:root .mytheme .v-checkbox-large label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-checkbox-large > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-checkbox-large > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-checkbox-large > input ~ label:before, :root .mytheme .v-checkbox-large > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 22px; + height: 22px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 15px; + text-align: center; +} + +:root .mytheme .v-checkbox-large > input ~ label:before { + height: 22px; + padding: 0 10px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 22px; +} + +:root .mytheme .v-checkbox-large > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-checkbox-large > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-checkbox-large > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-checkbox-large > .v-icon, .mytheme .v-checkbox-large > label .v-icon { + margin: 0 7px 0 4px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-checkbox-large.v-disabled > label, .mytheme .v-checkbox-large.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-checkbox-large.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox-large.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-checkbox-large.v-readonly > label, .mytheme .v-checkbox-large.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-checkbox-large.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-checkbox-large.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-checkbox-large.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect { + position: relative; + width: 185px; + height: 37px; + border-radius: 4px; + white-space: nowrap; +} + +.mytheme .v-filterselect [class*="input"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 4px; + padding: 4px 9px; + border: 1px solid #c5c5c5; + background: white; + color: #474747; + -webkit-box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 100% !important; + height: 100%; + padding-right: 38px; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-filterselect [class*="input"], .v-ie9 .mytheme .v-filterselect [class*="input"] { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-filterselect [class*="input"].v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect [class*="input"]:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-filterselect [class*="input"][class*="prompt"] { + color: #a3a3a3; +} + +.mytheme .v-filterselect .v-icon + [class*="input"] { + padding-left: 37px; +} + +.mytheme .v-filterselect img.v-icon { + max-height: 37px; + margin-left: 9px; +} + +.mytheme .v-filterselect span.v-icon { + color: #474747; + width: 37px; + line-height: 1; + padding-top: 0.12em; +} + +.mytheme .v-filterselect[class*="prompt"] > [class*="input"] { + color: #a3a3a3; +} + +.mytheme .v-filterselect [class$="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + position: absolute; + width: 37px; + top: 1px; + right: 1px; + bottom: 1px; + border-left: 1px solid #e4e4e4; + color: #a3a3a3; + border-radius: 0 3px 3px 0; +} + +.v-ie8 .mytheme .v-filterselect [class$="button"] { + background-color: white; +} + +.mytheme .v-filterselect [class$="button"]:before { + font-family: ThemeIcons; + content: "\f078"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + position: absolute; + width: 37px; + text-align: center; + top: 50%; + line-height: 1; + margin-top: -0.47em; +} + +.mytheme .v-filterselect [class$="button"]:hover:before { + color: #474747; +} + +.mytheme .v-filterselect [class$="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; + background-color: rgba(128, 128, 128, 0.2); +} + +.mytheme .v-filterselect.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect.v-disabled [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect.v-disabled [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect.v-readonly [class*="input"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect.v-readonly [class*="input"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-filterselect.v-readonly [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect.v-readonly [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect .v-icon { + position: absolute; + pointer-events: none; +} + +.mytheme .v-filterselect-error .v-filterselect-input { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-filterselect-error .v-filterselect-button { + color: #ed473b; + border-color: #ed473b; +} + +.mytheme .v-filterselect-suggestpopup { + margin-top: 5px !important; +} + +.mytheme .v-filterselect-suggestpopup[class*="animate-in"] { + -webkit-animation: valo-overlay-animate-in 120ms; + -moz-animation: valo-overlay-animate-in 120ms; + animation: valo-overlay-animate-in 120ms; +} + +.mytheme .v-filterselect-suggestpopup [class$="suggestmenu"] { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + padding: 4px 4px; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + position: relative; + z-index: 1; + display: block; +} + +.mytheme .v-filterselect-suggestpopup table, .mytheme .v-filterselect-suggestpopup tbody, .mytheme .v-filterselect-suggestpopup tr, .mytheme .v-filterselect-suggestpopup td { + display: block; + width: 100%; + overflow-y: hidden; + float: left; + clear: both; +} + +.mytheme .v-filterselect-suggestpopup .gwt-MenuItem { + cursor: pointer; + line-height: 27px; + padding: 0 20px 0 10px; + border-radius: 3px; + font-weight: 400; + white-space: nowrap; + position: relative; + height: 27px; + box-sizing: border-box; + text-overflow: ellipsis; + overflow-x: hidden; +} + +.mytheme .v-filterselect-suggestpopup .gwt-MenuItem:active:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: #0957a6; + opacity: 0.15; + filter: alpha(opacity=15.0) ; + pointer-events: none; + border-radius: inherit; +} + +.mytheme .v-filterselect-suggestpopup .gwt-MenuItem .v-icon { + max-height: 27px; + margin-right: 5px; + min-width: 1em; +} + +.mytheme .v-filterselect-suggestpopup .gwt-MenuItem-selected { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-filterselect-suggestpopup [class$="status"] { + position: absolute; + right: 4px; + background: rgba(212, 212, 212, 0.9); + color: #3b3b3b; + border-radius: 0 0 4px 4px; + height: 23px; + bottom: -23px; + font-size: 12px; + line-height: 23px; + padding: 0 6px; + cursor: default; + pointer-events: none; + -webkit-animation: valo-animate-in-slide-down 200ms 80ms backwards; + -moz-animation: valo-animate-in-slide-down 200ms 80ms backwards; + animation: valo-animate-in-slide-down 200ms 80ms backwards; +} + +.mytheme .v-filterselect-suggestpopup [class$="status"] > * { + color: #3b3b3b; + text-decoration: none; +} + +.mytheme .v-filterselect-suggestpopup div[class*="page"] { + position: absolute; + z-index: 3; + right: 0; + opacity: 0.2; + filter: alpha(opacity=20) ; + cursor: pointer; + -webkit-transition: all 200ms; + -moz-transition: all 200ms; + transition: all 200ms; + width: 25px; + height: 25px; + line-height: 25px; + text-align: center; + font-family: ThemeIcons; + -webkit-transform: scale(0.8); + -moz-transform: scale(0.8); + -ms-transform: scale(0.8); + -o-transform: scale(0.8); + transform: scale(0.8); + color: #464646; +} + +.mytheme .v-filterselect-suggestpopup div[class*="page"]:after { + content: ""; + position: absolute; + display: block; + border-radius: 50%; +} + +.mytheme .v-filterselect-suggestpopup div[class*="page"]:hover { + opacity: 1; + filter: none ; + background: rgba(250, 250, 250, 0.5); +} + +.mytheme .v-filterselect-suggestpopup div[class*="page"]:hover:after { + top: -10px; + bottom: -10px; + left: -20px; + right: -20px; +} + +.mytheme .v-filterselect-suggestpopup div[class*="page"] span { + display: none; +} + +.mytheme .v-filterselect-suggestpopup:hover div[class*="page"] { + -webkit-transform: scale(1); + -moz-transform: scale(1); + -ms-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); +} + +.mytheme .v-filterselect-suggestpopup div[class*="prev"] { + top: 0; + -webkit-transform-origin: 100% 0%; + -moz-transform-origin: 100% 0%; + -ms-transform-origin: 100% 0%; + -o-transform-origin: 100% 0%; + transform-origin: 100% 0%; + border-radius: 0 4px 0 4px; +} + +.mytheme .v-filterselect-suggestpopup div[class*="prev"]:before { + content: "\f0d8"; +} + +.mytheme .v-filterselect-suggestpopup div[class*="next"] { + bottom: 0; + -webkit-transform-origin: 100% 100%; + -moz-transform-origin: 100% 100%; + -ms-transform-origin: 100% 100%; + -o-transform-origin: 100% 100%; + transform-origin: 100% 100%; + border-radius: 4px 0 4px 0; +} + +.mytheme .v-filterselect-suggestpopup div[class*="next"]:before { + content: "\f0d7"; +} + +.mytheme .v-filterselect-suggestpopup div[class*="-off"] { + display: none; +} + +.mytheme .v-filterselect-no-input { + cursor: pointer; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-filterselect-no-input [class*="input"] { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + cursor: inherit; + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + text-shadow: inherit; + text-overflow: ellipsis; + border-radius: inherit; +} + +.mytheme .v-filterselect-no-input [class*="input"]:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-filterselect-no-input [class$="button"] { + border-left: none !important; +} + +.mytheme .v-filterselect-no-input:hover [class$="button"]:before { + color: inherit; +} + +.mytheme .v-filterselect-borderless .v-filterselect-input { + border: none; + border-radius: 0; + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + color: inherit; +} + +.mytheme .v-filterselect-borderless .v-filterselect-input:focus { + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect-borderless .v-filterselect-input[class*="prompt"] { + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-borderless .v-filterselect-button { + border: none; + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-borderless.v-filterselect-prompt .v-filterselect-input { + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-align-right input { + text-align: right; +} + +.mytheme .v-filterselect-align-center input { + text-align: center; +} + +.mytheme .v-filterselect-tiny { + height: 28px; + + font-size: 12px; +} + +.mytheme .v-filterselect-tiny [class*="input"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 28px; + + padding: 3px 5px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 100% !important; + height: 100%; + padding-right: 29px; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-filterselect-tiny [class*="input"], .v-ie9 .mytheme .v-filterselect-tiny [class*="input"] { + line-height: 28px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-filterselect-tiny .v-icon + [class*="input"] { + padding-left: 28px; +} + +.mytheme .v-filterselect-tiny img.v-icon { + max-height: 28px; + margin-left: 5px; +} + +.mytheme .v-filterselect-tiny span.v-icon { + + width: 28px; + line-height: 1; + padding-top: 0.12em; +} + +.mytheme .v-filterselect-tiny [class$="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + position: absolute; + width: 28px; + border-radius: 0 4px 4px 0; +} + +.mytheme .v-filterselect-tiny [class$="button"]:before { + font-family: ThemeIcons; + content: "\f078"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + position: absolute; + width: 28px; + text-align: center; + top: 50%; + line-height: 1; + margin-top: -0.47em; +} + +.mytheme .v-filterselect-tiny [class$="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-filterselect-tiny.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-tiny.v-disabled [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-tiny.v-disabled [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-tiny.v-readonly [class*="input"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect-tiny.v-readonly [class*="input"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-filterselect-tiny.v-readonly [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-tiny.v-readonly [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-compact, .mytheme .v-filterselect-small { + height: 31px; + +} + +.mytheme .v-filterselect-compact [class*="input"], .mytheme .v-filterselect-small [class*="input"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 31px; + + padding: 3px 6px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 100% !important; + height: 100%; + padding-right: 32px; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-filterselect-compact [class*="input"], .v-ie9 .mytheme .v-filterselect-compact [class*="input"], .v-ie8 .mytheme .v-filterselect-small [class*="input"], .v-ie9 .mytheme .v-filterselect-small [class*="input"] { + line-height: 31px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-filterselect-compact .v-icon + [class*="input"], .mytheme .v-filterselect-small .v-icon + [class*="input"] { + padding-left: 31px; +} + +.mytheme .v-filterselect-compact img.v-icon, .mytheme .v-filterselect-small img.v-icon { + max-height: 31px; + margin-left: 6px; +} + +.mytheme .v-filterselect-compact span.v-icon, .mytheme .v-filterselect-small span.v-icon { + + width: 31px; + line-height: 1; + padding-top: 0.12em; +} + +.mytheme .v-filterselect-compact [class$="button"], .mytheme .v-filterselect-small [class$="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + position: absolute; + width: 31px; + border-radius: 0 4px 4px 0; +} + +.mytheme .v-filterselect-compact [class$="button"]:before, .mytheme .v-filterselect-small [class$="button"]:before { + font-family: ThemeIcons; + content: "\f078"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + position: absolute; + width: 31px; + text-align: center; + top: 50%; + line-height: 1; + margin-top: -0.47em; +} + +.mytheme .v-filterselect-compact [class$="button"]:active:after, .mytheme .v-filterselect-small [class$="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-filterselect-compact.v-disabled, .mytheme .v-filterselect-small.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-compact.v-disabled [class$="button"], .mytheme .v-filterselect-small.v-disabled [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-compact.v-disabled [class$="button"]:active:after, .mytheme .v-filterselect-small.v-disabled [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-compact.v-readonly [class*="input"], .mytheme .v-filterselect-small.v-readonly [class*="input"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect-compact.v-readonly [class*="input"]:focus, .mytheme .v-filterselect-small.v-readonly [class*="input"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-filterselect-compact.v-readonly [class$="button"], .mytheme .v-filterselect-small.v-readonly [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-compact.v-readonly [class$="button"]:active:after, .mytheme .v-filterselect-small.v-readonly [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-small { + font-size: 14px; +} + +.mytheme .v-filterselect-large { + height: 44px; + + font-size: 20px; +} + +.mytheme .v-filterselect-large [class*="input"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 44px; + + padding: 5px 8px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 100% !important; + height: 100%; + padding-right: 45px; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-filterselect-large [class*="input"], .v-ie9 .mytheme .v-filterselect-large [class*="input"] { + line-height: 44px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-filterselect-large .v-icon + [class*="input"] { + padding-left: 44px; +} + +.mytheme .v-filterselect-large img.v-icon { + max-height: 44px; + margin-left: 8px; +} + +.mytheme .v-filterselect-large span.v-icon { + + width: 44px; + line-height: 1; + padding-top: 0.12em; +} + +.mytheme .v-filterselect-large [class$="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + position: absolute; + width: 44px; + border-radius: 0 4px 4px 0; +} + +.mytheme .v-filterselect-large [class$="button"]:before { + font-family: ThemeIcons; + content: "\f078"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + position: absolute; + width: 44px; + text-align: center; + top: 50%; + line-height: 1; + margin-top: -0.47em; +} + +.mytheme .v-filterselect-large [class$="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-filterselect-large.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-large.v-disabled [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-large.v-disabled [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-large.v-readonly [class*="input"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect-large.v-readonly [class*="input"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-filterselect-large.v-readonly [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-large.v-readonly [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-huge { + height: 59px; + + font-size: 26px; +} + +.mytheme .v-filterselect-huge [class*="input"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 59px; + + padding: 7px 10px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 100% !important; + height: 100%; + padding-right: 60px; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-filterselect-huge [class*="input"], .v-ie9 .mytheme .v-filterselect-huge [class*="input"] { + line-height: 59px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-filterselect-huge .v-icon + [class*="input"] { + padding-left: 59px; +} + +.mytheme .v-filterselect-huge img.v-icon { + max-height: 59px; + margin-left: 10px; +} + +.mytheme .v-filterselect-huge span.v-icon { + + width: 59px; + line-height: 1; + padding-top: 0.12em; +} + +.mytheme .v-filterselect-huge [class$="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + position: absolute; + width: 59px; + border-radius: 0 4px 4px 0; +} + +.mytheme .v-filterselect-huge [class$="button"]:before { + font-family: ThemeIcons; + content: "\f078"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + position: absolute; + width: 59px; + text-align: center; + top: 50%; + line-height: 1; + margin-top: -0.47em; +} + +.mytheme .v-filterselect-huge [class$="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-filterselect-huge.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-filterselect-huge.v-disabled [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-huge.v-disabled [class$="button"]:active:after { + display: none; +} + +.mytheme .v-filterselect-huge.v-readonly [class*="input"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-filterselect-huge.v-readonly [class*="input"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-filterselect-huge.v-readonly [class$="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-filterselect-huge.v-readonly [class$="button"]:active:after { + display: none; +} + +.mytheme .v-csslayout-well { + background: #f5f5f5; + color: #454545; + -webkit-box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + border-radius: 4px; + border: 1px solid #c5c5c5; +} + +.mytheme .v-csslayout-well > div > [class*="-caption"] { + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-csslayout-well > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-csslayout-well > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-csslayout-well > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-csslayout-well > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-csslayout-card { + background: white; + color: #474747; + border-radius: 4px; + border: 1px solid #d5d5d5; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); +} + +.mytheme .v-csslayout-card > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-csslayout-card > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-csslayout-card > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-csslayout-card > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-csslayout-v-component-group { + white-space: nowrap; + position: relative; +} + +.mytheme .v-csslayout-v-component-group .v-widget ~ .v-widget:not(:last-child) { + border-radius: 0; +} + +.mytheme .v-csslayout-v-component-group .v-widget:last-child { + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} + +.mytheme .v-csslayout-v-component-group .v-widget:first-child, .mytheme .v-csslayout-v-component-group .v-caption:first-child + .v-widget { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} + +.mytheme .v-csslayout-v-component-group .v-widget ~ .v-widget.first.first { + border-radius: 4px 0 0 4px; +} + +.mytheme .v-csslayout-v-component-group .v-widget ~ .v-widget.last.last { + border-radius: 0 4px 4px 0; +} + +.mytheme .v-csslayout-v-component-group .v-widget { + vertical-align: middle; + margin-left: -1px; +} + +.mytheme .v-csslayout-v-component-group .v-widget:first-child { + margin-left: 0; +} + +.mytheme .v-csslayout-v-component-group .v-widget:focus, .mytheme .v-csslayout-v-component-group .v-widget[class*="focus"], .mytheme .v-csslayout-v-component-group .v-widget [class*="focus"] { + position: relative; + z-index: 5; +} + +.mytheme .v-form fieldset { + border: none; + padding: 0; + margin: 0; + height: 100%; +} + +.mytheme .v-form-content { + height: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme [class*="spacing"] > tbody > [class*="row"] > td { + padding-top: 12px; +} + +.mytheme [class*="spacing"] > tbody > [class*="firstrow"] > td { + padding-top: 0; +} + +.mytheme [class*="margin-top"] > tbody > [class*="firstrow"] > td { + padding-top: 37px; +} + +.mytheme [class*="margin-bottom"] > tbody > [class*="lastrow"] > td { + padding-bottom: 37px; +} + +.mytheme [class*="margin-left"] > tbody > [class*="row"] > [class*="captioncell"] { + padding-left: 37px; +} + +.mytheme [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h2, .mytheme [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + left: 37px; +} + +.mytheme [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] { + padding-right: 37px; +} + +.mytheme [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h2, .mytheme [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + right: 37px; +} + +.mytheme .v-formlayout > table { + border-spacing: 0; + position: relative; +} + +.mytheme .v-formlayout.v-has-width > table, .mytheme .v-formlayout.v-has-width .v-formlayout-contentcell { + width: 100%; +} + +.mytheme .v-formlayout-error-indicator { + width: 19px; +} + +.mytheme .v-formlayout-captioncell { + vertical-align: top; + line-height: 36px; +} + +.mytheme .v-formlayout-captioncell .v-caption { + padding-bottom: 0; +} + +.mytheme .v-formlayout-captioncell .v-caption-h2, .mytheme .v-formlayout-captioncell .v-caption-h3, .mytheme .v-formlayout-captioncell .v-caption-h4 { + height: 3em; +} + +.mytheme .v-formlayout-contentcell .v-checkbox, .mytheme .v-formlayout-contentcell .v-radiobutton { + font-weight: 400; +} + +.mytheme .v-formlayout-contentcell > .v-label-h2, .mytheme .v-formlayout-contentcell > .v-label-h3, .mytheme .v-formlayout-contentcell > .v-label-h4 { + position: absolute; + left: 0; + right: 0; + width: auto !important; + margin-top: -0.5em; + padding-bottom: 0.5em; + border-bottom: 1px solid #dfdfdf; +} + +.mytheme .v-formlayout.light > table { + padding: 0; +} + +.mytheme .v-formlayout.light > table > tbody > tr > td { + padding-top: 0; + height: 37px; + border-bottom: 1px solid #eaeaea; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="lastrow"] > td { + border-bottom: none; +} + +.mytheme .v-formlayout.light > table > tbody > tr > [class*="captioncell"] { + color: #7d7d7d; + text-align: right; + padding-left: 13px; + line-height: 37px; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] { + padding-right: 0; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect-input, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield-textfield { + width: 100%; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 0; + padding: 4px 7px; + + -webkit-box-shadow: none; + box-shadow: none; + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + background: transparent; + border: none; + color: inherit; +} + +.v-ie8 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield, .v-ie9 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield, .v-ie8 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea, .v-ie9 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea, .v-ie8 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input, .v-ie9 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input, .v-ie8 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input, .v-ie9 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input, .v-ie8 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea, .v-ie9 .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield.v-disabled, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea.v-disabled, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input.v-disabled, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input.v-disabled, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), none; + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), none; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect input:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield input:focus, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea:focus { + box-shadow: none; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textfield-prompt, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea-prompt, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-filterselect-prompt input, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-datefield-prompt input { + color: #a3a3a3; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-textarea, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-richtextarea { + height: auto; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h2, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + border-bottom: none; + left: 0; + right: 0; +} + +.mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme .v-formlayout.light > table > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + margin-top: 0; +} + +.mytheme .v-formlayout.light .v-richtextarea { + margin: 5px 0; +} + +.mytheme .v-formlayout.light .v-filterselect-button, .mytheme .v-formlayout.light .v-datefield-button { + border: none; +} + +.mytheme .v-formlayout.light .v-filterselect-button:active:after, .mytheme .v-formlayout.light .v-datefield-button:active:after { + display: none; +} + +.mytheme .v-formlayout.light .v-datefield-button { + right: 0; + left: auto; +} + +.mytheme .v-formlayout.light .v-checkbox { + margin-left: 7px; +} + +.mytheme .v-grid { + position: relative; +} + +.mytheme .v-grid-scroller { + position: absolute; + z-index: 1; + outline: none; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-grid-scroller-horizontal { + left: 0; + right: 0; + bottom: 0; + overflow-y: hidden; + -ms-overflow-y: hidden; +} + +.mytheme .v-grid-scroller-vertical { + right: 0; + top: 0; + bottom: 0; + overflow-x: hidden; + -ms-overflow-x: hidden; +} + +.mytheme .v-grid-tablewrapper { + position: absolute; + overflow: hidden; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + z-index: 5; +} + +.mytheme .v-grid-tablewrapper > table { + border-spacing: 0; + table-layout: fixed; + width: inherit; +} + +.mytheme .v-grid-header-deco, .mytheme .v-grid-footer-deco { + position: absolute; + right: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-grid-horizontal-scrollbar-deco { + position: absolute; + bottom: 0; + left: 0; + right: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-grid-header, .mytheme .v-grid-body, .mytheme .v-grid-footer { + position: absolute; + left: 0; + width: inherit; + z-index: 10; +} + +.mytheme .v-grid-header, .mytheme .v-grid-header-deco { + top: 0; +} + +.mytheme .v-grid-footer, .mytheme .v-grid-footer-deco { + bottom: 0; +} + +.mytheme .v-grid-body { + -ms-touch-action: none; + touch-action: none; + z-index: 0; + top: 0; +} + +.mytheme .v-grid-body .v-grid-row { + position: absolute; + top: 0; + left: 0; +} + +.mytheme .v-grid-row { + display: block; +} + +.v-ie8 .mytheme .v-grid-row, .v-ie9 .mytheme .v-grid-row { + float: left; + clear: left; + margin-top: 0; +} + +.mytheme .v-grid-row > td, .mytheme .v-grid-row > th { + background-color: white; +} + +.mytheme .v-grid-row { + width: inherit; +} + +.mytheme .v-grid-cell { + display: block; + float: left; + padding: 2px; + white-space: nowrap; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + font-size: 16px; +} + +.mytheme .v-grid-cell.frozen { + position: relative; + z-index: 1; +} + +.mytheme .v-grid-spacer { + position: absolute; + display: block; + background-color: white; +} + +.mytheme .v-grid-spacer > td { + width: 100%; + height: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.v-ie8 .mytheme .v-grid-spacer, .v-ie9 .mytheme .v-grid-spacer { + margin-top: 0; +} + +.mytheme .v-grid { + outline: none; +} + +.mytheme .v-grid-scroller-vertical, .mytheme .v-grid-scroller-horizontal { + border: 1px solid #d4d4d4; +} + +.mytheme .v-grid-scroller-vertical { + border-left: none; +} + +.mytheme .v-grid-scroller-horizontal { + border-top: none; +} + +.mytheme .v-grid-tablewrapper { + border: 1px solid #d4d4d4; +} + +.mytheme .v-grid .header-drag-table { + border-spacing: 0; + position: relative; + table-layout: fixed; + width: inherit; +} + +.mytheme .v-grid .header-drag-table .v-grid-header { + position: absolute; +} + +.mytheme .v-grid .header-drag-table .v-grid-header > .v-grid-cell { + border: 1px solid #d4d4d4; + margin-top: -10px; + opacity: 0.9; + filter: alpha(opacity=90); + z-index: 30000; +} + +.mytheme .v-grid .header-drag-table .v-grid-header > .v-grid-drop-marker { + background-color: #197de1; + position: absolute; + width: 3px; +} + +.mytheme .v-grid-sidebar.v-contextmenu { + -webkit-box-shadow: none; + box-shadow: none; + border-radius: 0; + position: absolute; + top: 0; + right: 0; + background-color: #fafafa; + border: 1px solid #d4d4d4; + padding: 0; + z-index: 5; +} + +.mytheme .v-grid-sidebar.v-contextmenu.v-grid-sidebar-popup { + right: auto; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-button { + background: transparent; + border: none; + color: inherit; + cursor: pointer; + outline: none; + padding: 0 4px; + text-align: right; + line-height: 1; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-button[disabled] { + cursor: default; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-button::-moz-focus-inner { + border: 0; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-button:after { + content: "\f0c9"; + display: block; + font-family: ThemeIcons, sans-serif; + font-size: 14px; +} + +.mytheme .v-grid-sidebar.v-contextmenu.closed { + border-radius: 0; +} + +.mytheme .v-grid-sidebar.v-contextmenu.open .v-grid-sidebar-button { + width: 100%; +} + +.mytheme .v-grid-sidebar.v-contextmenu.open .v-grid-sidebar-button:after { + content: "\f0c9"; + font-size: 14px; + line-height: 1; +} + +.v-ie .mytheme .v-grid-sidebar.v-contextmenu.open .v-grid-sidebar-button { + vertical-align: middle; +} + +.v-ie8 .mytheme .v-grid-sidebar.v-contextmenu.open .v-grid-sidebar-button:after { + vertical-align: middle; + text-align: center; + display: inline; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-content { + padding: 4px 0; + overflow-y: auto; + overflow-x: hidden; +} + +.mytheme .v-grid-sidebar.v-contextmenu .v-grid-sidebar-content .gwt-MenuBar .gwt-MenuItem .column-hiding-toggle { + text-shadow: none; +} + +.mytheme .v-grid-cell { + background-color: white; + padding: 0 18px; + line-height: 37px; + text-overflow: ellipsis; +} + +.mytheme .v-grid-cell > * { + line-height: 1.55; + vertical-align: middle; +} + +.mytheme .v-grid-cell > div { + display: inline-block; +} + +.mytheme .v-grid-cell.frozen { + -webkit-box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1); + box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1); + border-right: 1px solid #d4d4d4; +} + +.mytheme .v-grid-cell.frozen + th, .mytheme .v-grid-cell.frozen + td { + border-left: none; +} + +.mytheme .v-grid-row > td, .mytheme .v-grid-editor-cells > div { + border-left: 1px solid #d4d4d4; + border-bottom: 1px solid #d4d4d4; +} + +.mytheme .v-grid-row > td:first-child, .mytheme .v-grid-editor-cells > div:first-child { + border-left: none; +} + +.mytheme .v-grid-editor-cells.frozen > div { + -webkit-box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1); + box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1); + border-right: 1px solid #d4d4d4; + border-left: none; +} + +.mytheme .v-grid-row-stripe > td { + background-color: #f5f5f5; +} + +.mytheme .v-grid-row-selected > td { + background: #197de1; +} + +.mytheme .v-grid-row-focused > td { + +} + +.mytheme .v-grid-header th { + position: relative; + background-color: #fafafa; + font-size: 14px; + font-weight: inherit; + border-left: 1px solid #d4d4d4; + border-bottom: 1px solid #d4d4d4; + + text-align: left; +} + +.mytheme .v-grid-header th:first-child { + border-left: none; +} + +.mytheme .v-grid-header .sort-asc, .mytheme .v-grid-header .sort-desc { + padding-right: 35px; +} + +.mytheme .v-grid-header .sort-asc:after, .mytheme .v-grid-header .sort-desc:after { + font-family: ThemeIcons, sans-serif; + content: "\f0de" " " attr(sort-order); + position: absolute; + right: 18px; + font-size: 12px; +} + +.mytheme .v-grid-header .sort-desc:after { + content: "\f0dd" " " attr(sort-order); +} + +.mytheme .v-grid-column-resize-handle { + position: absolute; + width: 36px; + right: -18px; + top: 0px; + bottom: 0px; + cursor: col-resize; + z-index: 10; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.mytheme .v-grid-column-resize-simple-indicator { + position: absolute; + width: 3px; + top: 0px; + left: 18px; + z-index: 9001; + background: #fff; + box-shadow: 0px 0px 5px #000; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.mytheme .v-grid-footer td { + background-color: #fafafa; + font-size: 14px; + font-weight: inherit; + border-left: 1px solid #d4d4d4; + border-top: 1px solid #d4d4d4; + border-bottom: none; + +} + +.mytheme .v-grid-footer td:first-child { + border-left: none; +} + +.mytheme .v-grid-header .v-grid-cell, .mytheme .v-grid-footer .v-grid-cell { + overflow: visible; +} + +.mytheme .v-grid-column-header-content, .mytheme .v-grid-column-footer-content { + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + line-height: 37px; + vertical-align: baseline; +} + +.mytheme .v-grid-header-deco { + border-top: 1px solid #d4d4d4; + border-right: 1px solid #d4d4d4; + background-color: #fafafa; +} + +.mytheme .v-grid-footer-deco { + border-bottom: 1px solid #d4d4d4; + border-right: 1px solid #d4d4d4; + background-color: #fafafa; +} + +.mytheme .v-grid-horizontal-scrollbar-deco { + background-color: #fafafa; + border: 1px solid #d4d4d4; + border-top: none; +} + +.mytheme .v-grid-cell-focused { + position: relative; +} + +.mytheme .v-grid-cell-focused:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border: 2px solid #197de1; + display: none; + pointer-events: none; +} + +.ie8 .mytheme .v-grid-cell-focused:before, .ie9 .mytheme .v-grid-cell-focused:before, .ie10 .mytheme .v-grid-cell-focused:before { + content: url(data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==); +} + +.mytheme .v-grid:focus .v-grid-cell-focused:before { + display: block; +} + +.mytheme .v-grid.v-disabled:focus .v-grid-cell-focused:before { + display: none; +} + +.mytheme .v-grid-editor { + position: absolute; + z-index: 20; + overflow: hidden; + left: 0; + right: 0; + border: 1px solid #d4d4d4; + box-sizing: border-box; + -moz-box-sizing: border-box; + margin-top: -1px; + -webkit-box-shadow: 0 0 9px rgba(0, 0, 0, 0.2); + box-shadow: 0 0 9px rgba(0, 0, 0, 0.2); +} + +.mytheme .v-grid-editor.unbuffered .v-grid-editor-footer { + width: 100%; +} + +.mytheme .v-grid-editor-cells { + position: relative; + white-space: nowrap; +} + +.mytheme .v-grid-editor-cells.frozen { + z-index: 2; +} + +.mytheme .v-grid-editor-cells > div { + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + vertical-align: middle; + background: white; +} + +.mytheme .v-grid-editor-cells > div:first-child { + border-left: none; +} + +.mytheme .v-grid-editor-cells > div > * { + vertical-align: middle; + display: inline-block; +} + +.mytheme .v-grid-editor-cells > div .v-filterselect { + padding-left: 0; +} + +.mytheme .v-grid-editor-cells > div input[type="text"], .mytheme .v-grid-editor-cells > div input[type="text"].v-filterselect-input, .mytheme .v-grid-editor-cells > div input[type="password"] { + padding-left: 18px; +} + +.mytheme .v-grid-editor-cells > div input[type="text"]:not(.v-filterselect-input), .mytheme .v-grid-editor-cells > div input[type="password"] { + padding-right: 9px; +} + +.mytheme .v-grid-editor-cells > div input[type="checkbox"] { + margin-left: 18px; +} + +.mytheme .v-grid-editor-cells > div .v-textfield, .mytheme .v-grid-editor-cells > div .v-datefield, .mytheme .v-grid-editor-cells > div .v-filterselect { + min-width: 100%; + max-width: 100%; + min-height: 100%; + max-height: 100%; +} + +.v-ie8 .mytheme .v-grid-editor-cells > div .v-datefield-button { + margin-left: -37px; +} + +.v-ie8 .mytheme .v-grid-editor-cells > div .v-filterselect-button { + margin-left: -25px; +} + +.mytheme .v-grid-editor-cells > div .v-select, .mytheme .v-grid-editor-cells > div .v-select-select { + min-width: 100%; + max-width: 100%; +} + +.mytheme .v-grid-editor-cells > div.not-editable.v-grid-cell { + float: none; +} + +.mytheme .v-grid-editor-cells .error::before { + position: absolute; + display: block; + height: 0; + width: 0; + content: ""; + border-top: 5px solid red; + border-right: 5px solid transparent; +} + +.mytheme .v-grid-editor-cells .error, .mytheme .v-grid-editor-cells .error > input { + background-color: #fee; +} + +.mytheme .v-grid-editor-footer { + display: table; + height: 37px; + border-top: 1px solid #d4d4d4; + margin-top: -1px; + background: white; + padding: 0 5px; +} + +.mytheme .v-grid-editor-footer + .v-grid-editor-cells > div { + border-bottom: none; + border-top: 1px solid #d4d4d4; +} + +.mytheme .v-grid-editor-footer:first-child { + border-top: none; + margin-top: 0; + border-bottom: 1px solid #d4d4d4; + margin-bottom: -1px; +} + +.mytheme .v-grid-editor-message, .mytheme .v-grid-editor-buttons { + display: table-cell; + white-space: nowrap; + vertical-align: middle; +} + +.mytheme .v-grid-editor-message { + width: 100%; + position: relative; +} + +.mytheme .v-grid-editor-message > div { + position: absolute; + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + line-height: 37px; + top: 0; +} + +.mytheme .v-grid-editor-save { + margin-right: 4px; +} + +.mytheme .v-grid-spacer { + padding-left: 1px; +} + +.mytheme .v-grid-spacer > td { + display: block; + padding: 0; + background-color: white; + border-top: 1px solid #eeeeee; + border-bottom: 1px solid #d4d4d4; +} + +.mytheme .v-grid-spacer.stripe > td { + background-color: #f5f5f5; + border-top: 1px solid #e5e5e5; + border-bottom: 1px solid #d4d4d4; +} + +.mytheme .v-grid-spacer-deco-container { + border-top: 1px solid transparent; + position: relative; + top: 0; + z-index: 5; +} + +.mytheme .v-grid-spacer-deco { + top: 0; + left: 0; + width: 2px; + background-color: #197de1; + position: absolute; + height: 100%; + pointer-events: none; +} + +.ie8 .mytheme .v-grid-spacer-deco:before, .ie9 .mytheme .v-grid-spacer-deco:before, .ie10 .mytheme .v-grid-spacer-deco:before { + content: url(data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==); +} + +.mytheme .v-grid-cell > .v-progressbar { + width: 100%; +} + +.mytheme .v-grid { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + background-color: #fafafa; +} + +.mytheme .v-grid.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-grid-header .v-grid-cell { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-grid-header .v-grid-cell.dragged { + opacity: 0.5; + filter: alpha(opacity=50) ; + -webkit-transition: opacity 0.3s ease-in-out; + -moz-transition: opacity 0.3s ease-in-out; + transition: opacity 0.3s ease-in-out; +} + +.mytheme .v-grid-header .v-grid-cell.dragged-column-header { + margin-top: -19px; +} + +.mytheme .v-grid-footer .v-grid-cell { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-grid-header-deco { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); +} + +.mytheme .v-grid-footer-deco, .mytheme .v-grid-horizontal-scrollbar-deco { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); +} + +.mytheme .v-grid-row-selected > .v-grid-cell { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: #c8dbed; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); + border-color: #1d69b4; +} + +.mytheme .v-grid-row-selected > .v-grid-cell-focused:before { + border-color: #71b0ef; +} + +.mytheme .v-grid-editor { + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + border-color: #197de1; +} + +.mytheme .v-grid-editor-footer { + font-size: 14px; + padding: 0 6px; + background: #fafafa; + -webkit-animation: valo-grid-editor-footer-animate-in 200ms 120ms backwards; + -moz-animation: valo-grid-editor-footer-animate-in 200ms 120ms backwards; + animation: valo-grid-editor-footer-animate-in 200ms 120ms backwards; +} + +.mytheme .v-grid-editor-footer:first-child { + -webkit-animation: valo-grid-editor-footer-animate-in-alt 200ms 120ms backwards; + -moz-animation: valo-grid-editor-footer-animate-in-alt 200ms 120ms backwards; + animation: valo-grid-editor-footer-animate-in-alt 200ms 120ms backwards; +} + +.mytheme .v-grid-editor-cells { + z-index: 1; +} + +.mytheme .v-grid-editor-cells > div:before { + content: ""; + display: inline-block; + height: 100%; + vertical-align: middle; +} + +.mytheme .v-grid-editor-cells > div.not-editable.v-grid-cell { + float: none; +} + +.mytheme .v-grid-editor-cells > div .error::before { + border-top: 9px solid #ed473b; + border-right: 9px solid transparent; +} + +.mytheme .v-grid-editor-cells > div .error, .mytheme .v-grid-editor-cells > div .error > input { + background-color: #fffbfb; +} + +.mytheme .v-grid-editor-cells > div .v-textfield, .mytheme .v-grid-editor-cells > div .v-textfield-focus, .mytheme .v-grid-editor-cells > div .v-datefield, .mytheme .v-grid-editor-cells > div .v-datefield .v-textfield-focus, .mytheme .v-grid-editor-cells > div .v-filterselect-input, .mytheme .v-grid-editor-cells > div .v-filterselect-input:focus { + border: none; + border-radius: 0; + background: transparent; + -webkit-box-shadow: inset 0 1px 0 #f2f2f2; + box-shadow: inset 0 1px 0 #f2f2f2; +} + +.mytheme .v-grid-editor-cells > div input[type="text"].v-datefield-textfield { + padding-left: 44.4px; +} + +.v-ie8 .mytheme .v-grid-editor-cells > div .v-datefield-button { + margin-left: 0px; +} + +.v-ie8 .mytheme .v-grid-editor-cells > div .v-filterselect-button { + margin-left: 0px; +} + +.mytheme .v-grid-editor-cells > div .v-textfield-focus, .mytheme .v-grid-editor-cells > div .v-datefield .v-textfield-focus, .mytheme .v-grid-editor-cells > div .v-filterselect-input:focus { + position: relative; +} + +.mytheme .v-grid-editor-cells > div .v-select { + padding-left: 9px; + padding-right: 9px; +} + +.mytheme .v-grid-editor-cells > div .v-checkbox { + margin: 0 9px 0 18px; +} + +.mytheme .v-grid-editor-cells > div .v-checkbox > input[type="checkbox"] { + margin-left: 0; +} + +.mytheme .v-grid-editor-cells > div .v-checkbox > label { + white-space: nowrap; +} + +.mytheme .v-grid-editor-message > div:before { + display: inline-block; + color: #ed473b; + font-weight: 600; + width: 19px; + text-align: center; + content: "!"; +} + +.mytheme .v-grid-editor-save, .mytheme .v-grid-editor-cancel { + cursor: pointer; + color: #197de1; + text-decoration: underline; + font-weight: inherit; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; + font-weight: 400; + text-decoration: none; + border: none; + background: transparent; + padding: 6px 6px; + margin: 0; + outline: none; +} + +.mytheme .v-grid-editor-save:hover, .mytheme .v-grid-editor-cancel:hover { + color: #4396ea; +} + +.mytheme .v-grid-editor-save.v-disabled, .mytheme .v-grid-editor-cancel.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-grid-spacer { + margin-top: -1px; +} + +.mytheme .v-grid-sidebar.v-contextmenu.open .v-grid-sidebar-content { + margin: 0 0 2px; + padding: 4px 4px 2px; + overflow-y: auto; + overflow-x: hidden; +} + +.mytheme .v-grid-sidebar.v-contextmenu.closed { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); +} + +.mytheme .v-grid-scroller::-webkit-scrollbar { + border: none; +} + +.mytheme .v-grid-scroller::-webkit-scrollbar-thumb { + border-radius: 10px; + border: 4px solid transparent; + background: rgba(0, 0, 0, 0.3); + -webkit-background-clip: content-box; + background-clip: content-box; +} + +.mytheme .v-grid-scroller-vertical::-webkit-scrollbar-thumb { + min-height: 30px; +} + +.mytheme .v-grid-scroller-horizontal::-webkit-scrollbar-thumb { + min-width: 30px; +} + +.mytheme .v-textfield { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 4px; + padding: 4px 9px; + border: 1px solid #c5c5c5; + background: white; + color: #474747; + -webkit-box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + width: 185px; +} + +.v-ie8 .mytheme .v-textfield, .v-ie9 .mytheme .v-textfield { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-textfield.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-textfield:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-textfield[class*="prompt"] { + color: #a3a3a3; +} + +.mytheme .v-textfield-readonly { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-textfield-readonly:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-textfield-error { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-textfield-borderless { + border: none; + border-radius: 0; + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + color: inherit; +} + +.mytheme .v-textfield-borderless:focus { + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-textfield-borderless[class*="prompt"] { + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-textfield-tiny { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 28px; + border-radius: 4px; + padding: 3px 7px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + font-size: 12px; +} + +.v-ie8 .mytheme .v-textfield-tiny, .v-ie9 .mytheme .v-textfield-tiny { + line-height: 28px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-textfield-compact, .mytheme .v-textfield-small { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 31px; + border-radius: 4px; + padding: 3px 8px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; +} + +.v-ie8 .mytheme .v-textfield-compact, .v-ie9 .mytheme .v-textfield-compact, .v-ie8 .mytheme .v-textfield-small, .v-ie9 .mytheme .v-textfield-small { + line-height: 31px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-textfield-small { + font-size: 14px; +} + +.mytheme .v-textfield-large { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 44px; + border-radius: 4px; + padding: 5px 10px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + font-size: 20px; +} + +.v-ie8 .mytheme .v-textfield-large, .v-ie9 .mytheme .v-textfield-large { + line-height: 44px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-textfield-huge { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 59px; + border-radius: 4px; + padding: 7px 12px; + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + font-size: 26px; +} + +.v-ie8 .mytheme .v-textfield-huge, .v-ie9 .mytheme .v-textfield-huge { + line-height: 59px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-slot-inline-icon { + position: relative; +} + +.mytheme .v-caption-inline-icon { + padding: 0; +} + +.mytheme .v-caption-inline-icon .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon span.v-icon { + left: 1px; + bottom: 1px; + width: 37px; + line-height: 35px; + text-align: center; + font-size: 16px; +} + +.mytheme .v-caption-inline-icon img.v-icon { + left: 11px; + bottom: 11px; +} + +.mytheme .v-textfield-inline-icon { + padding-left: 37px; +} + +.mytheme .v-slot-inline-icon.v-slot-tiny { + position: relative; +} + +.mytheme .v-caption-inline-icon.v-caption-tiny { + padding: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-tiny .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-tiny .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon.v-caption-tiny span.v-icon { + left: 1px; + bottom: 1px; + width: 28px; + line-height: 26px; + text-align: center; + font-size: 12px; +} + +.mytheme .v-caption-inline-icon.v-caption-tiny img.v-icon { + left: 6px; + bottom: 6px; +} + +.mytheme .v-textfield-inline-icon.v-textfield-tiny { + padding-left: 28px; +} + +.mytheme .v-slot-inline-icon.v-slot-compact { + position: relative; +} + +.mytheme .v-caption-inline-icon.v-caption-compact { + padding: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-compact .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-compact .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon.v-caption-compact span.v-icon { + left: 1px; + bottom: 1px; + width: 31px; + line-height: 29px; + text-align: center; + font-size: 16px; +} + +.mytheme .v-caption-inline-icon.v-caption-compact img.v-icon { + left: 8px; + bottom: 8px; +} + +.mytheme .v-textfield-inline-icon.v-textfield-compact { + padding-left: 31px; +} + +.mytheme .v-slot-inline-icon.v-slot-small { + position: relative; +} + +.mytheme .v-caption-inline-icon.v-caption-small { + padding: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-small .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-small .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon.v-caption-small span.v-icon { + left: 1px; + bottom: 1px; + width: 31px; + line-height: 29px; + text-align: center; + font-size: 14px; +} + +.mytheme .v-caption-inline-icon.v-caption-small img.v-icon { + left: 8px; + bottom: 8px; +} + +.mytheme .v-textfield-inline-icon.v-textfield-small { + padding-left: 31px; +} + +.mytheme .v-slot-inline-icon.v-slot-large { + position: relative; +} + +.mytheme .v-caption-inline-icon.v-caption-large { + padding: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-large .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-large .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon.v-caption-large span.v-icon { + left: 1px; + bottom: 1px; + width: 44px; + line-height: 42px; + text-align: center; + font-size: 20px; +} + +.mytheme .v-caption-inline-icon.v-caption-large img.v-icon { + left: 14px; + bottom: 14px; +} + +.mytheme .v-textfield-inline-icon.v-textfield-large { + padding-left: 44px; +} + +.mytheme .v-slot-inline-icon.v-slot-huge { + position: relative; +} + +.mytheme .v-caption-inline-icon.v-caption-huge { + padding: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-huge .v-captiontext { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; + margin: 0; +} + +.mytheme .v-caption-inline-icon.v-caption-huge .v-icon { + position: absolute; + z-index: 10; +} + +.mytheme .v-caption-inline-icon.v-caption-huge span.v-icon { + left: 1px; + bottom: 1px; + width: 59px; + line-height: 57px; + text-align: center; + font-size: 26px; +} + +.mytheme .v-caption-inline-icon.v-caption-huge img.v-icon { + left: 22px; + bottom: 22px; +} + +.mytheme .v-textfield-inline-icon.v-textfield-huge { + padding-left: 59px; +} + +.mytheme .v-textfield-align-right { + text-align: right; +} + +.mytheme .v-textfield-align-center { + text-align: center; +} + +.mytheme .v-textarea { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 4px; + padding: 6px; + border: 1px solid #c5c5c5; + background: white; + color: #474747; + -webkit-box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + resize: none; + white-space: pre-wrap; + width: 185px; +} + +.v-ie8 .mytheme .v-textarea, .v-ie9 .mytheme .v-textarea { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-textarea.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-textarea:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-textarea[class*="prompt"] { + color: #a3a3a3; +} + +.v-ie8 .mytheme .v-textarea, .v-ie9 .mytheme .v-textarea { + line-height: inherit; + padding-top: 4px; + padding-bottom: 4px; +} + +.mytheme .v-textarea-readonly { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-textarea-readonly:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-textarea-error { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-textarea-borderless { + border: none; + border-radius: 0; + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + color: inherit; +} + +.mytheme .v-textarea-borderless:focus { + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-textarea-borderless[class*="prompt"] { + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-textarea-tiny { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 28px; + border-radius: 4px; + padding: 6px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + resize: none; + white-space: pre-wrap; + font-size: 12px; +} + +.v-ie8 .mytheme .v-textarea-tiny, .v-ie9 .mytheme .v-textarea-tiny { + line-height: 28px; + padding-top: 0; + padding-bottom: 0; +} + +.v-ie8 .mytheme .v-textarea-tiny, .v-ie9 .mytheme .v-textarea-tiny { + line-height: inherit; + padding-top: 3px; + padding-bottom: 3px; +} + +.mytheme .v-textarea-small { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 31px; + border-radius: 4px; + padding: 6px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + resize: none; + white-space: pre-wrap; + font-size: 14px; +} + +.v-ie8 .mytheme .v-textarea-small, .v-ie9 .mytheme .v-textarea-small { + line-height: 31px; + padding-top: 0; + padding-bottom: 0; +} + +.v-ie8 .mytheme .v-textarea-small, .v-ie9 .mytheme .v-textarea-small { + line-height: inherit; + padding-top: 3px; + padding-bottom: 3px; +} + +.mytheme .v-textarea-large { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 44px; + border-radius: 4px; + padding: 6px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + resize: none; + white-space: pre-wrap; + font-size: 20px; +} + +.v-ie8 .mytheme .v-textarea-large, .v-ie9 .mytheme .v-textarea-large { + line-height: 44px; + padding-top: 0; + padding-bottom: 0; +} + +.v-ie8 .mytheme .v-textarea-large, .v-ie9 .mytheme .v-textarea-large { + line-height: inherit; + padding-top: 5px; + padding-bottom: 5px; +} + +.mytheme .v-textarea-huge { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 59px; + border-radius: 4px; + padding: 6px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + resize: none; + white-space: pre-wrap; + font-size: 26px; +} + +.v-ie8 .mytheme .v-textarea-huge, .v-ie9 .mytheme .v-textarea-huge { + line-height: 59px; + padding-top: 0; + padding-bottom: 0; +} + +.v-ie8 .mytheme .v-textarea-huge, .v-ie9 .mytheme .v-textarea-huge { + line-height: inherit; + padding-top: 7px; + padding-bottom: 7px; +} + +.mytheme .v-textarea-align-right { + text-align: right; +} + +.mytheme .v-textarea-align-center { + text-align: center; +} + +.mytheme .v-datefield { + position: relative; + width: 185px; + height: 37px; + border-radius: 4px; +} + +.mytheme .v-datefield [class*="textfield"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 4px; + padding: 4px 9px; + border: 1px solid #c5c5c5; + background: white; + color: #474747; + -webkit-box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + padding-left: 44.4px; + width: 100%; + height: 100%; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-datefield [class*="textfield"], .v-ie9 .mytheme .v-datefield [class*="textfield"] { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-datefield [class*="textfield"].v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield [class*="textfield"]:focus { + outline: none; + -webkit-transition: none; + -moz-transition: none; + transition: none; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-datefield [class*="textfield"][class*="prompt"] { + color: #a3a3a3; +} + +.mytheme .v-datefield[class*="prompt"] > [class*="textfield"] { + color: #a3a3a3; +} + +.mytheme .v-datefield [class*="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + -webkit-appearance: none; + background: transparent; + padding: 0; + position: absolute; + z-index: 10; + width: 37px; + line-height: 35px; + text-align: center; + font: inherit; + outline: none; + margin: 0; + top: 1px; + bottom: 1px; + left: 1px; + border: none; + border-right: 1px solid #e4e4e4; + color: #a3a3a3; + border-radius: 3px 0 0 3px; +} + +.mytheme .v-datefield [class*="button"]:hover { + color: #474747; +} + +.mytheme .v-datefield [class*="button"]:before { + font-family: ThemeIcons; + content: "\f073"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-datefield [class*="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background-color: rgba(128, 128, 128, 0.2); + border-radius: inherit; +} + +.mytheme .v-datefield.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield.v-disabled [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield.v-disabled [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield.v-readonly [class*="textfield"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield.v-readonly [class*="textfield"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-datefield.v-readonly [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield.v-readonly [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-error .v-datefield-textfield { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-datefield-error .v-datefield-button { + color: #ed473b; + border-color: #ed473b; +} + +.mytheme .v-datefield-full { + width: 240px; +} + +.mytheme .v-datefield-day { + width: 185px; +} + +.mytheme .v-datefield-month { + width: 120px; +} + +.mytheme .v-datefield-year { + width: 104px; +} + +.mytheme .v-datefield-popup { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + margin-top: 5px !important; + margin-bottom: 5px !important; + margin-right: 5px !important; + cursor: default; + width: auto; +} + +.mytheme .v-datefield-popup[class*="animate-in"] { + -webkit-animation: valo-overlay-animate-in 120ms; + -moz-animation: valo-overlay-animate-in 120ms; + animation: valo-overlay-animate-in 120ms; +} + +.mytheme .v-datefield-popup[class*="animate-out"] { + -webkit-animation: valo-animate-out-fade 120ms; + -moz-animation: valo-animate-out-fade 120ms; + animation: valo-animate-out-fade 120ms; +} + +.mytheme .v-datefield-popup table { + border-collapse: collapse; + border-spacing: 0; + margin: 0 auto; +} + +.mytheme .v-datefield-popup td { + padding: 2px; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel { + font-size: 16px; + text-align: center; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel:focus { + outline: none; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 30px; + height: 26px; + border: 1px solid transparent; + line-height: 26px; + text-align: center; + font-size: 14px; + background: #fafafa; + border-radius: 2px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + cursor: pointer; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day:hover { + color: #197de1; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day-offmonth { + color: #a0a0a0; + background: transparent; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day-today { + color: #191919; + font-weight: 600; + border-color: #afafaf; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-selected, .mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-selected:hover { + color: #c8dbed; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + border: none; + font-weight: 600; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-focused { + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + position: relative; +} + +.v-ie8 .mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-focused { + border-color: #197de1; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-outside-range, .mytheme .v-datefield-popup .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-outside-range:hover { + color: #a0a0a0; + cursor: not-allowed; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-weekdays { + height: 26px; + color: rgba(133, 133, 133, 0.85); +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-weekdays strong { + font: inherit; + font-size: 14px; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-header { + white-space: nowrap; +} + +.mytheme .v-datefield-popup td[class*="year"] button, .mytheme .v-datefield-popup td[class*="month"] button { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + border: none; + background: transparent; + padding: 0; + margin: 0; + cursor: pointer; + color: transparent; + font-size: 0; + width: 19px; + height: 25px; + outline: none; + position: relative; + vertical-align: middle; +} + +.mytheme .v-datefield-popup td[class*="year"] button:before, .mytheme .v-datefield-popup td[class*="month"] button:before { + color: #a0a0a0; + font-size: 21px; + line-height: 24px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; +} + +.mytheme .v-datefield-popup td[class*="year"] button:hover:before, .mytheme .v-datefield-popup td[class*="month"] button:hover:before { + color: #197de1; +} + +.mytheme .v-datefield-popup td[class*="year"] button.outside-range, .mytheme .v-datefield-popup td[class*="month"] button.outside-range { + cursor: default; + opacity: 0.3; + filter: alpha(opacity=30.0) ; +} + +.mytheme .v-datefield-popup td[class*="year"] button.outside-range:hover:before, .mytheme .v-datefield-popup td[class*="month"] button.outside-range:hover:before { + color: #a0a0a0; +} + +.mytheme .v-datefield-popup .v-button-prevyear:before { + font-family: ThemeIcons; + content: "\f100"; +} + +.mytheme .v-datefield-popup .v-button-prevmonth:before { + font-family: ThemeIcons; + content: "\f104"; +} + +.mytheme .v-datefield-popup .v-button-nextyear:before { + font-family: ThemeIcons; + content: "\f101"; +} + +.mytheme .v-datefield-popup .v-button-nextmonth:before { + font-family: ThemeIcons; + content: "\f105"; +} + +.mytheme .v-datefield-popup td.v-datefield-calendarpanel-month { + width: 148px; + color: #197de1; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-year td.v-datefield-calendarpanel-month { + width: 74px; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-weeknumber, .mytheme .v-datefield-popup .v-datefield-calendarpanel-weekdays.v-datefield-calendarpanel-weeknumbers td:first-child { + width: 30px; + color: rgba(133, 133, 133, 0.85); + font-size: 14px; + display: inline-block; + text-align: left; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-weeknumber { + position: relative; +} + +.mytheme .v-datefield-popup .v-datefield-calendarpanel-weeknumbers .v-first:before { + content: ""; + position: absolute; + top: 38px; + bottom: 0; + left: 0; + width: 34px; + border-top: 1px solid #eaeaea; + border-right: 1px solid #eaeaea; + border-top-right-radius: 4px; + border-bottom-left-radius: 4px; + background: #fafafa; +} + +.mytheme .v-datefield-popup td.v-datefield-calendarpanel-time { + width: 100%; + font-size: 14px; +} + +.mytheme .v-datefield-popup td.v-datefield-calendarpanel-time .v-label { + display: inline; + margin: 0 0.1em; + font-weight: 400; +} + +.mytheme .v-datefield-calendarpanel { + font-size: 16px; + text-align: center; +} + +.mytheme .v-datefield-calendarpanel:focus { + outline: none; +} + +.mytheme .v-datefield-calendarpanel-day { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 30px; + height: 26px; + border: 1px solid transparent; + line-height: 26px; + text-align: center; + font-size: 14px; + background: #fafafa; + border-radius: 2px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + cursor: pointer; +} + +.mytheme .v-datefield-calendarpanel-day:hover { + color: #197de1; +} + +.mytheme .v-datefield-calendarpanel-day-offmonth { + color: #a0a0a0; + background: transparent; +} + +.mytheme .v-datefield-calendarpanel-day-today { + color: #191919; + font-weight: 600; + border-color: #afafaf; +} + +.mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-selected, .mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-selected:hover { + color: #c8dbed; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + border: none; + font-weight: 600; +} + +.mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-focused { + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + position: relative; +} + +.v-ie8 .mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-focused { + border-color: #197de1; +} + +.mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-outside-range, .mytheme .v-datefield-calendarpanel-day.v-datefield-calendarpanel-day-outside-range:hover { + color: #a0a0a0; + cursor: not-allowed; +} + +.mytheme .v-datefield-calendarpanel-weekdays { + height: 26px; + color: rgba(133, 133, 133, 0.85); +} + +.mytheme .v-datefield-calendarpanel-weekdays strong { + font: inherit; + font-size: 14px; +} + +.mytheme .v-datefield-calendarpanel-header { + white-space: nowrap; +} + +.mytheme td[class*="year"] button, .mytheme td[class*="month"] button { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + border: none; + background: transparent; + padding: 0; + margin: 0; + cursor: pointer; + color: transparent; + font-size: 0; + width: 19px; + height: 25px; + outline: none; + position: relative; + vertical-align: middle; +} + +.mytheme td[class*="year"] button:before, .mytheme td[class*="month"] button:before { + color: #a0a0a0; + font-size: 21px; + line-height: 24px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; +} + +.mytheme td[class*="year"] button:hover:before, .mytheme td[class*="month"] button:hover:before { + color: #197de1; +} + +.mytheme td[class*="year"] button.outside-range, .mytheme td[class*="month"] button.outside-range { + cursor: default; + opacity: 0.3; + filter: alpha(opacity=30.0) ; +} + +.mytheme td[class*="year"] button.outside-range:hover:before, .mytheme td[class*="month"] button.outside-range:hover:before { + color: #a0a0a0; +} + +.mytheme .v-button-prevyear:before { + font-family: ThemeIcons; + content: "\f100"; +} + +.mytheme .v-button-prevmonth:before { + font-family: ThemeIcons; + content: "\f104"; +} + +.mytheme .v-button-nextyear:before { + font-family: ThemeIcons; + content: "\f101"; +} + +.mytheme .v-button-nextmonth:before { + font-family: ThemeIcons; + content: "\f105"; +} + +.mytheme td.v-datefield-calendarpanel-month { + width: 148px; + color: #197de1; +} + +.mytheme .v-datefield-calendarpanel-year td.v-datefield-calendarpanel-month { + width: 74px; +} + +.mytheme .v-datefield-calendarpanel-weeknumber, .mytheme .v-datefield-calendarpanel-weekdays.v-datefield-calendarpanel-weeknumbers td:first-child { + width: 30px; + color: rgba(133, 133, 133, 0.85); + font-size: 14px; + display: inline-block; + text-align: left; +} + +.mytheme .v-datefield-calendarpanel-weeknumber { + position: relative; +} + +.mytheme .v-datefield-calendarpanel-weeknumbers .v-first:before { + content: ""; + position: absolute; + top: 38px; + bottom: 0; + left: 0; + width: 34px; + border-top: 1px solid #eaeaea; + border-right: 1px solid #eaeaea; + border-top-right-radius: 4px; + border-bottom-left-radius: 4px; + background: #fafafa; +} + +.mytheme td.v-datefield-calendarpanel-time { + width: 100%; + font-size: 14px; +} + +.mytheme td.v-datefield-calendarpanel-time .v-label { + display: inline; + margin: 0 0.1em; + font-weight: 400; +} + +.mytheme .v-datefield-borderless .v-datefield-textfield { + border: none; + border-radius: 0; + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + color: inherit; +} + +.mytheme .v-datefield-borderless .v-datefield-textfield:focus { + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield-borderless .v-datefield-textfield[class*="prompt"] { + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-borderless .v-datefield-button { + border: none; + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-align-right input { + text-align: right; +} + +.mytheme .v-datefield-align-center input { + text-align: center; +} + +.mytheme .v-datefield-tiny { + height: 28px; + border-radius: 4px; + font-size: 12px; +} + +.mytheme .v-datefield-tiny [class*="textfield"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 28px; + border-radius: 4px; + padding: 3px 7px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + padding-left: 33.6px; + width: 100%; + height: 100%; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-datefield-tiny [class*="textfield"], .v-ie9 .mytheme .v-datefield-tiny [class*="textfield"] { + line-height: 28px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-datefield-tiny [class*="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + -webkit-appearance: none; + background: transparent; + padding: 0; + position: absolute; + z-index: 10; + width: 28px; + line-height: 28px; + text-align: center; + font: inherit; + outline: none; + margin: 0; + border-radius: 4px 0 0 4px; +} + +.mytheme .v-datefield-tiny [class*="button"]:before { + font-family: ThemeIcons; + content: "\f073"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-datefield-tiny [class*="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-datefield-tiny.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-tiny.v-disabled [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-tiny.v-disabled [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-tiny.v-readonly [class*="textfield"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield-tiny.v-readonly [class*="textfield"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-datefield-tiny.v-readonly [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-tiny.v-readonly [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-compact, .mytheme .v-datefield-small { + height: 31px; + border-radius: 4px; +} + +.mytheme .v-datefield-compact [class*="textfield"], .mytheme .v-datefield-small [class*="textfield"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 31px; + border-radius: 4px; + padding: 3px 8px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + padding-left: 37.2px; + width: 100%; + height: 100%; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-datefield-compact [class*="textfield"], .v-ie9 .mytheme .v-datefield-compact [class*="textfield"], .v-ie8 .mytheme .v-datefield-small [class*="textfield"], .v-ie9 .mytheme .v-datefield-small [class*="textfield"] { + line-height: 31px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-datefield-compact [class*="button"], .mytheme .v-datefield-small [class*="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + -webkit-appearance: none; + background: transparent; + padding: 0; + position: absolute; + z-index: 10; + width: 31px; + line-height: 31px; + text-align: center; + font: inherit; + outline: none; + margin: 0; + border-radius: 4px 0 0 4px; +} + +.mytheme .v-datefield-compact [class*="button"]:before, .mytheme .v-datefield-small [class*="button"]:before { + font-family: ThemeIcons; + content: "\f073"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-datefield-compact [class*="button"]:active:after, .mytheme .v-datefield-small [class*="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-datefield-compact.v-disabled, .mytheme .v-datefield-small.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-compact.v-disabled [class*="button"], .mytheme .v-datefield-small.v-disabled [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-compact.v-disabled [class*="button"]:active:after, .mytheme .v-datefield-small.v-disabled [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-compact.v-readonly [class*="textfield"], .mytheme .v-datefield-small.v-readonly [class*="textfield"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield-compact.v-readonly [class*="textfield"]:focus, .mytheme .v-datefield-small.v-readonly [class*="textfield"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-datefield-compact.v-readonly [class*="button"], .mytheme .v-datefield-small.v-readonly [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-compact.v-readonly [class*="button"]:active:after, .mytheme .v-datefield-small.v-readonly [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-small { + font-size: 14px; +} + +.mytheme .v-datefield-large { + height: 44px; + border-radius: 4px; + font-size: 20px; +} + +.mytheme .v-datefield-large [class*="textfield"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 44px; + border-radius: 4px; + padding: 5px 10px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + padding-left: 52.8px; + width: 100%; + height: 100%; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-datefield-large [class*="textfield"], .v-ie9 .mytheme .v-datefield-large [class*="textfield"] { + line-height: 44px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-datefield-large [class*="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + -webkit-appearance: none; + background: transparent; + padding: 0; + position: absolute; + z-index: 10; + width: 44px; + line-height: 44px; + text-align: center; + font: inherit; + outline: none; + margin: 0; + border-radius: 4px 0 0 4px; +} + +.mytheme .v-datefield-large [class*="button"]:before { + font-family: ThemeIcons; + content: "\f073"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-datefield-large [class*="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-datefield-large.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-large.v-disabled [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-large.v-disabled [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-large.v-readonly [class*="textfield"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield-large.v-readonly [class*="textfield"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-datefield-large.v-readonly [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-large.v-readonly [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-huge { + height: 59px; + border-radius: 4px; + font-size: 26px; +} + +.mytheme .v-datefield-huge [class*="textfield"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 59px; + border-radius: 4px; + padding: 7px 12px; + + + + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + padding-left: 70.8px; + width: 100%; + height: 100%; + border-radius: inherit; +} + +.v-ie8 .mytheme .v-datefield-huge [class*="textfield"], .v-ie9 .mytheme .v-datefield-huge [class*="textfield"] { + line-height: 59px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-datefield-huge [class*="button"] { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + -webkit-appearance: none; + background: transparent; + padding: 0; + position: absolute; + z-index: 10; + width: 59px; + line-height: 59px; + text-align: center; + font: inherit; + outline: none; + margin: 0; + border-radius: 4px 0 0 4px; +} + +.mytheme .v-datefield-huge [class*="button"]:before { + font-family: ThemeIcons; + content: "\f073"; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-datefield-huge [class*="button"]:active:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-datefield-huge.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-datefield-huge.v-disabled [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-huge.v-disabled [class*="button"]:active:after { + display: none; +} + +.mytheme .v-datefield-huge.v-readonly [class*="textfield"] { + background: #fafafa; + color: #464646; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-datefield-huge.v-readonly [class*="textfield"]:focus { + box-shadow: none; + border-color: #c5c5c5; +} + +.mytheme .v-datefield-huge.v-readonly [class*="button"] { + cursor: default; + pointer-events: none; +} + +.mytheme .v-datefield-huge.v-readonly [class*="button"]:active:after { + display: none; +} + +.mytheme .v-inline-datefield-calendarpanel { + font-size: 16px; + text-align: center; +} + +.mytheme .v-inline-datefield-calendarpanel:focus { + outline: none; +} + +.mytheme .v-inline-datefield-calendarpanel-day { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 30px; + height: 26px; + border: 1px solid transparent; + line-height: 26px; + text-align: center; + font-size: 14px; + background: #fafafa; + border-radius: 2px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + cursor: pointer; +} + +.mytheme .v-inline-datefield-calendarpanel-day:hover { + color: #197de1; +} + +.mytheme .v-inline-datefield-calendarpanel-day-offmonth { + color: #a0a0a0; + background: transparent; +} + +.mytheme .v-inline-datefield-calendarpanel-day-today { + color: #191919; + font-weight: 600; + border-color: #afafaf; +} + +.mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-selected, .mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-selected:hover { + color: #c8dbed; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + border: none; + font-weight: 600; +} + +.mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-focused { + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + position: relative; +} + +.v-ie8 .mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-focused { + border-color: #197de1; +} + +.mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-outside-range, .mytheme .v-inline-datefield-calendarpanel-day.v-inline-datefield-calendarpanel-day-outside-range:hover { + color: #a0a0a0; + cursor: not-allowed; +} + +.mytheme .v-inline-datefield-calendarpanel-weekdays { + height: 26px; + color: rgba(133, 133, 133, 0.85); +} + +.mytheme .v-inline-datefield-calendarpanel-weekdays strong { + font: inherit; + font-size: 14px; +} + +.mytheme .v-inline-datefield-calendarpanel-header { + white-space: nowrap; +} + +.mytheme td[class*="year"] button, .mytheme td[class*="month"] button { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + border: none; + background: transparent; + padding: 0; + margin: 0; + cursor: pointer; + color: transparent; + font-size: 0; + width: 19px; + height: 25px; + outline: none; + position: relative; + vertical-align: middle; +} + +.mytheme td[class*="year"] button:before, .mytheme td[class*="month"] button:before { + color: #a0a0a0; + font-size: 21px; + line-height: 24px; + -webkit-transition: color 200ms; + -moz-transition: color 200ms; + transition: color 200ms; +} + +.mytheme td[class*="year"] button:hover:before, .mytheme td[class*="month"] button:hover:before { + color: #197de1; +} + +.mytheme td[class*="year"] button.outside-range, .mytheme td[class*="month"] button.outside-range { + cursor: default; + opacity: 0.3; + filter: alpha(opacity=30.0) ; +} + +.mytheme td[class*="year"] button.outside-range:hover:before, .mytheme td[class*="month"] button.outside-range:hover:before { + color: #a0a0a0; +} + +.mytheme .v-button-prevyear:before { + font-family: ThemeIcons; + content: "\f100"; +} + +.mytheme .v-button-prevmonth:before { + font-family: ThemeIcons; + content: "\f104"; +} + +.mytheme .v-button-nextyear:before { + font-family: ThemeIcons; + content: "\f101"; +} + +.mytheme .v-button-nextmonth:before { + font-family: ThemeIcons; + content: "\f105"; +} + +.mytheme td.v-inline-datefield-calendarpanel-month { + width: 148px; + color: #197de1; +} + +.mytheme .v-inline-datefield-calendarpanel-year td.v-inline-datefield-calendarpanel-month { + width: 74px; +} + +.mytheme .v-inline-datefield-calendarpanel-weeknumber, .mytheme .v-inline-datefield-calendarpanel-weekdays.v-inline-datefield-calendarpanel-weeknumbers td:first-child { + width: 30px; + color: rgba(133, 133, 133, 0.85); + font-size: 14px; + display: inline-block; + text-align: left; +} + +.mytheme .v-inline-datefield-calendarpanel-weeknumber { + position: relative; +} + +.mytheme .v-inline-datefield-calendarpanel-weeknumbers .v-first:before { + content: ""; + position: absolute; + top: 38px; + bottom: 0; + left: 0; + width: 34px; + border-top: 1px solid #eaeaea; + border-right: 1px solid #eaeaea; + border-top-right-radius: 4px; + border-bottom-left-radius: 4px; + background: #fafafa; +} + +.mytheme td.v-inline-datefield-calendarpanel-time { + width: 100%; + font-size: 14px; +} + +.mytheme td.v-inline-datefield-calendarpanel-time .v-label { + display: inline; + margin: 0 0.1em; + font-weight: 400; +} + +.mytheme .v-inline-datefield-calendarpanel { + position: relative; + background: white; + padding: 6px; +} + +.mytheme .v-gridlayout-margin-top { + padding-top: 37px; +} + +.mytheme .v-gridlayout-margin-bottom { + padding-bottom: 37px; +} + +.mytheme .v-gridlayout-margin-left { + padding-left: 37px; +} + +.mytheme .v-gridlayout-margin-right { + padding-right: 37px; +} + +.mytheme .v-gridlayout-spacing-on { + padding-left: 12px; + padding-top: 12px; +} + +.mytheme .v-menubar { + position: relative; + text-align: center; + white-space: nowrap; + outline: none; + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + cursor: default; + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + text-align: left; + line-height: 35px; +} + +.mytheme .v-menubar:after { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; +} + +.mytheme .v-menubar:focus:after { + -webkit-transition: none; + -moz-transition: none; + transition: none; +} + +.mytheme .v-menubar.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-menubar.v-disabled:after { + display: none; +} + +.mytheme .v-menubar:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-menubar:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-menubar > .v-menubar-menuitem { + padding: 0 14px; +} + +.mytheme .v-menubar > .v-menubar-menuitem[class*="-icon-only"] { + width: 37px; +} + +.mytheme .v-menubar:active:after { + background: transparent; +} + +.mytheme .v-menubar > .v-menubar-menuitem { + position: relative; + z-index: 1; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + height: 37px; + padding: 0 15px; + color: inherit; + font-weight: 400; + + cursor: pointer; + border-radius: 0; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + border-width: 0 1px 0 0; + border-color: inherit; + height: 100%; + line-height: inherit; + vertical-align: top; + text-align: center; +} + +.mytheme .v-menubar > .v-menubar-menuitem:first-child { + border-left-width: 0; + border-radius: 3px 0 0 3px; +} + +.mytheme .v-menubar > .v-menubar-menuitem:last-child { + border-radius: 0 3px 3px 0; + border-right-width: 0; +} + +.mytheme .v-menubar > .v-menubar-menuitem:first-child:last-child { + border-radius: 3px; +} + +.mytheme .v-menubar > .v-menubar-menuitem:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-menubar > .v-menubar-menuitem:hover { + zoom: 1; +} + +.mytheme .v-menubar > .v-menubar-menuitem:hover:before { + background-color: rgba(186, 186, 186, 0.1); + border: none; +} + +.mytheme .v-menubar > .v-menubar-menuitem:active:before { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-menubar > .v-menubar-menuitem .v-icon { + margin: 0 4px 0 -4px; + cursor: inherit; +} + +.mytheme .v-menubar > .v-menubar-menuitem[class*="-icon-only"] { + width: 37px; + padding: 0; +} + +.mytheme .v-menubar > .v-menubar-menuitem[class*="-icon-only"] .v-icon { + margin: 0; +} + +.mytheme .v-menubar > .v-menubar-menuitem-checked { + -webkit-box-shadow: none; + box-shadow: none; + background-color: #ededed; + background-image: -webkit-linear-gradient(bottom, #ededed 2%, #e9e9e9 98%); + background-image: linear-gradient(to top,#ededed 2%, #e9e9e9 98%); + color: #181818; +} + +.mytheme .v-disabled > .v-menubar-menuitem, .mytheme .v-menubar > .v-menubar-menuitem-disabled { + cursor: default; +} + +.mytheme .v-disabled > .v-menubar-menuitem:before, .mytheme .v-menubar > .v-menubar-menuitem-disabled:before { + display: none; +} + +.mytheme .v-menubar-menuitem-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-menubar > .v-menubar-menuitem-selected { + color: #ecf2f8; + + + + border-radius: 0; + border: 1px solid #1362b1; + border-top-color: #156ab3; + border-bottom-color: #1156a8; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + -webkit-box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca; + box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); + border-top-width: 0; + border-left-width: 0; + border-bottom-width: 0; + z-index: 2; +} + +.mytheme .v-menubar > .v-menubar-menuitem-selected:hover:before { + background: none; +} + +.mytheme .v-menubar .v-menubar-submenu-indicator { + display: none; +} + +.mytheme .v-menubar .v-menubar-submenu-indicator + .v-menubar-menuitem-caption:after { + font-family: ThemeIcons; + content: "\f078"; + font-size: 0.7em; + vertical-align: 0.15em; + margin: 0 -0.2em 0 0.5em; + opacity: 0.5; +} + +.mytheme .v-menubar .v-menubar-submenu-indicator + .v-menubar-menuitem-caption:empty:after { + margin-left: -0.2em; +} + +.mytheme .v-menubar-popup { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + padding: 4px 4px; + margin: 5px 0 0 1px !important; +} + +.mytheme .v-menubar-popup[class*="animate-in"] { + -webkit-animation: valo-overlay-animate-in 120ms; + -moz-animation: valo-overlay-animate-in 120ms; + animation: valo-overlay-animate-in 120ms; +} + +.mytheme .v-menubar-popup[class*="animate-out"] { + -webkit-animation: valo-animate-out-fade 120ms; + -moz-animation: valo-animate-out-fade 120ms; + animation: valo-animate-out-fade 120ms; +} + +.mytheme .v-menubar-popup .v-menubar-submenu { + outline: none; +} + +.mytheme .v-menubar-popup .v-menubar-menuitem { + display: block; + cursor: pointer; + line-height: 27px; + padding: 0 20px 0 10px; + border-radius: 3px; + font-weight: 400; + white-space: nowrap; + position: relative; + padding-left: 32px; + padding-right: 37px; + position: relative; +} + +.mytheme .v-menubar-popup .v-menubar-menuitem:active:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background: #0957a6; + opacity: 0.15; + filter: alpha(opacity=15.0) ; + pointer-events: none; + border-radius: inherit; +} + +.mytheme .v-menubar-popup .v-menubar-menuitem .v-icon { + max-height: 27px; + margin-right: 5px; + min-width: 1em; +} + +.mytheme .v-menubar-popup .v-menubar-submenu-indicator { + display: none; +} + +.mytheme .v-menubar-popup .v-menubar-submenu-indicator + .v-menubar-menuitem-caption:after { + position: absolute; + right: 10px; + font-family: ThemeIcons; + content: "\f054"; + line-height: 29px; +} + +.mytheme .v-menubar-popup .v-menubar-menuitem-selected { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-menubar-popup .v-menubar-separator { + display: block; + margin: 4px 0; + height: 0; + overflow: hidden; + border-bottom: 1px solid #e4e4e4; +} + +.mytheme .v-menubar-popup [class*="checked"] .v-menubar-menuitem-caption:before { + content: "\f00c"; + font-family: ThemeIcons; + position: absolute; + left: 10px; +} + +.mytheme .v-menubar-popup [class*="unchecked"] .v-menubar-menuitem-caption:before { + content: ""; +} + +.mytheme .v-menubar-popup [class*="disabled"] { + cursor: default; +} + +.mytheme .v-menubar-small { + height: 31px; + padding: 0 14px; + + font-weight: 400; + + cursor: default; + border-radius: 4px; + padding: 0; + text-align: left; + line-height: 29px; + font-size: 14px; +} + +.mytheme .v-menubar-small:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-menubar-small > .v-menubar-menuitem { + padding: 0 12px; +} + +.mytheme .v-menubar-small > .v-menubar-menuitem[class*="-icon-only"] { + width: 31px; +} + +.mytheme .v-menubar-borderless { + border: none; + border-radius: 0; + padding: 1px; + -webkit-box-shadow: none; + box-shadow: none; + text-shadow: none; + background: transparent; + color: inherit; +} + +.mytheme .v-menubar-borderless:focus:after { + display: none; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem { + -webkit-box-shadow: none; + box-shadow: none; + border: none; + margin-right: 1px; + border-radius: 4px; + color: #197de1; + padding: 0 12px; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem:first-child, .mytheme .v-menubar-borderless .v-menubar-menuitem:last-child, .mytheme .v-menubar-borderless .v-menubar-menuitem:first-child:last-child { + border-radius: 4px; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem:before { + content: none; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem:hover { + color: #4396ea; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem:active { + color: inherit; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem-checked, .mytheme .v-menubar-borderless .v-menubar-menuitem-checked:first-child { + border: 1px solid #c5c5c5; + color: #197de1; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem-checked .v-menubar-menuitem-caption, .mytheme .v-menubar-borderless .v-menubar-menuitem-checked:first-child .v-menubar-menuitem-caption { + position: relative; + top: -1px; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem-selected { + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem-selected:hover { + color: #ecf2f8; +} + +.mytheme .v-menubar-borderless .v-menubar-menuitem-disabled, .mytheme .v-menubar-borderless .v-menubar-menuitem-disabled:hover { + color: inherit; +} + +.mytheme .v-radiobutton { + position: relative; + line-height: 19px; + white-space: nowrap; +} + +.mytheme .v-radiobutton.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-radiobutton { + padding-left: 25px; +} + +:root .mytheme .v-radiobutton label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-radiobutton > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-radiobutton > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-radiobutton > input ~ label:before, :root .mytheme .v-radiobutton > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 19px; + height: 19px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 13px; + text-align: center; +} + +:root .mytheme .v-radiobutton > input ~ label:before { + height: 18.5px; + padding: 0 9px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 19px; +} + +:root .mytheme .v-radiobutton > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-radiobutton > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-radiobutton > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-radiobutton > .v-icon, .mytheme .v-radiobutton > label .v-icon { + margin: 0 6px 0 3px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-radiobutton.v-disabled > label, .mytheme .v-radiobutton.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-radiobutton.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-radiobutton.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-radiobutton.v-readonly > label, .mytheme .v-radiobutton.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-radiobutton.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-radiobutton.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-radiobutton.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +:root .mytheme .v-radiobutton > input:checked ~ label:after { + width: 7px; + height: 7px; + top: 6px; + left: 6px; + background: #197de1; +} + +:root .mytheme .v-radiobutton > input ~ label:before, :root .mytheme .v-radiobutton > input ~ label:after { + border-radius: 50%; + content: ""; +} + +.mytheme .v-select-optiongroup .v-radiobutton, .mytheme .v-select-optiongroup .v-checkbox { + display: block; + margin: 9px 16px 0 0; +} + +.mytheme .v-select-optiongroup .v-radiobutton:first-child, .mytheme .v-select-optiongroup .v-checkbox:first-child { + margin-top: 6px; +} + +.mytheme .v-select-optiongroup .v-radiobutton:last-child, .mytheme .v-select-optiongroup .v-checkbox:last-child { + margin-bottom: 6px; +} + +.mytheme .v-select-optiongroup.v-has-width label { + white-space: normal; +} + +.mytheme .v-select-optiongroup-small { + font-size: 14px; +} + +.mytheme .v-select-optiongroup-small .v-checkbox { + position: relative; + line-height: 16px; + white-space: nowrap; +} + +.mytheme .v-select-optiongroup-small .v-checkbox.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox { + padding-left: 21px; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input ~ label:before, :root .mytheme .v-select-optiongroup-small .v-checkbox > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 16px; + height: 16px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 11px; + text-align: center; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input ~ label:before { + height: 15.5px; + padding: 0 7px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 16px; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-select-optiongroup-small .v-checkbox > .v-icon, .mytheme .v-select-optiongroup-small .v-checkbox > label .v-icon { + margin: 0 5px 0 3px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-select-optiongroup-small .v-checkbox.v-disabled > label, .mytheme .v-select-optiongroup-small .v-checkbox.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-small .v-checkbox.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-select-optiongroup-small .v-checkbox.v-readonly > label, .mytheme .v-select-optiongroup-small .v-checkbox.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-select-optiongroup-small .v-checkbox.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-select-optiongroup-small .v-checkbox.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton { + position: relative; + line-height: 16px; + white-space: nowrap; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton { + padding-left: 21px; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:before, :root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 16px; + height: 16px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 11px; + text-align: center; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:before { + height: 15.5px; + padding: 0 7px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 16px; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton > .v-icon, .mytheme .v-select-optiongroup-small .v-radiobutton > label .v-icon { + margin: 0 5px 0 3px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton.v-disabled > label, .mytheme .v-select-optiongroup-small .v-radiobutton.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton.v-readonly > label, .mytheme .v-select-optiongroup-small .v-radiobutton.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input:checked ~ label:after { + width: 6px; + height: 6px; + top: 5px; + left: 5px; + background: #197de1; +} + +:root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:before, :root .mytheme .v-select-optiongroup-small .v-radiobutton > input ~ label:after { + border-radius: 50%; + content: ""; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton, .mytheme .v-select-optiongroup-small .v-checkbox { + display: block; + margin: 8px 16px 0 0; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton:first-child, .mytheme .v-select-optiongroup-small .v-checkbox:first-child { + margin-top: 5px; +} + +.mytheme .v-select-optiongroup-small .v-radiobutton:last-child, .mytheme .v-select-optiongroup-small .v-checkbox:last-child { + margin-bottom: 5px; +} + +.mytheme .v-select-optiongroup-small.v-has-width label { + white-space: normal; +} + +.mytheme .v-select-optiongroup-large { + font-size: 20px; +} + +.mytheme .v-select-optiongroup-large .v-checkbox { + position: relative; + line-height: 22px; + white-space: nowrap; +} + +.mytheme .v-select-optiongroup-large .v-checkbox.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox { + padding-left: 29px; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input ~ label:before, :root .mytheme .v-select-optiongroup-large .v-checkbox > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 22px; + height: 22px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 15px; + text-align: center; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input ~ label:before { + height: 22px; + padding: 0 10px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 22px; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-select-optiongroup-large .v-checkbox > .v-icon, .mytheme .v-select-optiongroup-large .v-checkbox > label .v-icon { + margin: 0 7px 0 4px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-select-optiongroup-large .v-checkbox.v-disabled > label, .mytheme .v-select-optiongroup-large .v-checkbox.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-large .v-checkbox.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-select-optiongroup-large .v-checkbox.v-readonly > label, .mytheme .v-select-optiongroup-large .v-checkbox.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-select-optiongroup-large .v-checkbox.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-select-optiongroup-large .v-checkbox.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton { + position: relative; + line-height: 22px; + white-space: nowrap; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton.v-has-width label { + white-space: normal; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton { + padding-left: 29px; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton label { + -webkit-tap-highlight-color: transparent; + -webkit-touch-callout: none; + cursor: pointer; + display: inline-block; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input { + position: absolute; + clip: rect(0, 0, 0, 0); + left: 0.2em; + top: 0.2em; + z-index: 0; + margin: 0; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input:focus ~ label:before { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5), inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:before, :root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:after { + content: ""; + display: inline-block; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 22px; + height: 22px; + position: absolute; + top: 0; + left: 0; + border-radius: 4px; + font-size: 15px; + text-align: center; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:before { + height: 22px; + padding: 0 10px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + height: 22px; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:after { + content: "\f00c"; + font-family: ThemeIcons; + color: transparent; + -webkit-transition: color 100ms; + -moz-transition: color 100ms; + transition: color 100ms; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input:active ~ label:after { + background-color: rgba(125, 125, 125, 0.2); +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input:checked ~ label:after { + color: #197de1; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton > .v-icon, .mytheme .v-select-optiongroup-large .v-radiobutton > label .v-icon { + margin: 0 7px 0 4px; + min-width: 1em; + cursor: pointer; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton.v-disabled > label, .mytheme .v-select-optiongroup-large .v-radiobutton.v-disabled > .v-icon { + cursor: default; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton.v-disabled > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton.v-disabled > input:active ~ label:after { + background: transparent; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton.v-readonly > label, .mytheme .v-select-optiongroup-large .v-radiobutton.v-readonly > .v-icon { + cursor: default; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton.v-readonly > label > .v-icon { + cursor: default; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton.v-readonly > input:active ~ label:after { + background: transparent; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton.v-readonly > input ~ label:after { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input:checked ~ label:after { + width: 8px; + height: 8px; + top: 7px; + left: 7px; + background: #197de1; +} + +:root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:before, :root .mytheme .v-select-optiongroup-large .v-radiobutton > input ~ label:after { + border-radius: 50%; + content: ""; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton, .mytheme .v-select-optiongroup-large .v-checkbox { + display: block; + margin: 11px 16px 0 0; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton:first-child, .mytheme .v-select-optiongroup-large .v-checkbox:first-child { + margin-top: 7px; +} + +.mytheme .v-select-optiongroup-large .v-radiobutton:last-child, .mytheme .v-select-optiongroup-large .v-checkbox:last-child { + margin-bottom: 7px; +} + +.mytheme .v-select-optiongroup-large.v-has-width label { + white-space: normal; +} + +.mytheme .v-select-optiongroup-horizontal { + white-space: nowrap; +} + +.mytheme .v-select-optiongroup-horizontal .v-radiobutton, .mytheme .v-select-optiongroup-horizontal .v-checkbox { + display: inline-block; +} + +.mytheme .v-select-optiongroup-horizontal.v-has-width { + white-space: normal; +} + +.mytheme .v-select-optiongroup-horizontal.v-has-width label { + white-space: nowrap; +} + +.mytheme .v-link { + cursor: pointer; + color: #197de1; + text-decoration: underline; + font-weight: inherit; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-link:hover { + color: #4396ea; +} + +.mytheme .v-link.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-link a { + cursor: inherit; + color: inherit; + text-decoration: inherit; + -webkit-transition: inherit; + -moz-transition: inherit; + transition: inherit; +} + +.mytheme .v-link .v-icon { + cursor: inherit; +} + +.mytheme .v-link-small { + font-size: 14px; +} + +.mytheme .v-link-large { + font-size: 20px; +} + +.mytheme .v-window { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + -webkit-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1), 0 16px 80px -6px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1), 0 16px 80px -6px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.09098); + padding: 0; + min-width: 148px !important; + min-height: 37px !important; + white-space: nowrap; + overflow: hidden !important; + -webkit-transition: width 200ms, height 200ms, top 200ms, left 200ms; + -moz-transition: width 200ms, height 200ms, top 200ms, left 200ms; + transition: width 200ms, height 200ms, top 200ms, left 200ms; +} + +.mytheme .v-window[class*="animate-in"] { + -webkit-animation: valo-animate-in-fade 140ms; + -moz-animation: valo-animate-in-fade 140ms; + animation: valo-animate-in-fade 140ms; +} + +.mytheme .v-window[class*="animate-out"] { + -webkit-animation: valo-animate-out-scale-down-fade 100ms; + -moz-animation: valo-animate-out-scale-down-fade 100ms; + animation: valo-animate-out-scale-down-fade 100ms; +} + +.mytheme .v-window.v-window-animate-in { + -webkit-transition: none; + -moz-transition: none; + transition: none; +} + +.mytheme .v-window-modalitycurtain { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + background-color: #222; + background-image: -webkit-radial-gradient(50% 50%, circle, #222, #0e0e0e); + background-image: radial-gradient( circle at 50% 50%, #222, #0e0e0e); + opacity: 0.72; + filter: alpha(opacity=72) ; + -webkit-animation: valo-animate-in-fade 400ms 100ms backwards; + -moz-animation: valo-animate-in-fade 400ms 100ms backwards; + animation: valo-animate-in-fade 400ms 100ms backwards; +} + +.v-op12 .mytheme .v-window-modalitycurtain { + -webkit-animation: none; + -moz-animation: none; + animation: none; +} + +.mytheme .v-window-draggingCurtain { + position: fixed !important; +} + +.mytheme .v-window-resizingCurtain + .v-window, .mytheme .v-window-draggingCurtain + .v-window { + -webkit-transition: none; + -moz-transition: none; + transition: none; +} + +.mytheme .v-window-outerheader { + cursor: move; + position: absolute; + z-index: 2; + top: 0; + left: 0; + right: 0; + -webkit-transform: translatez(0); + -moz-transform: translatez(0); + -ms-transform: translatez(0); + -o-transform: translatez(0); + transform: translatez(0); +} + +.mytheme .v-window-outerheader:after { + content: ""; + position: absolute; + bottom: -1px; + right: 0; + left: 0; + height: 0; + border-top: 1px solid #dfdfdf; + border-color: rgba(197, 197, 197, 0.5); +} + +.mytheme .v-window-header { + line-height: 36px; + padding-left: 12px; + margin-right: 74px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: #7e7e7e; +} + +.mytheme .v-window-restorebox-disabled ~ .v-window-closebox ~ .v-window-header, .mytheme .v-window-maximizebox-disabled ~ .v-window-closebox ~ .v-window-header { + margin-right: 37px; +} + +.mytheme .v-window-restorebox-disabled ~ .v-window-closebox-disabled ~ .v-window-header, .mytheme .v-window-maximizebox-disabled ~ .v-window-closebox-disabled ~ .v-window-header { + margin-right: 12px; +} + +.mytheme .v-window-closebox, .mytheme .v-window-maximizebox, .mytheme .v-window-restorebox { + position: absolute; + z-index: 3; + top: 0; + right: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 33px; + height: 36px; + background-color: white; + line-height: 34px; + text-align: center; + cursor: pointer; + font-size: 21px; + color: #999999; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-window-closebox:focus, .mytheme .v-window-maximizebox:focus, .mytheme .v-window-restorebox:focus { + outline: none; +} + +.mytheme .v-window-closebox:hover, .mytheme .v-window-maximizebox:hover, .mytheme .v-window-restorebox:hover { + opacity: 1; + filter: none ; + color: #197de1; +} + +.mytheme .v-window-closebox:active, .mytheme .v-window-maximizebox:active, .mytheme .v-window-restorebox:active { + color: inherit; +} + +.mytheme .v-window-closebox { + padding-right: 4px; + border-radius: 0 4px 0 4px; +} + +.mytheme .v-window-closebox:before { + content: "\00d7"; +} + +.mytheme .v-window-maximizebox, .mytheme .v-window-restorebox { + right: 33px; + padding-left: 4px; + border-radius: 0 0 0 4px; +} + +.mytheme .v-window-maximizebox + .v-window-closebox, .mytheme .v-window-restorebox + .v-window-closebox { + border-bottom-left-radius: 0; +} + +.mytheme .v-window-closebox-disabled, .mytheme .v-window-resizebox-disabled, .mytheme .v-window-restorebox-disabled, .mytheme .v-window-maximizebox-disabled { + display: none; +} + +.mytheme .v-window-closebox-disabled + .v-window-closebox, .mytheme .v-window-resizebox-disabled + .v-window-closebox, .mytheme .v-window-restorebox-disabled + .v-window-closebox, .mytheme .v-window-maximizebox-disabled + .v-window-closebox { + width: 37px; + padding-right: 0; + border-bottom-left-radius: 4px; +} + +.mytheme .v-window-maximizebox:before { + content: "+"; +} + +.mytheme .v-window-restorebox:before { + content: "\2013"; +} + +.mytheme .v-window > .popupContent, .mytheme .v-window-wrap, .mytheme .v-window-contents, .mytheme .v-window-contents > .v-scrollable { + height: 100%; +} + +.mytheme .v-window-contents { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border-radius: 4px; + margin-top: 0 !important; +} + +.mytheme .v-window-contents > .v-scrollable { + position: relative; +} + +.mytheme .v-window-contents > .v-scrollable > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-top"] > tbody > [class*="firstrow"] > td { + padding-top: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-bottom"] > tbody > [class*="lastrow"] > td { + padding-bottom: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-left"] > tbody > [class*="row"] > [class*="captioncell"] { + padding-left: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h2, .mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-left"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + left: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] { + padding-right: 12px; +} + +.mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h2, .mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h3, .mytheme .v-window-contents > .v-scrollable > .v-formlayout [class*="margin-right"] > tbody > [class*="row"] > [class*="contentcell"] > .v-label-h4 { + right: 12px; +} + +.mytheme .v-window-contents > .v-scrollable:focus { + outline: none; +} + +.mytheme .v-window-contents > .v-scrollable:before { + content: ""; + position: absolute; + z-index: 2; + top: 0; + height: 0; + border-top: 1px solid white; + left: 0; + right: 0; +} + +.mytheme .v-window-contents > .v-scrollable .v-panel-captionwrap:after { + border-color: #dfdfdf; +} + +.mytheme .v-window-contents > .v-scrollable .v-panel-content:before { + border-color: white; +} + +.mytheme .v-window-footer { + height: 0; +} + +.mytheme .v-window-resizebox { + position: absolute; + z-index: 1000; + right: 0; + bottom: 0; + width: 19px; + height: 19px; + cursor: nwse-resize; +} + +.v-ie8 .mytheme .v-window-resizebox { + background: #000; + filter: alpha(opacity=0.1); +} + +.v-ie8 .mytheme .v-window-resizebox, .v-ie9 .mytheme .v-window-resizebox { + cursor: se-resize; +} + +.mytheme .v-window-modalitycurtain:active ~ .v-window { + -webkit-animation: none; + -moz-animation: none; + animation: none; +} + +.mytheme .v-window-top-toolbar > .v-widget, .mytheme .v-window-bottom-toolbar > .v-widget { + vertical-align: top; +} + +.mytheme .v-window-top-toolbar .v-label, .mytheme .v-window-bottom-toolbar .v-label { + line-height: 36px; +} + +.mytheme .v-window-top-toolbar .v-spacing, .mytheme .v-window-bottom-toolbar .v-spacing { + width: 6px; +} + +.mytheme .v-window-top-toolbar.v-layout { + padding: 7px 12px; + position: relative; + z-index: 2; + border-top: 1px solid #dfdfdf; + border-bottom: 1px solid #dfdfdf; + background-color: #fafafa; +} + +.mytheme .v-window-top-toolbar.v-menubar { + margin: 12px 12px 6px; +} + +.mytheme .v-window-top-toolbar.v-menubar-borderless { + padding-left: 6px; + padding-right: 6px; + margin: 5px 0; +} + +.mytheme .v-window-bottom-toolbar.v-layout { + padding: 7px 12px; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #f0f0f0 0, #fafafa 4px); + background-image: linear-gradient(to bottom,#f0f0f0 0, #fafafa 4px); + border-top: 1px solid #dfdfdf; + border-radius: 0 0 4px 4px; +} + +.mytheme .v-margin-left.v-margin-right.v-margin-top .v-window-top-toolbar.v-layout { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + margin: -12px -12px 0; +} + +.mytheme .v-margin-left.v-margin-right.v-margin-top .v-window-top-toolbar.v-menubar { + margin: 0; +} + +.mytheme .v-margin-left.v-margin-right.v-margin-top .v-window-top-toolbar.v-menubar-borderless { + margin: -6px -6px 0; + padding: 0; +} + +.mytheme .v-margin-left.v-margin-right.v-margin-bottom .v-window-bottom-toolbar.v-layout { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + margin: 0 -12px -12px; +} + +.mytheme .v-tree { + position: relative; + white-space: nowrap; +} + +.mytheme .v-tree:focus { + outline: none; +} + +.mytheme .v-tree-node:before { + content: ""; + position: absolute; + display: inline-block; + z-index: 3; + width: 1.9em; + height: 28px; + cursor: pointer; + background: red; + opacity: 0; +} + +.v-ie8 .mytheme .v-tree-node:before { + position: static; + margin-left: -1.9em; + vertical-align: top; + content: "\f0da"; + font-family: ThemeIcons; + text-align: center; + background: transparent; +} + +.v-ie8 .mytheme .v-tree-node { + padding-left: 1.9em; +} + +.mytheme .v-tree-node-caption { + height: 28px; + line-height: 27px; + overflow: hidden; + white-space: nowrap; + vertical-align: top; +} + +.mytheme .v-tree-node-caption > div { + display: inline-block; + width: 100%; + position: relative; + z-index: 2; +} + +.mytheme .v-tree-node-caption > div:before { + content: "\f0da"; + font-family: ThemeIcons; + display: inline-block; + width: 0.5em; + text-align: center; + margin: 0 0.6em 0 0.8em; + -webkit-transition: all 100ms; + -moz-transition: all 100ms; + transition: all 100ms; +} + +.v-ie8 .mytheme .v-tree-node-caption > div:before { + display: none; +} + +.mytheme .v-tree-node-caption span { + padding-right: 28px; + cursor: pointer; + display: inline-block; + width: 100%; +} + +.v-ie .mytheme .v-tree-node-caption span { + width: auto; +} + +.mytheme .v-tree-node-caption .v-icon { + padding-right: 0; + width: auto; + min-width: 1em; +} + +.mytheme .v-tree-node-caption:after { + content: ""; + display: block; + vertical-align: top; + position: absolute; + z-index: 1; + left: 0; + margin-top: -28px; + width: 100%; + height: 28px; + border-radius: 4px; + opacity: 0; + -webkit-transition: opacity 120ms; + -moz-transition: opacity 120ms; + transition: opacity 120ms; +} + +.v-ie8 .mytheme .v-tree-node-caption:after { + content: none; +} + +.v-ie8 .mytheme .v-tree-node-caption { + display: inline-block; +} + +.mytheme .v-tree-node-expanded > .v-tree-node-caption > div:before { + -webkit-transform: rotate(90deg); + -moz-transform: rotate(90deg); + -ms-transform: rotate(90deg); + -o-transform: rotate(90deg); + transform: rotate(90deg); + content: "\f0da"; + font-family: ThemeIcons; +} + +.v-ie8 .mytheme .v-tree-node-expanded:before { + content: "\f0d7"; + font-family: ThemeIcons; +} + +.mytheme .v-tree-node-leaf:before, .mytheme .v-tree-node-leaf > .v-tree-node-caption > div:before { + visibility: hidden; +} + +.mytheme .v-tree-node-focused:after { + opacity: 1; + border: 1px solid #197de1; +} + +.v-ie8 .mytheme .v-tree-node-focused { + outline: 1px dotted #197de1; +} + +.mytheme .v-tree-node-selected { + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-tree-node-selected:after { + opacity: 1; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + border: none; +} + +.v-ie8 .mytheme .v-tree-node-selected { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); +} + +.mytheme .v-tree-node-children { + padding-left: 19px; +} + +.v-ie8 .mytheme .v-tree-node-children { + padding-left: 0; +} + +.mytheme .v-tree-node-drag-top:before, .mytheme .v-tree-node-drag-bottom:after, .mytheme .v-tree-node-drag-bottom.v-tree-node-dragfolder.v-tree-node-expanded > .v-tree-node-children:before { + content: "\2022"; + display: block; + position: absolute; + height: 2px; + width: 100%; + background: #197de1; + font-size: 32px; + line-height: 2px; + color: #197de1; + text-indent: -4px; + text-shadow: 0 0 1px #fafafa, 0 0 1px #fafafa; + opacity: 1; + visibility: visible; +} + +.mytheme .v-tree-node-drag-bottom.v-tree-node-dragfolder.v-tree-node-expanded:after { + content: none; +} + +.mytheme .v-tree-node-caption-drag-center { + -webkit-box-shadow: 0 0 0 2px #197de1; + box-shadow: 0 0 0 2px #197de1; + position: relative; + border-radius: 4px; +} + +.v-ie8 .mytheme .v-tree-node-caption-drag-center { + outline: 2px solid #197de1; +} + +.v-ff .mytheme .v-tree-node-drag-top:before, .v-ff .mytheme .v-tree-node-drag-bottom:after { + line-height: 1px; +} + +.v-ie8 .mytheme .v-tree-node-drag-top:before, .v-ie8 .mytheme .v-tree-node-drag-bottom:after { + line-height: 0; +} + +.mytheme .v-table { + position: relative; + background: #fafafa; + color: #464646; + overflow: hidden; +} + +.mytheme .v-table-header table, .mytheme .v-table-footer table, .mytheme .v-table-table { + -webkit-box-shadow: 0 0 0 1px #d4d4d4; + box-shadow: 0 0 0 1px #d4d4d4; +} + +.v-ie8 .mytheme .v-table-header table, .v-ie8 .mytheme .v-table-footer table, .v-ie8 .mytheme .v-table-table { + outline: 1px solid #d4d4d4; +} + +.mytheme .v-table-header-wrap, .mytheme .v-table-footer-wrap, .mytheme .v-table-header-drag { + border: 1px solid #d4d4d4; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + white-space: nowrap; + font-size: 14px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-table-header-wrap { + position: relative; + border-bottom: none; +} + +.mytheme .v-table-footer-wrap { + border-top: none; +} + +.mytheme .v-table-footer td { + border-left: 1px solid #d4d4d4; +} + +.mytheme .v-table-footer-container, .mytheme .v-table-caption-container { + overflow: hidden; + line-height: 1; + min-height: 37px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.v-ie8 .mytheme .v-table-footer-container, .v-ie8 .mytheme .v-table-caption-container { + min-height: 14px; +} + +.mytheme .v-table-footer-container { + padding: 11px 12px 12px; + float: right; +} + +.mytheme [class^="v-table-header-cell"] { + position: relative; +} + +.mytheme .v-table-caption-container, .mytheme .v-table-header-drag { + padding: 12px 12px 11px; + border-left: 1px solid #d4d4d4; +} + +.mytheme .v-table-caption-container-align-right { + padding-right: 4px; +} + +.mytheme .v-table-resizer { + height: 37px; + width: 8px; + cursor: e-resize; + cursor: col-resize; + position: relative; + right: -4px; + z-index: 1; + margin-left: -8px; +} + +.mytheme .v-table-cell-content { + border-left: 1px solid #d4d4d4; + overflow: hidden; + height: 37px; + vertical-align: middle; +} + +.mytheme .v-table-cell-content:first-child { + border-left: none; + padding-left: 1px; +} + +.mytheme .v-table-header td:first-child .v-table-caption-container, .mytheme .v-table-footer td:first-child { + border-left-color: transparent; +} + +.mytheme .v-table-cell-wrapper { + line-height: 1; + padding: 0 12px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + margin-right: 0 !important; +} + +.mytheme .v-table-cell-wrapper > .v-widget { + margin: 3px -6px; +} + +.mytheme .v-table-cell-wrapper > .v-widget.v-label, .mytheme .v-table-cell-wrapper > .v-widget.v-checkbox, .mytheme .v-table-cell-wrapper > .v-widget.v-select-optiongroup { + margin: 0; +} + +.mytheme .v-table-cell-wrapper > .v-widget.v-progressbar { + margin-left: 0; + margin-right: 0; +} + +.mytheme .v-table-body { + border: 1px solid #d4d4d4; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} + +.mytheme .v-table-table { + background-color: white; + white-space: nowrap; +} + +.mytheme .v-table-table td { + border-top: 1px solid #d4d4d4; +} + +.mytheme .v-table-table tr:first-child > td { + border-top: none; +} + +.mytheme .v-table-row { + background-color: white; + cursor: pointer; +} + +.mytheme .v-table-row-odd { + background-color: #f5f5f5; + cursor: pointer; +} + +.mytheme .v-table-body-noselection .v-table-row, .mytheme .v-table-body-noselection .v-table-row-odd { + cursor: default; +} + +.mytheme .v-table [class*="-row"].v-selected { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + background-origin: border-box; + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-table [class*="-row"].v-selected + .v-selected { + background: #166ed5; +} + +.mytheme .v-table [class*="-row"].v-selected + .v-selected td { + border-top-color: #166ed5; +} + +.mytheme .v-table [class*="-row"].v-selected .v-table-cell-content { + border-color: transparent; + border-left-color: #1d69b4; +} + +.mytheme .v-table [class*="-row"].v-selected .v-table-cell-content:first-child { + border-left-color: transparent; +} + +.mytheme .v-table-header-cell-asc .v-table-sort-indicator, .mytheme .v-table-header-cell-desc .v-table-sort-indicator { + background: transparent; + width: 19px; + height: 37px; + line-height: 37px; + margin-left: -19px; +} + +.mytheme .v-table-header-cell-asc .v-table-sort-indicator:before, .mytheme .v-table-header-cell-desc .v-table-sort-indicator:before { + font-style: normal; + font-weight: normal; + display: inline-block; +} + +.mytheme .v-table-header-cell-asc .v-table-sort-indicator:before { + content: "\f0de"; + font-family: ThemeIcons; +} + +.mytheme .v-table-header-cell-desc .v-table-sort-indicator:before { + content: "\f0dd"; + font-family: ThemeIcons; +} + +.mytheme [class*="rowheader"] span.v-icon { + min-width: 1em; +} + +.mytheme .v-table-focus { + outline: 1px solid #197de1; + outline-offset: -1px; +} + +.mytheme .v-drag-element.v-table-focus, .mytheme .v-drag-element .v-table-focus { + outline: none; +} + +.mytheme .v-table-header-drag { + position: absolute; + opacity: 0.9; + filter: alpha(opacity=90) ; + margin-top: -19px; + z-index: 30000; + line-height: 1; +} + +.mytheme .v-table-focus-slot-right { + border-right: 3px solid #197de1; + right: -2px; + margin-left: -11px !important; +} + +.mytheme .v-table-focus-slot-left { + float: left; + border-left: 3px solid #197de1; + left: -1px; + right: auto; + margin-left: 0 !important; + margin-right: -11px; +} + +.mytheme .v-table-column-selector { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + position: absolute; + z-index: 2; + top: 0; + right: 0; + width: 19px; + height: 19px; + line-height: 19px; + padding: 0; + border-top-width: 0; + border-right-width: 0; + border-radius: 0 0 0 4px; + cursor: pointer; + text-align: center; + opacity: 0; + filter: alpha(opacity=0) ; + -webkit-transition: opacity 200ms 2s; + -moz-transition: opacity 200ms 2s; + transition: opacity 200ms 2s; +} + +.mytheme .v-table-column-selector:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-table-column-selector:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-table-column-selector:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-table-column-selector:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-table-column-selector:after { + content: ""; + position: absolute; + border: none; + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.mytheme .v-table-column-selector:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-table-column-selector:before { + font-family: ThemeIcons; + content: "\f013"; +} + +.mytheme .v-table-header-wrap:hover .v-table-column-selector { + opacity: 1; + filter: none ; + -webkit-transition-delay: 200ms; + -moz-transition-delay: 200ms; + transition-delay: 200ms; +} + +.mytheme .v-on:before, .mytheme .v-off:before { + content: "\f00c"; + font-family: ThemeIcons; + font-size: 0.9em; + margin-right: 6px; +} + +.mytheme .v-on div, .mytheme .v-off div { + display: inline; +} + +.mytheme .v-on.v-disabled, .mytheme .v-off.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-off:before { + visibility: hidden; +} + +.mytheme tbody.v-drag-element { + display: block; + overflow: visible; + -webkit-box-shadow: none; + box-shadow: none; + background: transparent; + opacity: 1; + filter: none ; +} + +.mytheme tbody.v-drag-element tr { + display: block; + + + -webkit-box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); + border-radius: 4px; + overflow: hidden; + opacity: 0.5; + filter: alpha(opacity=50) ; + background: white; +} + +.mytheme .v-table-body { + position: relative; + z-index: 1; +} + +.mytheme .v-table-scrollposition { + position: absolute; + top: 50%; + width: 100%; + height: 37px; + line-height: 37px; + margin: -19px 0 0 !important; + text-align: center; +} + +.mytheme .v-table-drag { + overflow: visible; +} + +.mytheme .v-table-drag .v-table-body { + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + border-color: #197de1; +} + +.v-ie8 .mytheme .v-table-drag .v-table-body { + border-color: #197de1; +} + +.mytheme .v-table-drag .v-table-body .v-table-focus { + outline: none; +} + +.mytheme .v-table-row-drag-middle .v-table-cell-content { + background-color: #d1e5f9; + color: #214060; +} + +.mytheme .v-table-row-drag-bottom td.v-table-cell-content { + border-bottom: 2px solid #197de1; + height: 35px; +} + +.mytheme .v-table-row-drag-bottom .v-table-cell-wrapper { + margin-bottom: -2px; +} + +.mytheme .v-table-row-drag-top td.v-table-cell-content { + border-top: 2px solid #197de1; + height: 36px; +} + +.mytheme .v-table-row-drag-top .v-table-cell-wrapper { + margin-top: -1px; +} + +.mytheme .v-table-no-stripes .v-table-row, .mytheme .v-table-no-stripes .v-table-row-odd { + background: transparent; +} + +.mytheme .v-table-no-vertical-lines .v-table-cell-content { + border-left: none; + padding-left: 1px; +} + +.mytheme .v-table-no-vertical-lines.v-treetable .v-table-cell-content { + padding-left: 13px; +} + +.mytheme .v-table-no-horizontal-lines .v-table-cell-content { + border-top: none; + border-bottom: none; +} + +.mytheme .v-table-no-horizontal-lines .v-table-row-drag-top .v-table-cell-content, .mytheme .v-table-no-horizontal-lines .v-table-row-drag-bottom .v-table-cell-content { + height: 36px; +} + +.mytheme .v-table-no-header .v-table-header-wrap { + display: none; +} + +.mytheme .v-table-borderless .v-table-header-wrap, .mytheme .v-table-borderless .v-table-footer-wrap, .mytheme .v-table-borderless .v-table-header-drag, .mytheme .v-table-borderless .v-table-body { + border: none; +} + +.mytheme .v-table-borderless .v-table-header-wrap { + border-bottom: 1px solid #d9d9d9; +} + +.mytheme .v-table-borderless .v-table-footer-wrap { + border-top: 1px solid #d9d9d9; +} + +.mytheme .v-table-compact .v-table-header-wrap, .mytheme .v-table-compact .v-table-footer-wrap, .mytheme .v-table-compact .v-table-header-drag, .mytheme .v-table-small .v-table-header-wrap, .mytheme .v-table-small .v-table-footer-wrap, .mytheme .v-table-small .v-table-header-drag { + font-size: 14px; +} + +.mytheme .v-table-compact .v-table-footer-container, .mytheme .v-table-small .v-table-footer-container { + padding: 8px 7px 9px; +} + +.mytheme .v-table-compact .v-table-caption-container, .mytheme .v-table-compact .v-table-header-drag, .mytheme .v-table-small .v-table-caption-container, .mytheme .v-table-small .v-table-header-drag { + padding-top: 9px; + padding-bottom: 8px; + padding-left: 6px; + padding-right: 6px; +} + +.mytheme .v-table-compact .v-table-caption-container-align-right, .mytheme .v-table-small .v-table-caption-container-align-right { + padding-right: 0; +} + +.mytheme .v-table-compact .v-table-resizer, .mytheme .v-table-small .v-table-resizer { + height: 31px; +} + +.mytheme .v-table-compact .v-table-cell-content, .mytheme .v-table-small .v-table-cell-content { + height: 31px; +} + +.mytheme .v-table-compact .v-table-cell-wrapper, .mytheme .v-table-small .v-table-cell-wrapper { + padding-left: 6px; + padding-right: 6px; +} + +.mytheme .v-table-compact .v-table-cell-wrapper > .v-widget, .mytheme .v-table-small .v-table-cell-wrapper > .v-widget { + margin: 2px -3px; +} + +.mytheme .v-table-compact .v-table-cell-wrapper > .v-widget.v-label, .mytheme .v-table-compact .v-table-cell-wrapper > .v-widget.v-checkbox, .mytheme .v-table-compact .v-table-cell-wrapper > .v-widget.v-select-optiongroup, .mytheme .v-table-small .v-table-cell-wrapper > .v-widget.v-label, .mytheme .v-table-small .v-table-cell-wrapper > .v-widget.v-checkbox, .mytheme .v-table-small .v-table-cell-wrapper > .v-widget.v-select-optiongroup { + margin: 0; +} + +.mytheme .v-table-compact .v-table-cell-wrapper > .v-widget.v-progressbar, .mytheme .v-table-small .v-table-cell-wrapper > .v-widget.v-progressbar { + margin-left: 0; + margin-right: 0; +} + +.mytheme .v-table-compact .v-table-header-cell-asc .v-table-sort-indicator, .mytheme .v-table-compact .v-table-header-cell-desc .v-table-sort-indicator, .mytheme .v-table-small .v-table-header-cell-asc .v-table-sort-indicator, .mytheme .v-table-small .v-table-header-cell-desc .v-table-sort-indicator { + height: 31px; + line-height: 31px; +} + +.mytheme .v-table-compact .v-table-header-drag, .mytheme .v-table-small .v-table-header-drag { + margin-top: -16px; +} + +.mytheme .v-table-compact.v-treetable .v-table-cell-wrapper, .mytheme .v-table-small.v-treetable .v-table-cell-wrapper { + padding-left: 0; + padding-right: 0; + min-height: 16px; +} + +.mytheme .v-table-compact.v-treetable .v-table-cell-content, .mytheme .v-table-small.v-treetable .v-table-cell-content { + padding-left: 6px; + padding-right: 6px; +} + +.mytheme .v-table-compact.v-treetable .v-table-cell-content:first-child, .mytheme .v-table-small.v-treetable .v-table-cell-content:first-child { + padding-left: 7px; +} + +.mytheme .v-table-compact.v-treetable .v-table-footer-container, .mytheme .v-table-small.v-treetable .v-table-footer-container { + padding-left: 6px; + padding-right: 6px; +} + +.mytheme .v-table-compact .v-table-row-drag-top .v-table-cell-content, .mytheme .v-table-compact .v-table-row-drag-bottom .v-table-cell-content, .mytheme .v-table-small .v-table-row-drag-top .v-table-cell-content, .mytheme .v-table-small .v-table-row-drag-bottom .v-table-cell-content { + height: 30px; +} + +.mytheme .v-table-small { + font-size: 14px; +} + +.mytheme .v-table-small.v-treetable .v-table-cell-wrapper { + min-height: 14px; +} + +.mytheme .v-treetable [class*="caption-container"], .mytheme .v-treetable [class*="footer-container"], .mytheme .v-treetable [class*="cell-wrapper"] { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + padding-left: 0; + padding-right: 0; +} + +.mytheme .v-treetable [class*="caption-container"], .mytheme .v-treetable [class*="footer-container"] { + min-height: 14px; +} + +.mytheme .v-treetable [class*="cell-wrapper"] { + min-height: 16px; +} + +.mytheme .v-treetable [class*="caption-container"] { + padding-left: 12px; +} + +.mytheme .v-treetable [class*="caption-container-align-right"] { + padding-left: 20px; +} + +.mytheme .v-treetable [class*="footer-container"] { + padding-right: 12px; +} + +.mytheme .v-treetable [class*="cell-content"] { + padding-left: 12px; + padding-right: 12px; +} + +.mytheme .v-treetable [class*="cell-content"]:first-child { + padding-left: 13px; +} + +.mytheme .v-treetable-treespacer { + display: inline-block; + position: absolute; + width: 19px !important; + margin-left: -25px; + text-align: center; + cursor: pointer; +} + +.mytheme .v-treetable-node-closed:before { + content: "\f0da"; + font-family: ThemeIcons; +} + +.mytheme .v-treetable-node-open:before { + content: "\f0d7"; + font-family: ThemeIcons; +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter { + width: 1px; +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter:after { + left: -6px; + right: -6px; +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter div:before { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + height: auto; + padding: 0; + border-radius: 0; + background-color: #fafafa; + background-image: -webkit-linear-gradient(left, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to right,#fafafa 2%, #efefef 98%); +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter div:before:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter div:before:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter div:before:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-hsplitter div:before:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-splitpanel-horizontal > div > .v-splitpanel-second-container { + margin-left: 1px; +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter { + height: 1px; +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter:after { + top: -6px; + bottom: -6px; +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter div:before { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + height: auto; + padding: 0; + border-radius: 0; +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter div:before:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter div:before:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter div:before:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-splitpanel-vertical > div > .v-splitpanel-vsplitter div:before:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter { + width: 12px; +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter:after { + left: 0px; + right: 0px; +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:before { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + height: auto; + padding: 0; + border-radius: 0; + background-color: #fafafa; + background-image: -webkit-linear-gradient(left, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to right,#fafafa 2%, #efefef 98%); +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:before:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:before:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:before:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:before:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-hsplitter div:after { + content: ""; + border: 1px solid #dadada; + border-top-color: #bababa; + border-left-color: #bababa; + position: absolute; + top: 50%; + left: 50%; + width: 0; + height: 37px; + margin-left: -1px; + margin-top: -19px; +} + +.mytheme .v-splitpanel-horizontal.large > div > .v-splitpanel-second-container { + margin-left: 12px; +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter { + height: 12px; +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter:after { + top: 0px; + bottom: 0px; +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:before { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, none; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + height: auto; + padding: 0; + border-radius: 0; +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:before:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:before:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:before:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:before:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-splitpanel-vertical.large > div > .v-splitpanel-vsplitter div:after { + content: ""; + border: 1px solid #dadada; + border-top-color: #bababa; + border-left-color: #bababa; + position: absolute; + top: 50%; + left: 50%; + width: 37px; + height: 0; + margin-left: -19px; + margin-top: -1px; +} + +.mytheme .v-progressbar-wrapper { + border-radius: 4px; + height: 9px; + background-color: #d4d4d4; + background-image: -webkit-linear-gradient(bottom, #d7d7d7 2%, #c7c7c7 98%); + background-image: linear-gradient(to top,#d7d7d7 2%, #c7c7c7 98%); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + min-width: 74px; +} + +.mytheme .v-progressbar-indicator { + border-radius: 4px; + height: inherit; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + + + border: 1px solid #1362b1; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + max-width: 100%; + min-width: 8px; + -webkit-transition: width 160ms; + -moz-transition: width 160ms; + transition: width 160ms; +} + +.mytheme .v-progressbar-point .v-progressbar-indicator { + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + border: none; + text-align: right; + overflow: hidden; +} + +.mytheme .v-progressbar-point .v-progressbar-indicator:before { + content: ""; + display: inline-block; + border-radius: 4px; + height: inherit; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + + + border: 1px solid #1362b1; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + max-width: 100%; + width: 9px; + vertical-align: top; +} + +.mytheme .v-progressbar-indeterminate { + height: 24px !important; + width: 24px !important; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: 2px solid rgba(25, 125, 225, 0.2); + border-top-color: #197de1; + border-right-color: #197de1; + border-radius: 100%; + -webkit-animation: v-rotate-360 500ms infinite linear; + -moz-animation: v-rotate-360 500ms infinite linear; + animation: v-rotate-360 500ms infinite linear; + pointer-events: none; +} + +.v-ie8 .mytheme .v-progressbar-indeterminate, .v-ie9 .mytheme .v-progressbar-indeterminate { + border: none; + border-radius: 4px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50% 50%; + background-size: 80%; +} + +.v-ie8 .mytheme .v-progressbar-indeterminate { + min-width: 30px; + min-height: 30px; +} + +.mytheme .v-progressbar-indeterminate .v-progressbar-wrapper { + display: none; +} + +.mytheme .v-slider { + position: relative; +} + +.mytheme .v-slider:focus { + outline: none; +} + +.mytheme .v-slider:focus .v-slider-handle:after { + opacity: 1; +} + +.v-ie8 .mytheme .v-slider:focus .v-slider-handle:after { + visibility: visible; +} + +.mytheme .v-slider.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-slider-base { + border-radius: 4px; + height: 9px; + background-color: #d4d4d4; + background-image: -webkit-linear-gradient(bottom, #d7d7d7 2%, #c7c7c7 98%); + background-image: linear-gradient(to top,#d7d7d7 2%, #c7c7c7 98%); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + min-width: 74px; + height: 6px; + margin: 16px 11px; + white-space: nowrap; + overflow: hidden; + +} + +.mytheme .v-slider-base:before { + content: ""; + position: absolute; + top: 16px; + bottom: 16px; + left: 11px; + width: 8px; + border-radius: 4px; + border-left: 1px solid #1362b1; +} + +.mytheme .v-slider-base:after { + border-radius: 4px; + height: inherit; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + + + border: 1px solid #1362b1; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + max-width: 100%; + content: ""; + display: inline-block; + margin-left: -100%; + width: 100%; + vertical-align: top; +} + +.v-ie8 .mytheme .v-slider-base:after { + position: relative; + left: -11px; +} + +.mytheme .v-has-width > .v-slider-base { + min-width: 0; +} + +.mytheme .v-slider-handle { + margin-top: -16px; + width: 0.1px; + display: inline-block; + vertical-align: top; +} + +.mytheme .v-slider-handle:before { + height: 37px; + padding: 0 16px; + color: #191919; + font-weight: 400; + + + border-radius: 4px; + border: 1px solid #c5c5c5; + border-top-color: #c5c5c5; + border-bottom-color: #bcbcbc; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7, 0 2px 3px rgba(0, 0, 0, 0.05); + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.mytheme .v-slider-handle:before:after { + border: inherit; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; +} + +.mytheme .v-slider-handle:before:hover:after { + background-color: rgba(186, 186, 186, 0.1); +} + +.mytheme .v-slider-handle:before:focus:after { + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-slider-handle:before:active:after { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-slider-handle:after { + border: 1px solid #c5c5c5; + border-color: #197de1; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + opacity: 0; + -webkit-transition: opacity 200ms; + -moz-transition: opacity 200ms; + transition: opacity 200ms; +} + +.v-ie8 .mytheme .v-slider-handle:after { + visibility: hidden; +} + +.mytheme .v-slider-handle:before, .mytheme .v-slider-handle:after { + content: ""; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 0; + width: 22px; + height: 22px; + border-radius: 11px; + position: absolute; + z-index: 1; + margin-top: 8px; + margin-left: -11px; +} + +.mytheme .v-slider-feedback { + background-color: #323232; + background-color: rgba(50, 50, 50, 0.9); + -webkit-box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2); + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2); + color: white; + padding: 5px 9px; + border-radius: 3px; + max-width: 35em; + overflow: hidden !important; + font-size: 14px; +} + +.mytheme .v-slider-vertical { + padding: 11px 0; + height: 96px; +} + +.mytheme .v-slider-vertical .v-slider-base { + background-color: #d4d4d4; + background-image: -webkit-linear-gradient(right, #d7d7d7 2%, #c7c7c7 98%); + background-image: linear-gradient(to left,#d7d7d7 2%, #c7c7c7 98%); + width: 6px; + height: 100% !important; + min-width: 0; + margin: 0 16px; +} + +.mytheme .v-slider-vertical .v-slider-base:before { + top: auto; + bottom: 11px; + left: 16px; + right: 16px; + width: auto; + height: 8px; + border-left: none; + border-bottom: 1px solid #1362b1; +} + +.mytheme .v-slider-vertical .v-slider-base:after { + height: 101%; + margin-left: 0; + background-color: #197de1; + background-image: -webkit-linear-gradient(left, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to right,#1b87e3 2%, #166ed5 98%); +} + +.v-ie8 .mytheme .v-slider-vertical .v-slider-base:after { + top: 11px; + left: 0; + height: 130%; +} + +.mytheme .v-slider-vertical .v-slider-handle { + width: 0; + height: 0.1px; + width: 37px; + display: block; +} + +.mytheme .v-slider-vertical .v-slider-handle:before, .mytheme .v-slider-vertical .v-slider-handle:after { + width: 22px; + height: 22px; + margin-top: -11px; + margin-left: -8px; +} + +.mytheme .v-slider-no-indicator .v-slider-base:before, .mytheme .v-slider-no-indicator .v-slider-base:after { + display: none; +} + +.mytheme .v-tabsheet:not(.v-has-width) { + width: auto !important; +} + +.mytheme .v-tabsheet-spacertd { + display: none !important; +} + +.mytheme .v-tabsheet-tabcontainer { + position: relative; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-tabsheet-tabcontainer:before { + content: ""; + position: absolute; + height: 0; + border-top: 1px solid #dfdfdf; + bottom: 0; + left: 0; + right: 0; +} + +.mytheme .v-tabsheet-tabcontainer .v-tabsheet-tabs { + position: relative; +} + +.mytheme .v-tabsheet-tabitemcell { + vertical-align: bottom; +} + +.mytheme .v-tabsheet-tabitemcell .v-tabsheet-tabitem { + line-height: 0; + overflow: hidden; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption { + margin-left: 19px; + padding: 0 4px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + cursor: pointer; + text-align: center; + line-height: 37px; + font-size: 15px; + font-weight: 300; + color: #696969; + width: auto !important; + overflow: hidden; + text-overflow: ellipsis; + border-bottom: 2px solid transparent; + position: relative; + -webkit-transition: border-bottom 200ms, color 200ms; + -moz-transition: border-bottom 200ms, color 200ms; + transition: border-bottom 200ms, color 200ms; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption .v-captiontext { + display: inline; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption .v-icon + .v-captiontext { + margin-left: 9px; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption:hover { + color: #197de1; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; + cursor: default; + color: inherit !important; +} + +.mytheme .v-tabsheet-tabitemcell:first-child .v-caption, .mytheme .v-tabsheet-tabitemcell[aria-hidden="true"] + td .v-caption { + margin-left: 0; +} + +.mytheme .v-tabsheet-tabitemcell:focus { + outline: none; +} + +.mytheme .v-tabsheet-tabitemcell:focus .v-caption { + color: #197de1; +} + +.mytheme .v-tabsheet-tabitemcell .v-tabsheet-tabitem-selected .v-caption.v-caption { + border-bottom-color: #197de1; + color: #197de1; +} + +.mytheme .v-tabsheet-tabitemcell .v-caption-closable { + padding-right: 22px; +} + +.mytheme .v-tabsheet-tabitemcell.icons-on-top .v-caption-closable { + padding-right: 4px; +} + +.mytheme .v-tabsheet-tabitemcell .v-tabsheet-caption-close { + position: absolute; + right: 0; + top: 50%; + margin: -8px 0 0; + font-size: 18px; + line-height: 18px; + width: 18px; + text-align: center; + border-radius: 2px; + color: #969696; +} + +.mytheme .v-tabsheet-tabitemcell .v-tabsheet-caption-close:hover { + background: rgba(0, 0, 0, 0.03); + color: #197de1; +} + +.mytheme .v-tabsheet-tabitemcell .v-tabsheet-caption-close:active { + background: #197de1; + color: #c8dbed; +} + +.mytheme .v-tabsheet-scroller { + position: absolute; + top: 0; + right: 0; + bottom: 0; + padding-left: 19px; + background-color: transparent; + background-image: -webkit-linear-gradient(right, #fafafa 70%, rgba(250, 250, 250, 0) 100%); + background-image: linear-gradient(to left,#fafafa 70%, rgba(250, 250, 250, 0) 100%); + pointer-events: none; +} + +.mytheme .v-tabsheet-scroller:after { + content: ""; + height: 1px; + position: absolute; + bottom: 0; + left: 0; + right: 0; + display: block; + background-color: transparent; + background-image: -webkit-linear-gradient(right, #dfdfdf 70%, rgba(223, 223, 223, 0) 100%); + background-image: linear-gradient(to left,#dfdfdf 70%, rgba(223, 223, 223, 0) 100%); +} + +.v-ie8 .mytheme .v-tabsheet-scroller, .v-ie9 .mytheme .v-tabsheet-scroller { + background-color: #fafafa; +} + +.v-ie8 .mytheme .v-tabsheet-scroller:after, .v-ie9 .mytheme .v-tabsheet-scroller:after { + background-color: #dfdfdf; +} + +.mytheme .v-tabsheet-scroller button { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + border: none; + background: transparent; + font: inherit; + color: inherit; + height: 100%; + margin: 0; + padding: 0 9px; + outline: none; + cursor: pointer; + pointer-events: auto; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-tabsheet-scroller button:hover { + opacity: 1; + filter: none ; + color: #197de1; +} + +.mytheme .v-tabsheet-scroller button:active { + opacity: 0.7; + filter: alpha(opacity=70) ; + color: #197de1; +} + +.mytheme .v-tabsheet-scroller button::-moz-focus-inner { + padding: 0; + border: 0; +} + +.mytheme .v-tabsheet-scroller [class*="Next"] { + padding-left: 5px; +} + +.mytheme .v-tabsheet-scroller [class*="Next"]:before { + font-family: ThemeIcons; + content: "\f054"; +} + +.mytheme .v-tabsheet-scroller [class*="Prev"] { + padding-right: 5px; +} + +.mytheme .v-tabsheet-scroller [class*="Prev"]:before { + font-family: ThemeIcons; + content: "\f053"; +} + +.mytheme .v-tabsheet-scroller [class*="disabled"] { + cursor: default; + color: inherit !important; + opacity: 0.1 !important; + filter: alpha(opacity=10) !important; +} + +.mytheme .v-tabsheet-tabsheetpanel > .v-scrollable > .v-widget { + -webkit-animation: valo-animate-in-fade 300ms backwards; + -moz-animation: valo-animate-in-fade 300ms backwards; + animation: valo-animate-in-fade 300ms backwards; +} + +.mytheme .v-tabsheet-deco { + height: 20px !important; + width: 20px !important; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: 2px solid rgba(25, 125, 225, 0.2); + border-top-color: #197de1; + border-right-color: #197de1; + border-radius: 100%; + -webkit-animation: v-rotate-360 500ms infinite linear; + -moz-animation: v-rotate-360 500ms infinite linear; + animation: v-rotate-360 500ms infinite linear; + pointer-events: none; + display: none; + position: absolute; + z-index: 1; + bottom: 50%; + margin-bottom: -29px; + left: 50%; + margin-left: -10px; +} + +.v-ie8 .mytheme .v-tabsheet-deco, .v-ie9 .mytheme .v-tabsheet-deco { + border: none; + border-radius: 4px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50% 50%; + background-size: 80%; +} + +.v-ie8 .mytheme .v-tabsheet-deco { + min-width: 30px; + min-height: 30px; +} + +.mytheme .v-tabsheet-loading .v-tabsheet-deco { + display: block; +} + +.mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer table, .mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer tbody, .mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer tr { + width: 100%; +} + +.mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer tr { + display: table; + table-layout: fixed; +} + +.mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer td { + display: table-cell; +} + +.mytheme .v-tabsheet-equal-width-tabs > .v-tabsheet-tabcontainer .v-caption { + margin: 0; + display: block; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-caption { + margin-left: 4px; + padding: 0 12px; + background-color: #fafafa; + border: 1px solid transparent; + line-height: 36px; + border-radius: 4px 4px 0 0; + font-weight: 400; + -webkit-transition: background-color 160ms; + -moz-transition: background-color 160ms; + transition: background-color 160ms; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-caption:hover { + background-color: #f2f2f2; + border-bottom-color: #dfdfdf; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-caption.v-disabled:hover { + background-color: #fafafa; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-caption-closable { + padding-right: 30px; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-tabsheet-caption-close { + top: 4px; + right: 4px; + margin-top: 0; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer td:first-child .v-caption, .mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer [aria-hidden="true"] + td .v-caption { + margin-left: 0; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-tabsheet-tabitem .v-caption { + border-color: #dfdfdf; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-tabcontainer .v-tabsheet-tabitem-selected .v-caption { + background: white; + border-color: #dfdfdf; + border-bottom: none; + padding-bottom: 1px; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-content { + border: 1px solid #dfdfdf; + border-top: none; +} + +.mytheme .v-tabsheet-framed > .v-tabsheet-content > div { + background: white; +} + +.mytheme .v-tabsheet-framed.padded-tabbar > .v-tabsheet-tabcontainer { + border: 1px solid #dfdfdf; + border-bottom: none; + background: #fafafa; + padding-top: 6px; +} + +.mytheme .v-tabsheet-framed.icons-on-top > .v-tabsheet-tabcontainer .v-tabsheet-tabitem-selected .v-caption { + padding-bottom: 7px; +} + +.mytheme .v-tabsheet-centered-tabs > .v-tabsheet-tabcontainer { + text-align: center; +} + +.mytheme .v-tabsheet-right-aligned-tabs > .v-tabsheet-tabcontainer { + text-align: right; +} + +.mytheme .v-tabsheet-padded-tabbar > .v-tabsheet-tabcontainer .v-tabsheet-tabs { + padding: 0 9px; +} + +.mytheme .v-tabsheet-icons-on-top > .v-tabsheet-tabcontainer .v-caption { + padding-top: 6px; + padding-bottom: 6px; + line-height: 1.2; +} + +.mytheme .v-tabsheet-icons-on-top > .v-tabsheet-tabcontainer .v-icon { + display: block; +} + +.mytheme .v-tabsheet-icons-on-top > .v-tabsheet-tabcontainer .v-icon + .v-captiontext.v-captiontext { + margin-left: 0; +} + +.mytheme .v-tabsheet-icons-on-top > .v-tabsheet-tabcontainer .v-caption-closable { + padding-right: 12px; +} + +.mytheme .v-tabsheet-icons-on-top > .v-tabsheet-tabcontainer .v-tabsheet-caption-close { + top: 4px; + margin-top: 0; +} + +.mytheme .v-tabsheet-compact-tabbar > .v-tabsheet-tabcontainer-compact-tabbar .v-caption { + line-height: 1.8; +} + +.mytheme .v-tabsheet-only-selected-closable > .v-tabsheet-tabcontainer .v-tabsheet-caption-close { + visibility: hidden; +} + +.mytheme .v-tabsheet-only-selected-closable > .v-tabsheet-tabcontainer .v-tabsheet-tabitem-selected .v-tabsheet-caption-close { + visibility: visible; +} + +.mytheme .v-colorpicker-popup.v-window { + min-width: 220px !important; +} + +.mytheme .v-colorpicker-popup .v-tabsheet-tabs { + padding: 0 9px; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] { + padding: 12px; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] .v-widget { + width: 100% !important; + vertical-align: middle; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] .v-has-caption { + white-space: nowrap; + padding-left: 48px; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] .v-caption { + display: inline-block; + margin-left: -48px; + width: 48px; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] .v-slot-hue-slider + .v-slot .v-has-caption { + padding-left: 80px; +} + +.mytheme .v-colorpicker-popup [class$="sliders"] .v-slot-hue-slider + .v-slot .v-caption { + margin-left: -80px; + width: 80px; +} + +.mytheme .v-colorpicker-popup .v-slider-red .v-slider-base:after { + background: red; + border: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-colorpicker-popup .v-slider-green .v-slider-base:after { + background: green; + border: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-colorpicker-popup .v-slider-blue .v-slider-base:after { + background: blue; + border: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-colorpicker-popup .v-margin-bottom { + padding-bottom: 0; +} + +.mytheme .v-colorpicker-popup .resize-button { + width: 100% !important; + height: auto !important; + text-align: center; + outline: none; +} + +.mytheme .v-colorpicker-popup .resize-button:before { + font-family: ThemeIcons; + content: "\f141"; +} + +.mytheme .v-colorpicker-popup .resize-button-caption { + display: none; +} + +.mytheme .v-colorpicker-popup .v-horizontallayout { + height: auto !important; + padding: 9px 0; + background-color: #fafafa; + border-top: 1px solid #ededed; +} + +.mytheme .v-colorpicker-popup .v-horizontallayout .v-expand { + overflow: visible; +} + +.mytheme .v-colorpicker-popup .v-horizontallayout .v-button { + width: 80% !important; +} + +.mytheme .v-colorpicker-preview { + width: 100% !important; + height: auto !important; + padding: 9px; +} + +.mytheme .v-colorpicker-preview-textfield { + height: auto !important; + text-align: center; + border: none; +} + +.mytheme .v-colorpicker { + width: auto; +} + +.mytheme .v-colorpicker-button-color { + position: absolute; + top: 6px; + right: 6px; + bottom: 6px; + left: 6px; + border-radius: 3px; + border: 1px solid rgba(0, 0, 0, 0.5); + max-width: 23px; +} + +.mytheme .v-colorpicker-button-color + .v-button-caption:not(:empty) { + margin-left: 19px; +} + +.v-ie8 .mytheme .v-colorpicker-button-color { + position: relative; + top: auto; + right: auto; + bottom: auto; + left: auto; + width: 16px; + height: 16px; + display: inline-block; + vertical-align: middle; + margin: 0 -8px; +} + +.v-ie8 .mytheme .v-colorpicker-button-color + .v-button-caption { + margin-left: 19px; +} + +.mytheme .v-panel { + background: white; + color: #474747; + border-radius: 4px; + border: 1px solid #d5d5d5; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + overflow: visible !important; +} + +.mytheme .v-panel-caption { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 0 12px; + line-height: 36px; + border-bottom: 1px solid #d5d5d5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #f6f6f6 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #f6f6f6 98%); + color: #464646; + font-weight: 400; + font-size: 14px; + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #eeeeee; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #eeeeee; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + border-radius: 3px 3px 0 0; +} + +.mytheme .v-panel-content { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: 100%; + height: 100%; +} + +.mytheme .v-panel-content > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-panel-content > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-panel-content > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-panel-content > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-panel-borderless { + background: transparent; + color: inherit; + border: none; + border-radius: 0; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-panel-borderless > div > [class*="-caption"] { + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; + color: inherit; + padding: 0; + margin: 0 12px; + border-bottom: none; +} + +.mytheme .v-panel-well { + background: #f5f5f5; + color: #454545; + -webkit-box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.05), inset 0 2px 3px rgba(0, 0, 0, 0.05); + border-radius: 4px; + border: 1px solid #c5c5c5; +} + +.mytheme .v-panel-well > div > [class*="-caption"] { + background: transparent; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-panel-scroll-divider > [class*="-captionwrap"] { + position: relative; + z-index: 2; +} + +.mytheme .v-panel-scroll-divider > [class*="-captionwrap"]:after { + content: ""; + position: absolute; + bottom: -1px; + right: 0; + left: 0; + height: 0; + border-top: 1px solid #dfdfdf; + border-color: rgba(197, 197, 197, 0.5); +} + +.mytheme .v-panel-scroll-divider > [class*="-content"]:before { + content: ""; + position: absolute; + z-index: 2; + top: 0; + height: 0; + border-top: 1px solid #fafafa; + left: 0; + right: 0; +} + +.mytheme .v-panel-caption.v-horizontallayout { + height: auto !important; + line-height: 0; +} + +.mytheme .v-panel-caption.v-horizontallayout .v-slot { + vertical-align: middle; +} + +.mytheme .v-panel-caption.v-horizontallayout .v-label { + line-height: 37px; +} + +.mytheme .v-accordion { + background: white; + color: #474747; + border-radius: 4px; + border: 1px solid #d5d5d5; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #f4f4f4 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #f4f4f4 98%); + overflow: hidden; +} + +.mytheme .v-accordion-item { + position: relative; +} + +.mytheme .v-accordion-item:first-child { + border-top-left-radius: 3px; + border-top-right-radius: 3px; +} + +.mytheme .v-accordion-item:last-child { + border-bottom-left-radius: 3px; + border-bottom-right-radius: 3px; +} + +.mytheme .v-accordion-item:last-child [class*="item-content"] { + border-radius: inherit; +} + +.mytheme .v-accordion-item[class*="item-open"]:last-child > div > .v-caption { + border-radius: 0; +} + +.mytheme .v-accordion-item:not([class*="item-open"]):last-child > div > .v-caption { + border-bottom: none; + margin-bottom: 0; +} + +.mytheme .v-accordion-item[class*="item-open"] + [class*="item"] { + border-top: 1px solid #d9d9d9; +} + +.mytheme .v-accordion-item-caption { + border-radius: inherit; +} + +.mytheme .v-accordion-item-caption > .v-caption { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 0 12px; + line-height: 36px; + border-bottom: 1px solid #d5d5d5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #f6f6f6 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #f6f6f6 98%); + color: #464646; + font-weight: 400; + font-size: 14px; + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #eeeeee; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #eeeeee; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.05); + display: block; + background: transparent; + border-bottom-color: #c9c9c9; + border-radius: inherit; + cursor: pointer; + position: relative; +} + +.mytheme .v-accordion-item-caption > .v-caption:hover:before, .mytheme .v-accordion-item-caption > .v-caption:active:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + border-radius: inherit; +} + +.mytheme .v-accordion-item-caption > .v-caption:hover:before { + background-color: rgba(186, 186, 186, 0.1); + border: none; +} + +.mytheme .v-accordion-item-caption > .v-caption:active:before { + background-color: rgba(125, 125, 125, 0.2); +} + +.mytheme .v-accordion-item-content { + -webkit-box-shadow: inset 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 3px rgba(0, 0, 0, 0.05); + background-color: white; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .v-accordion-item-content > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-accordion-item-content > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-accordion-item-content > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-accordion-item-content > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-accordion-borderless { + border: none; + border-radius: 0; + -webkit-box-shadow: none; + box-shadow: none; +} + +.mytheme .v-accordion-borderless > .v-accordion-item, .mytheme .v-accordion-borderless > .v-accordion-item > div > .v-caption, .mytheme .v-accordion-borderless > .v-accordion-item > .v-accordion-item-content { + border-radius: 0; +} + +.mytheme .v-select-twincol { + white-space: normal; +} + +.mytheme .v-select-twincol select { + border: 1px solid #c5c5c5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + color: #464646; +} + +.mytheme .v-select-twincol select:focus { + outline: none; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-select-twincol .v-textfield, .mytheme .v-select-twincol .v-nativebutton { + width: auto !important; + margin-top: 9px; +} + +.mytheme .v-select-twincol .v-nativebutton { + margin-left: 9px; +} + +.mytheme .v-select-twincol-caption-left, .mytheme .v-select-twincol-caption-right { + font-size: 14px; + font-weight: 400; + padding-bottom: 0.3em; + padding-left: 1px; +} + +.mytheme .v-select-twincol-buttons { + white-space: nowrap; + display: inline-block; + vertical-align: top; + position: relative; + min-width: 3.5em; +} + +.mytheme .v-select-twincol-buttons .v-button { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + display: inline-block; + vertical-align: top; + text-align: left; + white-space: normal; + position: absolute; + left: 9px; + right: 9px; + top: 36px; + padding: 0; + text-align: center; +} + +.mytheme .v-select-twincol-buttons .v-button:first-child { + top: 0; +} + +.mytheme .v-select-twincol-buttons .v-button-caption { + display: none; +} + +.mytheme .v-select-twincol-buttons .v-button:focus { + z-index: 1; +} + +.mytheme .v-select-twincol-buttons .v-button:first-child { + border-radius: 4px 4px 0 0; +} + +.mytheme .v-select-twincol-buttons .v-button:last-child { + border-radius: 0 0 4px 4px; +} + +.mytheme .v-select-twincol-buttons .v-button-wrap:before { + font-family: ThemeIcons; + content: "\f053"; +} + +.mytheme .v-select-twincol-buttons .v-button:first-child .v-button-wrap:before { + font-family: ThemeIcons; + content: "\f054"; +} + +.mytheme .v-select-twincol-error .v-select-twincol-options, .mytheme .v-select-twincol-error .v-select-twincol-selections { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-select select { + border: 1px solid #c5c5c5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + color: #464646; +} + +.mytheme .v-select select:focus { + outline: none; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-select-select { + display: block; +} + +.mytheme .v-select-select + .v-textfield { + width: auto !important; + margin-top: 9px; +} + +.mytheme .v-select-select + .v-textfield + .v-nativebutton { + margin-top: 9px; + margin-left: 9px; +} + +.mytheme .v-select-error .v-select-select { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-calendar-header-day { + font-weight: 400; + text-align: center; + padding: 7px 0; +} + +.mytheme .v-calendar-header-week .v-calendar-back, .mytheme .v-calendar-header-week .v-calendar-next { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + background: transparent; + border: none; + padding: 0; + margin: 0; + cursor: pointer; + outline: none; + color: inherit; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-calendar-header-week .v-calendar-back:focus, .mytheme .v-calendar-header-week .v-calendar-next:focus { + outline: none; +} + +.mytheme .v-calendar-header-week .v-calendar-back:hover, .mytheme .v-calendar-header-week .v-calendar-next:hover { + opacity: 1; + filter: none ; +} + +.mytheme .v-calendar-header-week .v-calendar-back:active, .mytheme .v-calendar-header-week .v-calendar-next:active { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-calendar-header-week .v-calendar-back:before { + font-family: ThemeIcons; + content: "\f053"; +} + +.mytheme .v-calendar-header-week .v-calendar-next:before { + font-family: ThemeIcons; + content: "\f054"; +} + +.mytheme .v-calendar-month { + outline: none; + overflow: hidden; +} + +.mytheme .v-calendar-month td { + vertical-align: top; +} + +.mytheme .v-calendar-week-number { + cursor: pointer; + width: 20px; + text-align: center; + font-size: 0.8em; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-calendar-week-number:hover { + opacity: 1; + filter: none ; +} + +.mytheme .v-calendar-month-day { + outline: none; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + line-height: 1.2; +} + +.mytheme .v-calendar-bottom-spacer, .mytheme .v-calendar-spacer, .mytheme .v-calendar-bottom-spacer-empty { + height: 19px; + margin-bottom: 3px; +} + +.mytheme .v-calendar-bottom-spacer { + font-size: 0.8em; + padding: 0 5px; + cursor: pointer; +} + +.mytheme .v-calendar-bottom-spacer:hover { + color: #197de1; +} + +.mytheme .v-calendar-day-number { + line-height: 25px; + font-size: 16px; + text-align: right; + margin: 0 5px; + white-space: nowrap; + border-top: 1px solid #f2f2f2; + cursor: pointer; +} + +.mytheme .v-calendar-day-number:hover { + color: #197de1; +} + +.mytheme .v-calendar-month-day-today { + background: #eef3f8; +} + +.mytheme .v-calendar-month-day-today .v-calendar-day-number { + font-weight: 400; + color: #197de1; + border-top: 2px solid #197de1; + line-height: 24px; + margin: 0; + padding: 0 5px; +} + +.mytheme .v-calendar-month-day-selected { + background-color: #e3edf7; +} + +.mytheme .v-calendar-month-day-dragemphasis { + background-color: #a8a8a8; +} + +.mytheme .v-calendar-month-day-scrollable { + overflow-y: scroll; +} + +.mytheme .v-calendar-weekly-longevents { + margin-left: 50px; + border-bottom: 3px solid #e0e0e0; +} + +.mytheme .v-calendar-weekly-longevents .v-calendar-event-all-day { + height: 22px; + line-height: 1.6; + margin-bottom: 3px; +} + +.mytheme .v-calendar-header-week td { + vertical-align: middle !important; +} + +.mytheme .v-calendar-header-week .v-calendar-header-day { + cursor: pointer; +} + +.mytheme .v-calendar-times { + width: 50px; + font-size: 0.77em; + line-height: 1; + white-space: nowrap; +} + +.mytheme .v-calendar-time { + text-align: right; + padding-right: 9px; + margin-top: -6px; + padding-bottom: 6px; +} + +.mytheme .v-calendar-day-times, .mytheme .v-calendar-day-times-today { + outline: none; + border-right: 1px solid transparent; +} + +.mytheme .v-calendar-day-times:focus, .mytheme .v-calendar-day-times-today:focus { + outline: none; +} + +.mytheme .v-calendar .v-datecellslot, .mytheme .v-calendar .v-datecellslot-even { + border-top: 1px solid #dfdfdf; +} + +.mytheme .v-calendar .v-datecellslot:first-child, .mytheme .v-calendar .v-datecellslot-even:first-child { + border-top-color: transparent; +} + +.mytheme .v-calendar .v-datecellslot { + border-top-style: dotted; +} + +.mytheme .v-calendar .v-datecellslot, .mytheme .v-calendar .v-datecellslot-even { + margin-right: 5px; +} + +.mytheme .v-calendar-current-time { + background: #197de1; + line-height: 1px; + pointer-events: none; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-calendar-current-time:before { + content: "\2022"; + color: #197de1; + font-size: 22px; + margin-left: -0.07em; +} + +.mytheme .v-calendar .v-daterange { + position: relative; +} + +.mytheme .v-calendar .v-daterange:before { + content: ""; + position: absolute; + top: 0; + right: 0; + bottom: -1px; + left: 0; + background: #197de1; + opacity: 0.5; + filter: alpha(opacity=50) ; + border-radius: 4px 4px 0 0; +} + +.mytheme .v-calendar .v-daterange + .v-daterange { + border-color: transparent; +} + +.mytheme .v-calendar .v-daterange + .v-daterange:before { + border-radius: 0; +} + +.mytheme .v-calendar-event { + font-size: 0.85em; + overflow: hidden; + cursor: pointer; + outline: none; + border-radius: 4px; +} + +.mytheme .v-calendar-event:focus { + outline: none; +} + +.mytheme .v-calendar-event-month { + padding: 0 5px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + margin-bottom: 3px; + white-space: nowrap; + text-overflow: ellipsis; + height: 19px; + line-height: 19px; +} + +.mytheme .v-calendar-event-month .v-calendar-event-time { + float: right; + font-size: 0.9em; + line-height: 19px; + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-calendar-event-month:before { + content: "\25cf"; + margin-right: 0.2em; +} + +.mytheme .v-calendar-event-all-day { + padding: 0 5px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + height: 19px; + line-height: 19px; + border-radius: 0; + margin-left: -1px; + white-space: nowrap; +} + +.mytheme .v-calendar-event-all-day:before { + content: ""; +} + +.mytheme .v-calendar-event-start { + overflow: visible; + margin-left: 0; +} + +.mytheme .v-calendar-event-start.v-calendar-event-continued-to, .mytheme .v-calendar-event-start.v-calendar-event-end { + overflow: hidden; + text-overflow: ellipsis; +} + +.mytheme .v-calendar-event-start { + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + margin-left: 5px; +} + +.mytheme .v-calendar-event-end { + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + margin-right: 5px; +} + +.mytheme .v-calendar-event-caption { + font-weight: 500; + line-height: 1.2; + padding: 5px 0; + position: absolute; + overflow: hidden; + right: 9px; + left: 5px; + bottom: 0; + top: 0; +} + +.mytheme .v-calendar-event-caption span { + font-weight: 300; + white-space: nowrap; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event { + overflow: visible; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event-content { + margin-top: -1px; + border-radius: 5px; + border: 1px solid #fafafa; + padding-top: 3px; + margin-right: 5px; +} + +.mytheme .v-calendar-event-month:before { + color: #00ace0; +} + +.mytheme .v-calendar-event-all-day { + background-color: #c8eaf4; + background-color: rgba(200, 234, 244, 0.8); + color: #00ace0; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event { + color: #00ace0; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event .v-calendar-event-content { + background-color: #c8eaf4; + background-color: rgba(200, 234, 244, 0.8); +} + +.mytheme .v-calendar-event-month[class*="color2"]:before { + color: #2d9f19; +} + +.mytheme .v-calendar-event-all-day[class*="color2"] { + background-color: #d1e7cd; + background-color: rgba(209, 231, 205, 0.8); + color: #2d9f19; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color2"] { + color: #2d9f19; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color2"] .v-calendar-event-content { + background-color: #d1e7cd; + background-color: rgba(209, 231, 205, 0.8); +} + +.mytheme .v-calendar-event-month[class*="color3"]:before { + color: #d18100; +} + +.mytheme .v-calendar-event-all-day[class*="color3"] { + background-color: #f1e1c8; + background-color: rgba(241, 225, 200, 0.8); + color: #d18100; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color3"] { + color: #d18100; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color3"] .v-calendar-event-content { + background-color: #f1e1c8; + background-color: rgba(241, 225, 200, 0.8); +} + +.mytheme .v-calendar-event-month[class*="color4"]:before { + color: #ce3812; +} + +.mytheme .v-calendar-event-all-day[class*="color4"] { + background-color: #f1d3cb; + background-color: rgba(241, 211, 203, 0.8); + color: #ce3812; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color4"] { + color: #ce3812; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color4"] .v-calendar-event-content { + background-color: #f1d3cb; + background-color: rgba(241, 211, 203, 0.8); +} + +.mytheme .v-calendar-event-month[class*="color5"]:before { + color: #2d55cd; +} + +.mytheme .v-calendar-event-all-day[class*="color5"] { + background-color: #d1d9f1; + background-color: rgba(209, 217, 241, 0.8); + color: #2d55cd; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color5"] { + color: #2d55cd; +} + +.mytheme .v-calendar-week-wrapper .v-calendar-event[class*="color5"] .v-calendar-event-content { + background-color: #d1d9f1; + background-color: rgba(209, 217, 241, 0.8); +} + +.mytheme .v-calendar.v-disabled * { + cursor: default; +} + +.mytheme .v-label { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} + +.mytheme .v-label.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-label-undef-w { + white-space: nowrap; +} + +.mytheme h1, .mytheme .v-label-h1, .mytheme h2, .mytheme .v-label-h2, .mytheme h3, .mytheme .v-label-h3 { + line-height: 1.1; + font-weight: 200; + color: #141414; +} + +.mytheme h1, .mytheme .v-label-h1 { + font-size: 2.4em; + margin-top: 1.4em; + margin-bottom: 1em; + + letter-spacing: -0.03em; +} + +.mytheme h2, .mytheme .v-label-h2 { + font-size: 1.6em; + + margin-top: 1.6em; + margin-bottom: 0.77em; + letter-spacing: -0.02em; +} + +.mytheme h3, .mytheme .v-label-h3 { + font-size: 1.2em; + + margin-top: 1.8em; + margin-bottom: 0.77em; + letter-spacing: 0; +} + +.mytheme h4, .mytheme .v-label-h4 { + line-height: 1.1; + font-weight: 500; + font-size: 14px; + color: #414141; + text-transform: uppercase; + letter-spacing: 0; + margin-top: 2.4em; + margin-bottom: 0.8em; +} + +.mytheme .v-csslayout > h1:first-child, .mytheme .v-csslayout > h2:first-child, .mytheme .v-csslayout > h3:first-child, .mytheme .v-csslayout > h4 > .v-label-h1:first-child, .mytheme .v-csslayout > .v-label-h2:first-child, .mytheme .v-csslayout > .v-label-h3:first-child, .mytheme .v-csslayout > .v-label-h4:first-child { + margin-top: 16px; +} + +.mytheme .v-verticallayout > .v-slot:first-child h1, .mytheme .v-verticallayout > .v-slot:first-child .v-label-h1, .mytheme .v-verticallayout > .v-slot:first-child h2, .mytheme .v-verticallayout > .v-slot:first-child .v-label-h2, .mytheme .v-verticallayout > .v-slot:first-child h3, .mytheme .v-verticallayout > .v-slot:first-child .v-label-h3, .mytheme .v-verticallayout > .v-slot:first-child h4, .mytheme .v-verticallayout > .v-slot:first-child .v-label-h4, .mytheme .v-verticallayout > div > .v-slot:first-child h1, .mytheme .v-verticallayout > div > .v-slot:first-child .v-label-h1, .mytheme .v-verticallayout > div > .v-slot:first-child h2, .mytheme .v-verticallayout > div > .v-slot:first-child .v-label-h2, .mytheme .v-verticallayout > div > .v-slot:first-child h3, .mytheme .v-verticallayout > div > .v-slot:first-child .v-label-h3, .mytheme .v-verticallayout > div > .v-slot:first-child h4, .mytheme .v-verticallayout > div > .v-slot:first-child .v-label-h4 { + margin-top: 16px; +} + +.mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell h1, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell .v-label-h1, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell h2, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell .v-label-h2, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell h3, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell .v-label-h3, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell h4, .mytheme .v-verticallayout > .v-slot:first-child .v-formlayout-contentcell .v-label-h4, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell h1, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell .v-label-h1, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell h2, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell .v-label-h2, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell h3, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell .v-label-h3, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell h4, .mytheme .v-verticallayout > div > .v-slot:first-child .v-formlayout-contentcell .v-label-h4 { + margin-top: -0.5em; +} + +.mytheme h1.no-margin, .mytheme .v-label-h1.no-margin, .mytheme h2.no-margin, .mytheme .v-label-h2.no-margin, .mytheme h3.no-margin, .mytheme .v-label-h3.no-margin, .mytheme h4.no-margin, .mytheme .v-label-h4.no-margin { + margin: 0 !important; +} + +.mytheme .v-label-colored { + color: #197de1; +} + +.mytheme .v-label-large { + font-size: 20px; +} + +.mytheme .v-label-small { + font-size: 14px; +} + +.mytheme .v-label-tiny { + font-size: 12px; +} + +.mytheme .v-label-huge { + font-size: 26px; +} + +.mytheme .v-label-bold { + font-weight: 500; +} + +.mytheme .v-label-light { + font-weight: 200; + color: #7d7d7d; +} + +.mytheme .v-label-align-right { + text-align: right; +} + +.mytheme .v-label-align-center { + text-align: center; +} + +.mytheme .v-label-spinner { + height: 24px !important; + width: 24px !important; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: 2px solid rgba(25, 125, 225, 0.2); + border-top-color: #197de1; + border-right-color: #197de1; + border-radius: 100%; + -webkit-animation: v-rotate-360 500ms infinite linear; + -moz-animation: v-rotate-360 500ms infinite linear; + animation: v-rotate-360 500ms infinite linear; + pointer-events: none; +} + +.v-ie8 .mytheme .v-label-spinner, .v-ie9 .mytheme .v-label-spinner { + border: none; + border-radius: 4px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50% 50%; + background-size: 80%; +} + +.v-ie8 .mytheme .v-label-spinner { + min-width: 30px; + min-height: 30px; +} + +.mytheme .v-label-success, .mytheme .v-label-failure { + background: white; + color: #474747; + border: 2px solid #2c9720; + border-radius: 4px; + padding: 7px 19px 7px 37px; + font-weight: 400; + font-size: 15px; +} + +.mytheme .v-label-success:before, .mytheme .v-label-failure:before { + font-family: ThemeIcons; + content: "\f00c"; + margin-right: 0.5em; + margin-left: -19px; + color: #2c9720; +} + +.mytheme .v-label-failure { + border-color: #ed473b; +} + +.mytheme .v-label-failure:before { + content: "\f05e"; + color: #ed473b; +} + +.mytheme [draggable=true] { + -khtml-user-drag: element; + -webkit-user-drag: element; +} + +.mytheme .v-ddwrapper { + position: relative; +} + +.mytheme .v-ddwrapper-over:before, .mytheme .v-ddwrapper-over:after { + content: ""; + position: absolute; + z-index: 10; + top: -1px; + right: -1px; + bottom: -1px; + left: -1px; + border: 0 solid #197de1; +} + +.mytheme .v-ddwrapper-over-top:before { + border-top-width: 2px; +} + +.mytheme .v-ddwrapper-over-right:before { + border-right-width: 2px; +} + +.mytheme .v-ddwrapper-over-bottom:before { + border-bottom-width: 2px; +} + +.mytheme .v-ddwrapper-over-left:before { + border-left-width: 2px; +} + +.mytheme .no-vertical-drag-hints .v-ddwrapper-over-top:before, .mytheme .no-vertical-drag-hints.v-ddwrapper-over-top:before { + border-top-width: 0; +} + +.mytheme .no-vertical-drag-hints .v-ddwrapper-over-top:after, .mytheme .no-vertical-drag-hints.v-ddwrapper-over-top:after { + border-width: 2px; + border-radius: 4px; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + background: #8abef2; +} + +.mytheme .no-vertical-drag-hints .v-ddwrapper-over-bottom:before, .mytheme .no-vertical-drag-hints.v-ddwrapper-over-bottom:before { + border-bottom-width: 0; +} + +.mytheme .no-vertical-drag-hints .v-ddwrapper-over-bottom:after, .mytheme .no-vertical-drag-hints.v-ddwrapper-over-bottom:after { + border-width: 2px; + border-radius: 4px; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + background: #8abef2; +} + +.mytheme .no-horizontal-drag-hints.v-ddwrapper-over-left:before, .mytheme .no-horizontal-drag-hints .v-ddwrapper-over-left:before { + border-left-width: 0; +} + +.mytheme .no-horizontal-drag-hints.v-ddwrapper-over-left:after, .mytheme .no-horizontal-drag-hints .v-ddwrapper-over-left:after { + border-width: 2px; + border-radius: 4px; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + background: #8abef2; +} + +.mytheme .no-horizontal-drag-hints.v-ddwrapper-over-right:before, .mytheme .no-horizontal-drag-hints .v-ddwrapper-over-right:before { + border-right-width: 0; +} + +.mytheme .no-horizontal-drag-hints.v-ddwrapper-over-right:after, .mytheme .no-horizontal-drag-hints .v-ddwrapper-over-right:after { + border-width: 2px; + border-radius: 4px; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + background: #8abef2; +} + +.mytheme .v-ddwrapper-over-middle:after, .mytheme .v-ddwrapper-over-center:after { + border-width: 2px; + border-radius: 4px; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + background: #8abef2; +} + +.mytheme .no-box-drag-hints.v-ddwrapper:after, .mytheme .no-box-drag-hints .v-ddwrapper:after { + display: none !important; + content: none; +} + +.mytheme .v-nativebutton { + -webkit-touch-callout: none; +} + +.mytheme .v-select select { + border: 1px solid #c5c5c5; + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + color: #464646; +} + +.mytheme .v-select select:focus { + outline: none; + -webkit-box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); + box-shadow: 0 0 0 2px rgba(25, 125, 225, 0.5); +} + +.mytheme .v-select-select { + display: block; +} + +.mytheme .v-select-select + .v-textfield { + width: auto !important; + margin-top: 9px; +} + +.mytheme .v-select-select + .v-textfield + .v-nativebutton { + margin-top: 9px; + margin-left: 9px; +} + +.mytheme .v-select-error .v-select-select { + border-color: #ed473b !important; + background: #fffbfb; + color: #6c2621; +} + +.mytheme .v-popupview { + cursor: pointer; + color: #197de1; + text-decoration: underline; + font-weight: inherit; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-popupview:hover { + color: #4396ea; +} + +.mytheme .v-popupview.v-disabled { + opacity: 0.5; + filter: alpha(opacity=50) ; +} + +.mytheme .v-popupview-popup { + padding: 4px 4px; + border-radius: 4px; + background-color: white; + color: #474747; + -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.1), 0 3px 5px 0 rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.09098); + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; +} + +.mytheme .v-popupview-popup[class*="animate-in"] { + -webkit-animation: v-popupview-animate-in 120ms; + -moz-animation: v-popupview-animate-in 120ms; + animation: v-popupview-animate-in 120ms; +} + +.mytheme .v-popupview-popup[class*="animate-out"] { + -webkit-animation: valo-animate-out-fade 120ms; + -moz-animation: valo-animate-out-fade 120ms; + animation: valo-animate-out-fade 120ms; +} + +.mytheme .v-popupview-popup .popupContent > .v-margin-top { + padding-top: 12px; +} + +.mytheme .v-popupview-popup .popupContent > .v-margin-right { + padding-right: 12px; +} + +.mytheme .v-popupview-popup .popupContent > .v-margin-bottom { + padding-bottom: 12px; +} + +.mytheme .v-popupview-popup .popupContent > .v-margin-left { + padding-left: 12px; +} + +.mytheme .v-popupview-loading { + margin: 12px 12px; + height: 24px !important; + width: 24px !important; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border: 2px solid rgba(25, 125, 225, 0.2); + border-top-color: #197de1; + border-right-color: #197de1; + border-radius: 100%; + -webkit-animation: v-rotate-360 500ms infinite linear; + -moz-animation: v-rotate-360 500ms infinite linear; + animation: v-rotate-360 500ms infinite linear; + pointer-events: none; +} + +.v-ie8 .mytheme .v-popupview-loading, .v-ie9 .mytheme .v-popupview-loading { + border: none; + border-radius: 4px; + background: #fff url(../valo/shared/img/spinner.gif) no-repeat 50% 50%; + background-size: 80%; +} + +.v-ie8 .mytheme .v-popupview-loading { + min-width: 30px; + min-height: 30px; +} + +.mytheme .v-richtextarea { + -webkit-appearance: none; + -moz-appearance: none; + -ms-appearance: none; + -o-appearance: none; + appearance: none; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + margin: 0; + font: inherit; + + font-weight: 400; + line-height: normal; + height: 37px; + border-radius: 4px; + padding: 0; + border: 1px solid #c5c5c5; + background: white; + color: #474747; + -webkit-box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 #f7f7f7, 0 1px 0 rgba(255, 255, 255, 0.1); + -webkit-transition: box-shadow 180ms, border 180ms; + -moz-transition: box-shadow 180ms, border 180ms; + transition: box-shadow 180ms, border 180ms; + height: auto; + overflow: hidden; +} + +.v-ie8 .mytheme .v-richtextarea, .v-ie9 .mytheme .v-richtextarea { + line-height: 37px; + padding-top: 0; + padding-bottom: 0; +} + +.mytheme .v-richtextarea[class*="prompt"] { + color: #a3a3a3; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar { + background-color: #fafafa; + background-image: -webkit-linear-gradient(top, #fafafa 2%, #efefef 98%); + background-image: linear-gradient(to bottom,#fafafa 2%, #efefef 98%); + -webkit-box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + box-shadow: inset 0 1px 0 white, inset 0 -1px 0 #e7e7e7; + border-bottom: 1px solid #c5c5c5; + color: #464646; +} + +.mytheme .v-richtextarea .gwt-ToggleButton, .mytheme .v-richtextarea .gwt-PushButton { + display: inline-block; + line-height: 37px; + width: 37px; + text-align: center; + outline: none; +} + +.mytheme .v-richtextarea .gwt-ToggleButton:hover, .mytheme .v-richtextarea .gwt-PushButton:hover { + color: black; +} + +.mytheme .v-richtextarea .gwt-ToggleButton-down, .mytheme .v-richtextarea .gwt-ToggleButton-down-hovering { + background-color: #e0e0e0; + background-image: -webkit-linear-gradient(bottom, #e0e0e0 2%, #dcdcdc 98%); + background-image: linear-gradient(to top,#e0e0e0 2%, #dcdcdc 98%); +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top img { + display: none; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div:before { + font-family: ThemeIcons; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Bold"]:before { + content: "\f032"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Italic"]:before { + content: "\f033"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Underline"]:before { + content: "\f0cd"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Subscript"]:before { + content: "\f12c"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Superscript"]:before { + content: "\f12b"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Left Justify"]:before { + content: "\f036"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Center"]:before { + content: "\f037"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Right Justify"]:before { + content: "\f038"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Toggle Strikethrough"]:before { + content: "\f0cc"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Indent Right"]:before { + content: "\f03c"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Indent Left"]:before { + content: "\f03b"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Insert Horizontal Rule"]:before { + content: "\2014"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Insert Ordered List"]:before { + content: "\f0cb"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Insert Unordered List"]:before { + content: "\f0ca"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Insert Image"]:before { + content: "\f03e"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Create Link"]:before { + content: "\f0c1"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Remove Link"]:before { + content: "\f127"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-top div[title="Remove Formatting"]:before { + content: "\f12d"; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-bottom { + font-size: 13px; + padding: 0 9px 9px 0; +} + +.mytheme .v-richtextarea .gwt-RichTextToolbar-bottom select { + margin: 9px 0 0 9px; +} + +.mytheme .v-richtextarea .gwt-RichTextArea { + background: #fff; + border: none; + display: block; +} + +.mytheme .v-richtextarea-readonly { + padding: 5px 7px; + background: transparent; +} + +.mytheme .v-upload .v-button { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + display: inline-block; + vertical-align: top; + text-align: left; + white-space: normal; +} + +.mytheme .v-upload-immediate .v-button { + width: 100%; +} + +.mytheme .v-upload-immediate input[type="file"] { + opacity: 0; + filter: alpha(opacity=0) ; + z-index: -1; + position: absolute; + right: 0; + height: 37px; + text-align: right; + border: none; + background: transparent; +} + +.mytheme .v-Notification.v-position-top { + top: 12px; +} + +.mytheme .v-Notification.v-position-right { + right: 12px; +} + +.mytheme .v-Notification.v-position-bottom { + bottom: 12px; +} + +.mytheme .v-Notification.v-position-left { + left: 12px; +} + +.mytheme .v-Notification.v-position-assistive { + top: -9999px; + left: -9999px; +} + +.mytheme .v-Notification-animate-in { + -webkit-animation: valo-animate-in-fade 180ms 10ms backwards; + -moz-animation: valo-animate-in-fade 180ms 10ms backwards; + animation: valo-animate-in-fade 180ms 10ms backwards; +} + +.mytheme .v-Notification-animate-in.v-position-top { + -webkit-animation: valo-animate-in-slide-down 400ms 10ms backwards; + -moz-animation: valo-animate-in-slide-down 400ms 10ms backwards; + animation: valo-animate-in-slide-down 400ms 10ms backwards; +} + +.mytheme .v-Notification-animate-in.v-position-bottom { + -webkit-animation: valo-animate-in-slide-up 400ms 10ms backwards; + -moz-animation: valo-animate-in-slide-up 400ms 10ms backwards; + animation: valo-animate-in-slide-up 400ms 10ms backwards; +} + +.mytheme .v-Notification-animate-out { + -webkit-animation: valo-animate-out-fade 150ms; + -moz-animation: valo-animate-out-fade 150ms; + animation: valo-animate-out-fade 150ms; +} + +.mytheme .v-Notification-animate-out.v-position-top, .mytheme .v-Notification-animate-out.v-position-bottom { + -webkit-animation: valo-animate-out-slide-down-fade 200ms; + -moz-animation: valo-animate-out-slide-down-fade 200ms; + animation: valo-animate-out-slide-down-fade 200ms; +} + +.mytheme .v-Notification { + border-radius: 4px; + text-align: center; + position: fixed !important; + -webkit-backface-visibility: hidden; + -moz-backface-visibility: hidden; + -ms-backface-visibility: hidden; + backface-visibility: hidden; + background: white; + -webkit-box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.15); + box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.15); + padding: 19px 22px; +} + +.mytheme .v-Notification .v-Notification-caption { + color: #197de1; + font-size: 19px; + line-height: 1; +} + +.mytheme .v-Notification .v-Notification-description { + line-height: 1.4; +} + +.mytheme .v-Notification-caption { + margin: 0; + display: inline-block; + text-align: left; + font-weight: inherit; + line-height: inherit; + white-space: nowrap; + letter-spacing: 0; +} + +.mytheme .v-Notification-description, .mytheme .v-Notification-details { + margin: 0; + display: inline-block; + vertical-align: middle; + max-width: 30em; + text-align: left; + max-height: 20em; + overflow: auto; +} + +.mytheme .v-Notification-caption ~ .v-Notification-description, .mytheme .v-Notification-caption ~ .v-Notification-details { + margin-left: 24px; +} + +.mytheme .v-icon + .v-Notification-caption { + margin-left: 16px; +} + +.mytheme .v-Notification-system { + left: 0 !important; + right: 0; + max-width: 100%; + margin: 0 !important; + border-radius: 0; + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + padding: 12px 15px; + background-color: #444; + background-color: rgba(68, 68, 68, 0.9); + font-weight: 400; + line-height: 22px; +} + +.mytheme .v-Notification-system .v-Notification-description, .mytheme .v-Notification-system .v-Notification-details { + max-width: 50em; +} + +.mytheme .v-Notification-system.v-position-top { + top: 0; +} + +.mytheme .v-Notification-system.v-position-top[class*="animate-in"] { + -webkit-animation: valo-animate-in-slide-down 300ms 10ms backwards; + -moz-animation: valo-animate-in-slide-down 300ms 10ms backwards; + animation: valo-animate-in-slide-down 300ms 10ms backwards; +} + +.mytheme .v-Notification-system.v-position-top[class*="animate-out"] { + -webkit-animation: valo-animate-out-slide-up 200ms; + -moz-animation: valo-animate-out-slide-up 200ms; + animation: valo-animate-out-slide-up 200ms; +} + +.mytheme .v-Notification-system.v-position-bottom { + bottom: 0; +} + +.mytheme .v-Notification-system.v-position-bottom[class*="animate-in"] { + -webkit-animation: valo-animate-in-slide-up 300ms 10ms backwards; + -moz-animation: valo-animate-in-slide-up 300ms 10ms backwards; + animation: valo-animate-in-slide-up 300ms 10ms backwards; +} + +.mytheme .v-Notification-system.v-position-bottom[class*="animate-out"] { + -webkit-animation: valo-animate-out-slide-down 200ms; + -moz-animation: valo-animate-out-slide-down 200ms; + animation: valo-animate-out-slide-down 200ms; +} + +.mytheme .v-Notification-system .v-Notification-caption { + color: #fff; + vertical-align: middle; +} + +.mytheme .v-Notification-system .v-Notification-description, .mytheme .v-Notification-system .v-Notification-details { + color: #e6e6e6; +} + +.mytheme .v-Notification-system u { + text-decoration: none; +} + +.mytheme .v-Notification.tray { + text-align: left; +} + +.mytheme .v-Notification.tray .v-Notification-caption + .v-Notification-description { + display: block; + margin: 0.5em 0 0; +} + +.mytheme .v-Notification.warning { + background: #FFF3D2; +} + +.mytheme .v-Notification.warning .v-Notification-caption { + color: #AC7C00; +} + +.mytheme .v-Notification.warning .v-Notification-description { + color: #9D874D; +} + +.mytheme .v-Notification.error { + background: #ed473b; + font-weight: 400; + -webkit-box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.25); + box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.25); +} + +.mytheme .v-Notification.error .v-Notification-caption { + color: white; +} + +.mytheme .v-Notification.error .v-Notification-description { + color: #f4e0df; +} + +.mytheme .v-Notification.dark { + background-color: #444; + background-color: rgba(68, 68, 68, 0.9); + font-weight: 400; + line-height: 22px; +} + +.mytheme .v-Notification.dark .v-Notification-caption { + color: #fff; + vertical-align: middle; +} + +.mytheme .v-Notification.dark .v-Notification-description, .mytheme .v-Notification.dark .v-Notification-details { + color: #e6e6e6; +} + +.mytheme .v-Notification.bar { + left: 0 !important; + right: 0; + max-width: 100%; + margin: 0 !important; + border-radius: 0; + -webkit-box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25); + padding: 12px 15px; +} + +.mytheme .v-Notification.bar .v-Notification-description, .mytheme .v-Notification.bar .v-Notification-details { + max-width: 50em; +} + +.mytheme .v-Notification.bar.v-position-top { + top: 0; +} + +.mytheme .v-Notification.bar.v-position-top[class*="animate-in"] { + -webkit-animation: valo-animate-in-slide-down 300ms 10ms backwards; + -moz-animation: valo-animate-in-slide-down 300ms 10ms backwards; + animation: valo-animate-in-slide-down 300ms 10ms backwards; +} + +.mytheme .v-Notification.bar.v-position-top[class*="animate-out"] { + -webkit-animation: valo-animate-out-slide-up 200ms; + -moz-animation: valo-animate-out-slide-up 200ms; + animation: valo-animate-out-slide-up 200ms; +} + +.mytheme .v-Notification.bar.v-position-bottom { + bottom: 0; +} + +.mytheme .v-Notification.bar.v-position-bottom[class*="animate-in"] { + -webkit-animation: valo-animate-in-slide-up 300ms 10ms backwards; + -moz-animation: valo-animate-in-slide-up 300ms 10ms backwards; + animation: valo-animate-in-slide-up 300ms 10ms backwards; +} + +.mytheme .v-Notification.bar.v-position-bottom[class*="animate-out"] { + -webkit-animation: valo-animate-out-slide-down 200ms; + -moz-animation: valo-animate-out-slide-down 200ms; + animation: valo-animate-out-slide-down 200ms; +} + +.mytheme .v-Notification.small { + padding: 11px 13px; +} + +.mytheme .v-Notification.small .v-Notification-caption { + font-size: 16px; +} + +.mytheme .v-Notification.small .v-Notification-description { + font-size: 14px; +} + +.mytheme .v-Notification.closable { + padding-right: 59px; + overflow: hidden !important; + cursor: pointer; +} + +.mytheme .v-Notification.closable:after { + content: "\00d7"; + font-size: 1.5em; + position: absolute; + top: 50%; + margin-top: -12px; + right: 12px; + width: 25px; + height: 25px; + line-height: 24px; + cursor: pointer; + color: #000; + opacity: 0.5; + filter: alpha(opacity=50) ; + text-align: center; + border: 1px solid #000; + border-color: rgba(0, 0, 0, 0.3); + border-radius: 50%; + -webkit-transition: opacity 200ms; + -moz-transition: opacity 200ms; + transition: opacity 200ms; +} + +.mytheme .v-Notification.closable:hover:after { + opacity: 1; + filter: none ; +} + +.mytheme .v-Notification.closable:active:after { + background-color: #000; + color: #fff; + opacity: 0.3; + filter: alpha(opacity=30.0) ; + -webkit-transition: none 200ms; + -moz-transition: none 200ms; + transition: none 200ms; +} + +.mytheme .v-Notification.closable.dark:after, .mytheme .v-Notification.closable.error:after, .mytheme .v-Notification.closable.system:after { + color: #fff; + border-color: #fff; + border-color: rgba(255, 255, 255, 0.3); +} + +.mytheme .v-Notification.closable.dark:active:after, .mytheme .v-Notification.closable.error:active:after, .mytheme .v-Notification.closable.system:active:after { + background-color: #fff; + color: #000; +} + +.mytheme .v-Notification.closable.tray:after { + top: 16px; + margin-top: 0; +} + +.mytheme .v-Notification.success, .mytheme .v-Notification.failure { + background: #fff; + color: #555; + border: 2px solid #2c9720; +} + +.mytheme .v-Notification.success .v-Notification-caption, .mytheme .v-Notification.failure .v-Notification-caption { + color: #2c9720; + font-weight: 400; +} + +.mytheme .v-Notification.success .v-Notification-caption:before, .mytheme .v-Notification.failure .v-Notification-caption:before { + font-family: ThemeIcons; + content: "\f00c"; + margin-right: 0.5em; +} + +.mytheme .v-Notification.success.bar, .mytheme .v-Notification.failure.bar { + margin: -2px !important; +} + +.mytheme .v-Notification.failure { + border-color: #ed473b; +} + +.mytheme .v-Notification.failure .v-Notification-caption { + color: #ed473b; +} + +.mytheme .v-Notification.failure .v-Notification-caption:before { + content: "\f05e"; +} + +.mytheme .valo-menu { + height: 100%; + background-color: #4b4b4b; + background-image: -webkit-linear-gradient(right, #414141 0%, #4b4b4b 9px); + background-image: linear-gradient(to left,#414141 0%, #4b4b4b 9px); + color: #a5a5a5; + font-size: 14px; + line-height: 30px; + border-right: 1px solid #3b3b3b; + white-space: nowrap; +} + +.mytheme .valo-menu-toggle { + display: none; + position: fixed; + z-index: 200; + top: 3px; + left: 3px; + min-width: 0; +} + +.mytheme .valo-menu-part { + border-left: 1px solid #414141; + height: 100%; + padding-bottom: 37px; + overflow: auto; +} + +.mytheme .valo-menu-part:first-child { + border-left: none; +} + +.mytheme .valo-menu-title, .mytheme .valo-menu-subtitle, .mytheme .valo-menu-item { + display: block; + line-height: inherit; + white-space: nowrap; + position: relative; +} + +.mytheme .valo-menu-title .valo-menu-badge, .mytheme .valo-menu-subtitle .valo-menu-badge, .mytheme .valo-menu-item .valo-menu-badge { + position: absolute; + right: 19px; +} + +.mytheme .valo-menu-title { + line-height: 1.2; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: white; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); + padding: 12px 19px; + font-size: 14px; + border-bottom: 1px solid #1362b1; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + text-align: center; +} + +.mytheme .valo-menu-title .v-menubar.v-menubar { + background: transparent; + border-color: #1362b1; + color: inherit; + -webkit-box-shadow: none; + box-shadow: none; + text-shadow: inherit; +} + +.mytheme .valo-menu-title .v-menubar-menuitem { + background: transparent; + -webkit-box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca; + box-shadow: inset 0 1px 0 #4d98e6, inset 0 -1px 0 #166bca; + text-shadow: inherit; + font-size: 16px; + border-color: inherit; +} + +.mytheme .valo-menu-title h1, .mytheme .valo-menu-title .v-label-h1, .mytheme .valo-menu-title h2, .mytheme .valo-menu-title .v-label-h2, .mytheme .valo-menu-title h3, .mytheme .valo-menu-title .v-label-h3, .mytheme .valo-menu-title h4, .mytheme .valo-menu-title .v-label-h4 { + margin-top: 0; + margin-bottom: 0; + color: inherit; +} + +.mytheme .v-menubar-user-menu { + border: none; + border-radius: 0; + padding: 1px; + -webkit-box-shadow: none; + box-shadow: none; + text-shadow: none; + background: transparent; + color: inherit; + margin: 19px 7px; + display: block; + overflow: hidden; + text-align: center; + height: auto; + color: inherit; +} + +.mytheme .v-menubar-user-menu:focus:after { + display: none; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem { + -webkit-box-shadow: none; + box-shadow: none; + border: none; + margin-right: 1px; + border-radius: 4px; + color: #197de1; + padding: 0 12px; + -webkit-transition: color 140ms; + -moz-transition: color 140ms; + transition: color 140ms; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem:first-child, .mytheme .v-menubar-user-menu .v-menubar-menuitem:last-child, .mytheme .v-menubar-user-menu .v-menubar-menuitem:first-child:last-child { + border-radius: 4px; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem:before { + content: none; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem:hover { + color: #4396ea; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem:active { + color: inherit; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-checked, .mytheme .v-menubar-user-menu .v-menubar-menuitem-checked:first-child { + border: 1px solid #c5c5c5; + color: #197de1; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-checked .v-menubar-menuitem-caption, .mytheme .v-menubar-user-menu .v-menubar-menuitem-checked:first-child .v-menubar-menuitem-caption { + position: relative; + top: -1px; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-selected { + color: #ecf2f8; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-selected:hover { + color: #ecf2f8; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-disabled, .mytheme .v-menubar-user-menu .v-menubar-menuitem-disabled:hover { + color: inherit; +} + +.mytheme .v-menubar-user-menu > .v-menubar-menuitem { + color: inherit; + white-space: normal; + line-height: 1.4; + margin: 0; +} + +.mytheme .v-menubar-user-menu > .v-menubar-menuitem img.v-icon { + width: 56px; + height: 56px; + border-radius: 29px; + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + display: block; + margin: 0 auto 0.3em; + border: 1px solid #c5c5c5; +} + +.mytheme .v-menubar-user-menu > .v-menubar-menuitem:after { + top: 0; + right: 0; + bottom: 0; + left: 0; +} + +.mytheme .v-menubar-user-menu .v-menubar-menuitem-selected { + background: transparent; +} + +.mytheme .valo-menu-subtitle { + color: #868686; + margin: 7px 0 7px 19px; + border-bottom: 1px solid #666666; +} + +.mytheme .valo-menu-subtitle [class*="badge"] { + color: #73a5d7; +} + +.mytheme .valo-menuitems { + display: block; +} + +.mytheme .valo-menu-item { + outline: none; + font-weight: 400; + padding: 0 37px 0 19px; + cursor: pointer; + position: relative; + overflow: hidden; + text-shadow: 0 2px 0 rgba(0, 0, 0, 0.05); + -webkit-transition: background-color 300ms, color 60ms; + -moz-transition: background-color 300ms, color 60ms; + transition: background-color 300ms, color 60ms; +} + +.mytheme .valo-menu-item [class*="caption"] { + vertical-align: middle; + display: inline-block; + width: 90%; + max-width: 15em; + padding-right: 19px; + text-overflow: ellipsis; + overflow: hidden; +} + +.mytheme .valo-menu-item [class*="badge"] { + color: #73a5d7; +} + +.mytheme .valo-menu-item.selected { + background: #434343; +} + +.mytheme .valo-menu-item.selected .v-icon { + color: #197de1; +} + +.mytheme .valo-menu-item.selected [class*="badge"] { + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: #c8dbed; +} + +.mytheme .valo-menu-item:focus, .mytheme .valo-menu-item:hover, .mytheme .valo-menu-item.selected { + color: white; +} + +.mytheme .valo-menu-item span.v-icon { + min-width: 1em; + margin-right: 19px; + text-align: center; + vertical-align: middle; + -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, from(black), to(rgba(0, 0, 0, 0.75))); +} + +.mytheme .valo-menu-item span.v-icon + span { + margin-left: 0; +} + +.mytheme .valo-menu-item [class*="badge"] { + background-color: #585858; + -webkit-transition: background-color 300ms; + -moz-transition: background-color 300ms; + transition: background-color 300ms; + line-height: 1; + padding: 4px 6px; + min-width: 11px; + text-align: center; + top: 4px; + border-radius: 4px; +} + +.mytheme .valo-menu-part.large-icons { + background-color: #4b4b4b; + min-width: 74px; + max-width: 111px; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-title { + font-size: 12px; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-title .v-label-undef-w { + white-space: normal; +} + +.mytheme .valo-menu-part.large-icons .v-menubar-user-menu { + margin-left: 0; + margin-right: 0; + font-size: 11px; +} + +.mytheme .valo-menu-part.large-icons .v-menubar-user-menu img.v-icon { + width: 28px; + height: 28px; +} + +.mytheme .valo-menu-part.large-icons [class*="subtitle"] { + margin: 9px 0 0; + padding: 7px 25px 7px 9px; + line-height: 1; + border: none; + text-overflow: ellipsis; + overflow: hidden; + background: #3c3c3c; + font-size: 13px; + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); +} + +.mytheme .valo-menu-part.large-icons [class*="subtitle"] [class*="badge"] { + right: 9px; +} + +.mytheme .valo-menu-part.large-icons [class*="subtitle"] + .valo-menu-item { + border-top: none; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item { + display: block; + font-size: 26px; + line-height: 1; + padding: 12px; + text-align: center; + border-top: 1px solid #555555; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item:first-child { + border-top: none; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item [class*="caption"] { + display: block; + width: auto; + margin: 0.3em 0 0; + padding: 0; + font-size: 11px; + line-height: 1.3; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item .v-icon { + margin: 0; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item span.v-icon { + opacity: 0.8; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item.selected { + background: #434343; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item.selected .v-icon { + opacity: 1; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item.selected [class*="badge"] { + border-color: #434343; +} + +.mytheme .valo-menu-part.large-icons .valo-menu-item [class*="badge"] { + padding-left: 4px; + padding-right: 4px; + top: 7px; + right: 7px; + border: 2px solid #4b4b4b; +} + +.mytheme .valo-menu-logo { + display: block; + overflow: hidden; + width: 44px !important; + height: 44px; + border-radius: 4px; + text-align: center; + background-color: #197de1; + background-image: -webkit-linear-gradient(top, #1b87e3 2%, #166ed5 98%); + background-image: linear-gradient(to bottom,#1b87e3 2%, #166ed5 98%); + color: white; + font-size: 25px; + line-height: 44px; + margin: 19px auto; + -webkit-box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); +} + +.mytheme .valo-menu-logo:focus { + outline: none; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part { + background-color: #4b4b4b; + min-width: 74px; + max-width: 111px; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-title { + font-size: 12px; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-title .v-label-undef-w { + white-space: normal; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .v-menubar-user-menu { + margin-left: 0; + margin-right: 0; + font-size: 11px; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .v-menubar-user-menu img.v-icon { + width: 28px; + height: 28px; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part [class*="subtitle"] { + margin: 9px 0 0; + padding: 7px 25px 7px 9px; + line-height: 1; + border: none; + text-overflow: ellipsis; + overflow: hidden; + background: #3c3c3c; + font-size: 13px; + box-shadow: 0 2px 3px rgba(0, 0, 0, 0.05); +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part [class*="subtitle"] [class*="badge"] { + right: 9px; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part [class*="subtitle"] + .valo-menu-item { + border-top: none; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item { + display: block; + font-size: 26px; + line-height: 1; + padding: 12px; + text-align: center; + border-top: 1px solid #555555; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item:first-child { + border-top: none; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item [class*="caption"] { + display: block; + width: auto; + margin: 0.3em 0 0; + padding: 0; + font-size: 11px; + line-height: 1.3; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item .v-icon { + margin: 0; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item span.v-icon { + opacity: 0.8; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item.selected { + background: #434343; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item.selected .v-icon { + opacity: 1; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item.selected [class*="badge"] { + border-color: #434343; +} + +.mytheme .valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item [class*="badge"] { + padding-left: 4px; + padding-right: 4px; + top: 7px; + right: 7px; + border: 2px solid #4b4b4b; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] { + padding-top: 37px; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .v-loading-indicator { + top: 37px; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] > .v-widget { + position: relative !important; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu { + border-right: none; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu-part { + overflow: visible; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu-toggle { + display: inline-block; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu-title { + position: fixed; + z-index: 100; + top: 0; + left: 0; + right: 0; + height: 37px !important; + padding-top: 0; + padding-bottom: 0; + -webkit-backface-visibility: hidden; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu .v-menubar-user-menu { + position: fixed; + z-index: 100; + top: 0; + right: 0; + margin: 0; + padding: 0; + height: 37px; + color: #97bee5; + max-width: 30%; + -webkit-backface-visibility: hidden; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu .v-menubar-user-menu .v-menubar-menuitem { + line-height: 36px; + white-space: nowrap; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu .v-menubar-user-menu img.v-icon { + display: inline-block; + margin: 0 6px 0 0; + width: 19px; + height: 19px; + border-radius: 10px; + border: none; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menuitems { + height: 100%; + background-color: #4b4b4b; + background-image: -webkit-linear-gradient(right, #414141 0%, #4b4b4b 9px); + background-image: linear-gradient(to left,#414141 0%, #4b4b4b 9px); + color: #a5a5a5; + font-size: 14px; + line-height: 30px; + border-right: 1px solid #3b3b3b; + white-space: nowrap; + position: fixed; + z-index: 9000; + top: 37px; + bottom: 0; + height: auto; + max-width: 100%; + overflow: auto; + padding: 19px 0; + -webkit-transform: translatex(-100%); + -moz-transform: translatex(-100%); + -ms-transform: translatex(-100%); + -o-transform: translatex(-100%); + transform: translatex(-100%); + -webkit-transition: all 300ms; + -moz-transition: all 300ms; + transition: all 300ms; +} + +.mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu-visible .valo-menuitems, .mytheme .valo-menu-responsive[width-range~="0-800px"] .valo-menu-hover:hover .valo-menuitems { + -webkit-transform: translatex(0%); + -moz-transform: translatex(0%); + -ms-transform: translatex(0%); + -o-transform: translatex(0%); + transform: translatex(0%); +} + +.mytheme .valo-menu-responsive[width-range~="0-500px"] .valo-menu-toggle .v-button-caption { + display: none; +} + +.mytheme .valo-menu-responsive[width-range~="0-500px"] .valo-menu .v-menubar-user-menu .v-menubar-menuitem-caption { + display: inline-block; + width: 19px; + overflow: hidden; +} \ No newline at end of file diff --git a/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss new file mode 100644 index 0000000000..bba1d493c0 --- /dev/null +++ b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss @@ -0,0 +1,11 @@ +@import "mytheme.scss"; +@import "addons.scss"; + +// This file prefixes all rules with the theme name to avoid causing conflicts with other themes. +// The actual styles should be defined in mytheme.scss + +.mytheme { + @include addons; + @include mytheme; + +} diff --git a/vavr/README.md b/vavr/README.md index e79e3269d5..d7816f3f9f 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -3,3 +3,6 @@ - [Guide to Try in Vavr](http://www.baeldung.com/javaslang-try) - [Guide to Pattern Matching in Vavr](http://www.baeldung.com/javaslang-pattern-matching) - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) +- [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) +- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) + diff --git a/vavr/pom.xml b/vavr/pom.xml index 5356417b3e..53cd07ddf7 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -6,10 +6,11 @@ 1.0 vavr - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.BUILD-SNAPSHOT + @@ -24,11 +25,80 @@ junit ${junit.version}
-
+ + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + + + + org.awaitility + awaitility + ${awaitility.version} + test + + + + + + spring-snapshot + Spring Snapshot Repository + https://repo.spring.io/snapshot + + true + + + + snapshots + libs-snapshot + https://repo.spring.io/libs-snapshot + + + + + + spring-snapshots + http://repo.spring.io/snapshot + + + + 1.8 0.9.0 4.12 + 3.0.0 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + \ No newline at end of file diff --git a/vavr/src/main/java/com/baeldung/Application.java b/vavr/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/vavr/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +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/vavr/src/main/java/com/baeldung/repositories/VavrUserRepository.java b/vavr/src/main/java/com/baeldung/repositories/VavrUserRepository.java new file mode 100644 index 0000000000..a3dd7937f7 --- /dev/null +++ b/vavr/src/main/java/com/baeldung/repositories/VavrUserRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.repositories; + +import org.springframework.data.repository.Repository; + +import com.baeldung.vavr.User; + +import io.vavr.collection.Seq; +import io.vavr.control.Option; + +public interface VavrUserRepository extends Repository { + + Option findById(long id); + + Seq findByName(String name); + + User save(User user); + +} diff --git a/vavr/src/main/java/com/baeldung/vavr/User.java b/vavr/src/main/java/com/baeldung/vavr/User.java new file mode 100644 index 0000000000..69dd9aea24 --- /dev/null +++ b/vavr/src/main/java/com/baeldung/vavr/User.java @@ -0,0 +1,32 @@ +package com.baeldung.vavr; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String 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/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java b/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java new file mode 100644 index 0000000000..95f8191342 --- /dev/null +++ b/vavr/src/main/java/com/baeldung/vavr/either/EitherDemo.java @@ -0,0 +1,37 @@ +package com.baeldung.vavr.either; + +import java.util.HashMap; +import java.util.Map; + +import io.vavr.control.Either; + +public class EitherDemo { + + public static Object[] computeWithoutEitherUsingArray(int marks) { + Object[] results = new Object[2]; + if (marks < 85) { + results[0] = "Marks not acceptable"; + } else { + results[1] = marks; + } + return results; + } + + public static Map computeWithoutEitherUsingMap(int marks) { + Map results = new HashMap<>(); + if (marks < 85) { + results.put("FAILURE", "Marks not acceptable"); + } else { + results.put("SUCCESS", marks); + } + return results; + } + + static Either computeWithEither(int marks) { + if (marks < 85) { + return Either.left("Marks not acceptable"); + } else { + return Either.right(marks); + } + } +} diff --git a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java index ef5afe0e29..1c7d70a9a4 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java @@ -1,18 +1,24 @@ package com.baeldung.vavr; +import io.vavr.MatchError; +import io.vavr.control.Option; +import org.junit.Test; + import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import static io.vavr.API.run; -import static io.vavr.Predicates.*; +import static io.vavr.Predicates.allOf; +import static io.vavr.Predicates.anyOf; +import static io.vavr.Predicates.instanceOf; +import static io.vavr.Predicates.is; +import static io.vavr.Predicates.isIn; +import static io.vavr.Predicates.isNotNull; +import static io.vavr.Predicates.isNull; +import static io.vavr.Predicates.noneOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - -import io.vavr.MatchError; -import io.vavr.control.Option; - public class PatternMatchingUnitTest { @Test public void whenMatchesDefault_thenCorrect() { @@ -100,13 +106,11 @@ public class PatternMatchingUnitTest { }))); } - - - public void displayEven() { + private void displayEven() { System.out.println("Input is even"); } - public void displayOdd() { + private void displayOdd() { System.out.println("Input is odd"); } } diff --git a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java index 8409dbfa60..e93084f2c0 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java @@ -9,7 +9,9 @@ import org.junit.Test; import java.util.function.Predicate; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; public class PropertyBasedLongRunningUnitTest { diff --git a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java index 5ddd344c5c..08a5e20b40 100644 --- a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java @@ -5,7 +5,9 @@ import io.vavr.Function1; import io.vavr.Function2; import io.vavr.Function5; import io.vavr.Lazy; -import io.vavr.*; +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.Tuple3; import io.vavr.collection.List; import io.vavr.collection.Seq; import io.vavr.control.Option; @@ -13,23 +15,25 @@ import io.vavr.control.Try; import io.vavr.control.Validation; import org.junit.Test; -import com.baeldung.vavr.Person; -import com.baeldung.vavr.PersonValidator; - import java.util.Arrays; import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.IntStream; -import static io.vavr.API.*; -import static org.junit.Assert.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class VavrUnitTest { @Test public void givenList_whenSorts_thenCorrect() { List sortedList = List.of(3, 2, 1) - .sorted(); + .sorted(); } /* @@ -123,7 +127,7 @@ public class VavrUnitTest { @Test public void whenCreatesFunction_thenCorrect0() { Function0 getClazzName = () -> this.getClass() - .getName(); + .getName(); String clazzName = getClazzName.apply(); assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName); } @@ -257,7 +261,7 @@ public class VavrUnitTest { public void whenSumsJava8List_thenCorrect() { // Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j); int sum = IntStream.of(1, 2, 3) - .sum(); + .sum(); assertEquals(6, sum); } @@ -273,8 +277,8 @@ public class VavrUnitTest { @Test public void whenSumsVavrList_thenCorrect() { int sum = List.of(1, 2, 3) - .sum() - .intValue(); + .sum() + .intValue(); assertEquals(6, sum); } @@ -307,21 +311,21 @@ public class VavrUnitTest { int input = 2; String output; switch (input) { - case 0: - output = "zero"; - break; - case 1: - output = "one"; - break; - case 2: - output = "two"; - break; - case 3: - output = "three"; - break; - default: - output = "unknown"; - break; + case 0: + output = "zero"; + break; + case 1: + output = "one"; + break; + case 2: + output = "two"; + break; + case 3: + output = "three"; + break; + default: + output = "unknown"; + break; } assertEquals("two", output); } diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java new file mode 100644 index 0000000000..cfc789a837 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -0,0 +1,315 @@ +package com.baeldung.vavr.collections; + +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.collection.Array; +import io.vavr.collection.CharSeq; +import io.vavr.collection.HashSet; +import io.vavr.collection.Iterator; +import io.vavr.collection.List; +import io.vavr.collection.Map; +import io.vavr.collection.Queue; +import io.vavr.collection.Set; +import io.vavr.collection.SortedMap; +import io.vavr.collection.SortedSet; +import io.vavr.collection.Stream; +import io.vavr.collection.TreeMap; +import io.vavr.collection.TreeSet; +import io.vavr.collection.Vector; +import org.junit.Test; + +import java.util.Comparator; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class CollectionAPIUnitTest { + + + @Test + public void givenParams_whenListAPI_thenCorrect() { + + List list + = List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA"); + + List list1 = list.drop(2); + assertFalse(list1.contains("Java") && list1.contains("PHP")); + + List list2 = list.dropRight(2); + assertFalse(list2.contains("JAVA") && list2.contains("JShell")); + + List list3 = list.dropUntil(s -> s.contains("Shell")); + assertEquals(list3.size(), 2); + + List list4 = list.dropWhile(s -> s.length() > 0); + assertTrue(list4.isEmpty()); + + List list5 = list.take(1); + assertEquals(list5.single(), "Java"); + + List list6 = list.takeRight(1); + assertEquals(list6.single(), "JAVA"); + + List list7 = list.takeUntil(s -> s.length() > 6); + assertEquals(list7.size(), 3); + + List list8 + = list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1); + assertEquals(list8.size(), 2); + + Iterator> iterator = list.grouped(2); + assertEquals(iterator.head().size(), 2); + + Map> map = list.groupBy(e -> e.startsWith("J")); + assertEquals(map.size(), 2); + assertEquals(map.get(false).get().size(), 1); + assertEquals(map.get(true).get().size(), 5); + + String words = List.of("Boys", "Girls") + .intersperse("and") + .reduce((s1, s2) -> s1.concat( " " + s2 )) + .trim(); + + assertEquals(words, "Boys and Girls"); + + } + + @Test + public void givenEmptyList_whenStackAPI_thenCorrect() { + + List intList = List.empty(); + + List intList1 = intList.pushAll(List.rangeClosed(5,10)); + + assertEquals(intList1.peek(), Integer.valueOf(10)); + + List intList2 = intList1.pop(); + assertEquals(intList2.size(), (intList1.size() - 1) ); + + } + + @Test + public void givenList_whenPrependTail_thenCorrect() { + List intList = List.of(1, 2, 3); + + List newList = intList.tail() + .prepend(0); + + assertEquals(new Integer(1), intList.get(0)); + assertEquals(new Integer(2), intList.get(1)); + assertEquals(new Integer(3), intList.get(2)); + + assertNotSame(intList.get(0), newList.get(0)); + assertEquals(new Integer(0), newList.get(0)); + assertSame(intList.get(1), newList.get(1)); + assertSame(intList.get(2), newList.get(2)); + } + + @Test + public void givenQueue_whenEnqueued_thenCorrect() { + + Queue queue = Queue.of(1, 2, 3); + Queue secondQueue = queue.enqueueAll(List.of(4,5)); + + assertEquals(3, queue.size()); + assertEquals(5, secondQueue.size()); + + Tuple2> result = secondQueue.dequeue(); + assertEquals(Integer.valueOf(1), result._1); + + Queue tailQueue = result._2; + assertFalse(tailQueue.contains(secondQueue.get(0))); + } + + @Test + public void givenStream_whenProcessed_thenCorrect() { + + Stream s1 = Stream.tabulate(5, (i)-> i + 1); + assertEquals(s1.get(2).intValue(), 3); + + Stream s = Stream.of(2,1,3,4); + + Stream> s2 = s.zip(List.of(7,8,9)); + Tuple2 t1 = s2.get(0); + assertEquals(t1._1().intValue(), 2); + assertEquals(t1._2().intValue(), 7); + + Stream intStream = Stream.iterate(0, i -> i + 1) + .take(10); + + assertEquals(10, intStream.size()); + + long evenSum = intStream.filter(i -> i % 2 == 0) + .sum() + .longValue(); + + assertEquals(20, evenSum); + } + + @Test + public void givenArray_whenQueried_thenCorrect() { + Array intArray = Array.of(1, 2, 3); + Array newArray = intArray.removeAt(1); + + assertEquals(3, intArray.size()); + assertEquals(2, newArray.size()); + assertEquals(3, newArray.get(1).intValue()); + + Array array2 = intArray.replace(1, 5); + assertEquals(array2.get(0).intValue(), 5); + + + } + + @Test + public void givenVector_whenQueried_thenCorrect() { + Vector intVector = Vector.range(1, 5); + Vector newVector = intVector.replace(2, 6); + + assertEquals(4, intVector.size()); + assertEquals(4, newVector.size()); + + assertEquals(2, intVector.get(1).intValue()); + assertEquals(6, newVector.get(1).intValue()); + } + + @Test + public void givenCharSeq_whenProcessed_thenCorrect() { + CharSeq chars = CharSeq.of("vavr"); + CharSeq newChars = chars.replace('v', 'V'); + + assertEquals(4, chars.size()); + assertEquals(4, newChars.size()); + + assertEquals('v', chars.charAt(0)); + assertEquals('V', newChars.charAt(0)); + assertEquals("Vavr", newChars.mkString()); + } + + @Test + public void givenHashSet_whenModified_thenCorrect() { + HashSet set = HashSet.of("Red", "Green", "Blue"); + HashSet newSet = set.add("Yellow"); + + assertEquals(3, set.size()); + assertEquals(4, newSet.size()); + assertTrue(newSet.contains("Yellow")); + } + + @Test + public void givenSortedSet_whenIterated_thenCorrect() { + SortedSet set = TreeSet.of("Red", "Green", "Blue"); + assertEquals("Blue", set.head()); + + SortedSet intSet = TreeSet.of(1,2,3); + assertEquals(2, intSet.average().get().intValue()); + + } + + @Test + public void givenSortedSet_whenReversed_thenCorrect() { + SortedSet reversedSet + = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); + assertEquals("Red", reversedSet.head()); + + String str = reversedSet.mkString(" and "); + assertEquals("Red and Green and Blue", str); + } + + @Test + public void givenMap_whenIterated_thenCorrect() { + Map> map = List.rangeClosed(0, 10) + .groupBy(i -> i % 2); + + assertEquals(2, map.size()); + assertEquals(6, map.get(0).get().size()); + assertEquals(5, map.get(1).get().size()); + } + + @Test + public void givenTreeMap_whenIterated_thenCorrect() { + SortedMap map + = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); + + assertEquals(1, map.keySet().toJavaArray()[0]); + assertEquals("Four", map.get(4).get()); + } + + @Test + public void givenJavaList_whenConverted_thenCorrect() { + java.util.List javaList = java.util.Arrays.asList(1, 2, 3, 4); + List vavrList = List.ofAll(javaList); + + assertEquals(4, vavrList.size()); + assertEquals(1, vavrList.head().intValue()); + + java.util.stream.Stream javaStream = javaList.stream(); + Set vavrSet = HashSet.ofAll(javaStream); + + assertEquals(4, vavrSet.size()); + assertEquals(2, vavrSet.tail().head().intValue()); + } + + @Test + public void givenJavaStream_whenCollected_thenCorrect() { + List vavrList = IntStream.range(1, 10) + .boxed() + .filter(i -> i % 2 == 0) + .collect(List.collector()); + + assertEquals(4, vavrList.size()); + assertEquals(2, vavrList.head().intValue()); + } + + @Test + public void givenVavrList_whenConverted_thenCorrect() { + Integer[] array = List.of(1, 2, 3) + .toJavaArray(Integer.class); + assertEquals(3, array.length); + + java.util.Map map = List.of("1", "2", "3") + .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); + assertEquals(2, map.get("2").intValue()); + } + + @Test + public void givenVavrList_whenCollected_thenCorrect() { + java.util.Set javaSet = List.of(1, 2, 3) + .collect(Collectors.toSet()); + + assertEquals(3, javaSet.size()); + assertEquals(1, javaSet.toArray()[0]); + } + + @Test + public void givenVavrList_whenConvertedView_thenCorrect() { + java.util.List javaList = List.of(1, 2, 3) + .asJavaMutable(); + javaList.add(4); + + assertEquals(4, javaList.get(3).intValue()); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenVavrList_whenConvertedView_thenException() { + java.util.List javaList = List.of(1, 2, 3) + .asJava(); + + assertEquals(3, javaList.get(2).intValue()); + javaList.add(4); + } + + @Test + public void givenList_whenSquared_thenCorrect() { + List vavrList = List.of(1, 2, 3); + Number sum = vavrList.map(i -> i * i) + .sum(); + + assertEquals(14L, sum); + } +} diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java new file mode 100644 index 0000000000..155932888d --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.vavr.either; + +import io.vavr.control.Either; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EitherUnitTest { + + @Test + public void givenMarks_whenPassNumber_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(100); + int marks = result.right() + .getOrElseThrow(x -> new IllegalStateException()); + + assertEquals(100, marks); + } + + @Test + public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { + Either result = EitherDemo.computeWithEither(50); + String error = result.left() + .getOrNull(); + + assertEquals("Marks not acceptable", error); + } + + @Test + public void givenPassMarks_whenModified_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(90); + int marks = result.right() + .map(x -> x * 2) + .get(); + + assertEquals(180, marks); + } + +} diff --git a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java index 9c3e5a9cae..c7f17c2afc 100644 --- a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java @@ -3,16 +3,18 @@ package com.baeldung.vavr.exception.handling; import com.baeldung.vavr.exception.handling.client.ClientException; import com.baeldung.vavr.exception.handling.client.HttpClient; import com.baeldung.vavr.exception.handling.client.Response; -import com.baeldung.vavr.exception.handling.VavrTry; - import io.vavr.collection.Stream; import io.vavr.control.Option; import io.vavr.control.Try; import org.junit.Test; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; import static io.vavr.Predicates.instanceOf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; public class VavrTryUnitTest { @@ -26,8 +28,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Stream stream = response.toStream().map(it -> it.id); //then @@ -49,8 +51,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Option optionalResponse = response.toOption(); //then @@ -70,9 +72,9 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse) + )); //then assertTrue(recovered.isFailure()); @@ -92,10 +94,10 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse), - Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse), + Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) + )); //then assertTrue(recovered.isSuccess()); @@ -106,7 +108,7 @@ public class VavrTryUnitTest { return response.id.hashCode(); } - public int actionThatTakesTryResponse(Try response, int defaultTransformation){ + public int actionThatTakesTryResponse(Try response, int defaultTransformation) { return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation)); } diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java new file mode 100644 index 0000000000..84621e3a68 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java @@ -0,0 +1,203 @@ +package com.baeldung.vavr.future; + +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; +import static io.vavr.Predicates.exists; +import static io.vavr.Predicates.forAll; +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CancellationException; +import java.util.function.Predicate; + +import org.junit.Test; + +import io.vavr.collection.List; +import io.vavr.concurrent.Future; + +public class FutureUnitTest { + + private final String SUCCESS = "Success"; + private final String FAILURE = "Failure"; + + @Test + public void givenFunctionReturnInteger_WhenCallWithFuture_ShouldReturnFunctionValue() { + Future future = Future.of(() -> 1); + + assertEquals(1, future.get() + .intValue()); + } + + @Test + public void givenFunctionGetRemoteHttpResourceAsString_WhenCallSuccessWithFuture_ShouldReturnContentValueAsString() { + String url = "http://resource"; + String content = "Content from " + url; + Future future = Future.of(() -> getResource(url)); + + assertEquals(content, future.get()); + } + + @Test + public void givenFunctionThrowException_WhenCallWithFuture_ShouldReturnFailure() { + Future future = Future.of(() -> getResourceThrowException("")); + future.await(); + + assertTrue(future.isFailure()); + } + + @Test + public void givenAFutureReturnZero_WhenCheckFutureWithExistEvenValue_ShouldReturnRight() { + Future future = Future.of(() -> 2); + boolean result = future.exists(i -> i % 2 == 0); + + assertTrue(result); + } + + @Test + public void givenFunction_WhenCallWithFutureAndRegisterConsumerForSuccess_ShouldCallConsumerToStoreValue() { + final int[] store = new int[] { 0 }; + Future future = Future.of(() -> 1); + future.onSuccess(i -> { + store[0] = i; + }); + await().until(() -> store[0] == 1); + } + + @Test + public void givenFunctionThrowException_WhenCallWithFutureAndRegisterConsumerForFailer_ShouldCallConsumerToStoreException() { + final Throwable[] store = new Throwable[] { null }; + Future future = Future.of(() -> getResourceThrowException("")); + future.onFailure(err -> store[0] = err); + await().until(() -> RuntimeException.class.isInstance(store[0])); + } + + @Test + public void givenAFuture_WhenAddAndThenConsumer_ShouldCallConsumerWithResultOfFutureAction() { + int[] store1 = new int[1]; + int[] store2 = new int[1]; + Future future = Future.of(() -> 1); + Future andThenFuture = future.andThen(i -> store1[0] = i.get() + 1) + .andThen(i -> store2[0] = store1[0] + 1); + andThenFuture.await(); + + assertEquals(2, store1[0]); + assertEquals(3, store2[0]); + } + + @Test + public void givenAFailureFuture_WhenCallOrElseFunction_ShouldReturnNewFuture() { + Future future = Future.failed(new RuntimeException()); + Future future2 = future.orElse(Future.of(() -> 2)); + + assertEquals(2, future2.get() + .intValue()); + } + + @Test(expected = CancellationException.class) + public void givenAFuture_WhenCallCancel_ShouldReturnCancellationException() { + long waitTime = 1000; + Future future = Future.of(() -> { + Thread.sleep(waitTime); + return 1; + }); + future.cancel(); + future.await(); + future.get(); + } + + @Test + public void givenAFuture_WhenCallFallBackWithSuccessFuture_ShouldReturnFutureResult() { + String expectedResult = "take this"; + Future future = Future.of(() -> expectedResult); + Future secondFuture = Future.of(() -> "take that"); + Future futureResult = future.fallbackTo(secondFuture); + futureResult.await(); + + assertEquals(expectedResult, futureResult.get()); + } + + @Test + public void givenAFuture_WhenCallFallBackWithFailureFuture_ShouldReturnValueOfFallBackFuture() { + String expectedResult = "take that"; + Future future = Future.failed(new RuntimeException()); + Future fallbackFuture = Future.of(() -> expectedResult); + Future futureResult = future.fallbackTo(fallbackFuture); + futureResult.await(); + + assertEquals(expectedResult, futureResult.get()); + } + + @Test + public void givenGetResourceWithFuture_WhenWaitAndMatchWithPredicate_ShouldReturnSuccess() { + String url = "http://resource"; + Future future = Future.of(() -> getResource(url)); + future.await(); + String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE)); + + assertEquals(SUCCESS, s); + } + + @Test + public void givenAFailedFuture_WhenWaitAndMatchWithPredicateCheckSuccess_ShouldReturnFailed() { + Future future = Future.failed(new RuntimeException()); + future.await(); + String s = Match(future).of(Case($(future0 -> future0.isSuccess()), SUCCESS), Case($(), FAILURE)); + + assertEquals(FAILURE, s); + } + + @Test + public void givenAFuture_WhenMatchWithFuturePredicate_ShouldReturnSuccess() { + Future future = Future.of(() -> { + Thread.sleep(10); + return 1; + }); + Predicate> predicate = f -> f.exists(i -> i % 2 == 1); + String s = Match(future).of(Case($(predicate), "Even"), Case($(), "Odd")); + + assertEquals("Even", s); + } + + @Test + public void givenAListOfFutureReturnFist3Integers_WhenMatchWithExistEvenNumberPredicate_ShouldReturnSuccess() { + List> futures = getFutureOfFirst3Number(); + Predicate> predicate0 = future -> future.exists(i -> i % 2 == 0); + String s = Match(futures).of(Case($(exists(predicate0)), "Even"), Case($(), "Odd")); + + assertEquals("Even", s); + } + + @Test + public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberBiggerThanZeroPredicate_ShouldReturnSuccess() { + List> futures = getFutureOfFirst3Number(); + Predicate> predicate0 = future -> future.exists(i -> i > 0); + String s = Match(futures).of(Case($(forAll(predicate0)), "Positive numbers"), Case($(), "None")); + + assertEquals("Positive numbers", s); + } + + @Test + public void givenAListOfFutureReturnFist3Integers_WhenMatchWithForAllNumberSmallerThanZeroPredicate_ShouldReturnFailed() { + List> futures = getFutureOfFirst3Number(); + Predicate> predicate0 = future -> future.exists(i -> i < 0); + String s = Match(futures).of(Case($(forAll(predicate0)), "Negative numbers"), Case($(), "None")); + + assertEquals("None", s); + } + + private String getResource(String url) throws InterruptedException { + Thread.sleep(10); + return "Content from " + url; + } + + private String getResourceThrowException(String url) { + throw new RuntimeException("Exception when get resource " + url); + } + + private List> getFutureOfFirst3Number() { + List> futures = List.of(Future.of(() -> 1), Future.of(() -> 2), Future.of(() -> 3)); + return futures; + } +} diff --git a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java new file mode 100644 index 0000000000..63338afc24 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.vavr.repositories; + +import com.baeldung.Application; +import com.baeldung.repositories.VavrUserRepository; +import com.baeldung.vavr.User; +import io.vavr.collection.Seq; +import io.vavr.control.Option; +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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class VavrRepositoryIntegrationTest { + + @Autowired + private VavrUserRepository userRepository; + + @Before + public void setup() { + User user1 = new User(); + user1.setName("John"); + User user2 = new User(); + user2.setName("John"); + + userRepository.save(user1); + userRepository.save(user2); + } + + @Test + public void whenAddUsers_thenGetUsers() { + Option user = userRepository.findById(1L); + assertFalse(user.isEmpty()); + assertTrue(user.get().getName().equals("John")); + + Seq users = userRepository.findByName("John"); + assertEquals(2, users.size()); + } + +} diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 853c84a1b8..e44611fab0 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -164,7 +164,7 @@ 2.5 - 2.2.26 + 2.8.9 4.4.1 4.5 diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java index 1b1986417d..33c96acf52 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -21,10 +21,10 @@ public class JsonCreatorUnitTest { // arrange String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + "{" + + " \"christianName\": \"Alex\"," + + " \"surname\": \"Theedom\"" + + "}"; // act final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java index 133f8b1f21..5491168f9b 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java @@ -24,7 +24,7 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act String result = new ObjectMapper().writer(filters).writeValueAsString(author); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java index 373e8d716a..6801516dfd 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java @@ -32,8 +32,8 @@ public class JsonFormatUnitTest { Date date = df.parse(toParse); Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.setPublished(date); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java index 191330be86..62f9b498ac 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java @@ -22,8 +22,8 @@ public class JsonPropertyUnitTest { // arrange Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.configureBinding("Hardback");