BAEL-1065 Merged changes and resolved conflict in core-java/pom.xml. JMH benchmarks

This commit is contained in:
iaforek 2017-09-04 21:26:33 +01:00
commit 0831cd8340
1133 changed files with 36836 additions and 4303 deletions

1
.gitignore vendored
View File

@ -42,3 +42,4 @@ spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
*.springBeans *.springBeans

View File

@ -6,3 +6,5 @@
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java) - [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) - [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers) - [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)

View File

@ -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<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
}

View File

@ -18,12 +18,12 @@ public class MiniMax {
constructTree(root); constructTree(root);
} }
private void constructTree(Node node) { private void constructTree(Node parentNode) {
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones()); List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones());
boolean isMaxPlayer = !node.isMaxPlayer(); boolean isChildMaxPlayer = !parentNode.isMaxPlayer();
listofPossibleHeaps.forEach(n -> { listofPossibleHeaps.forEach(n -> {
Node newNode = new Node(n, isMaxPlayer); Node newNode = new Node(n, isChildMaxPlayer);
node.addChild(newNode); parentNode.addChild(newNode);
if (newNode.getNoOfBones() > 0) { if (newNode.getNoOfBones() > 0) {
constructTree(newNode); constructTree(newNode);
} }

View File

@ -0,0 +1,194 @@
package com.baeldung.algorithms.string.search;
import java.math.BigInteger;
import java.util.Random;
public class StringSearchAlgorithms {
public static long getBiggerPrime(int m) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
return prime.longValue();
}
public static long getLowerPrime(long number) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
return prime.longValue();
}
private static int getNumberOfBits(final int number) {
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
}
private static int getNumberOfBits(final long number) {
return Long.SIZE - Long.numberOfLeadingZeros(number);
}
public static int simpleTextSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0;
while ((i + patternSize) <= textSize) {
int j = 0;
while (text[i + j] == pattern[j]) {
j += 1;
if (j >= patternSize)
return i;
}
i += 1;
}
return -1;
}
public static int RabinKarpMethod(char[] pattern, char[] text) {
int patternSize = pattern.length; // m
int textSize = text.length; // n
long prime = getBiggerPrime(patternSize);
long r = 1;
for (int i = 0; i < patternSize - 1; i++) {
r *= 2;
r = r % prime;
}
long[] t = new long[textSize];
t[0] = 0;
long pfinger = 0;
for (int j = 0; j < patternSize; j++) {
t[0] = (2 * t[0] + text[j]) % prime;
pfinger = (2 * pfinger + pattern[j]) % prime;
}
int i = 0;
boolean passed = false;
int diff = textSize - patternSize;
for (i = 0; i <= diff; i++) {
if (t[i] == pfinger) {
passed = true;
for (int k = 0; k < patternSize; k++) {
if (text[i + k] != pattern[k]) {
passed = false;
break;
}
}
if (passed) {
return i;
}
}
if (i < diff) {
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
t[i + 1] = ((value % prime) + prime) % prime;
}
}
return -1;
}
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
int patternSize = pattern.length; // m
int textSize = text.length; // n
int i = 0, j = 0;
int[] shift = KnuthMorrisPrattShift(pattern);
while ((i + patternSize) <= textSize) {
while (text[i + j] == pattern[j]) {
j += 1;
if (j >= patternSize)
return i;
}
if (j > 0) {
i += shift[j - 1];
j = Math.max(j - shift[j - 1], 0);
} else {
i++;
j = 0;
}
}
return -1;
}
public static int[] KnuthMorrisPrattShift(char[] pattern) {
int patternSize = pattern.length;
int[] shift = new int[patternSize];
shift[0] = 1;
int i = 1, j = 0;
while ((i + j) < patternSize) {
if (pattern[i + j] == pattern[j]) {
shift[i + j] = i;
j++;
} else {
if (j == 0)
shift[i] = i + 1;
if (j > 0) {
i = i + shift[j - 1];
j = Math.max(j - shift[j - 1], 0);
} else {
i = i + 1;
j = 0;
}
}
}
return shift;
}
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0, j = 0;
while ((i + patternSize) <= textSize) {
j = patternSize - 1;
while (text[i + j] == pattern[j]) {
j--;
if (j < 0)
return i;
}
i++;
}
return -1;
}
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
int shift[] = new int[256];
for (int k = 0; k < 256; k++) {
shift[k] = pattern.length;
}
for (int k = 0; k < pattern.length - 1; k++) {
shift[pattern[k]] = pattern.length - 1 - k;
}
int i = 0, j = 0;
while ((i + pattern.length) <= text.length) {
j = pattern.length - 1;
while (text[i + j] == pattern[j]) {
j -= 1;
if (j < 0)
return i;
}
i = i + shift[text[i + pattern.length - 1]];
}
return -1;
}
}

View File

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

View File

@ -0,0 +1,25 @@
package algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
public class StringSearchAlgorithmsTest {
@Test
public void testStringSearchAlgorithms(){
String text = "This is some nice text.";
String pattern = "some";
int realPosition = text.indexOf(pattern);
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
}
}

4
apache-shiro/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/.idea/
/target/
/apache-shiro.iml

0
apache-shiro/README.md Normal file
View File

78
apache-shiro/pom.xml Normal file
View File

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
<slf4j-version>1.7.25</slf4j-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>${apache-shiro-core-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${apache-shiro-core-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -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<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> 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<String> roleNames = new HashSet<>();
Set<String> permissions = new HashSet<>();
principals.forEach(p -> {
try {
Set<String> 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<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if(!roles.containsKey(username)) {
throw new SQLException("username not found!");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
for (String role : roleNames) {
if (!perm.containsKey(role)) {
throw new SQLException("role not found!");
}
}
Set<String> finalSet = new HashSet<>();
for (String role : roleNames) {
finalSet.addAll(perm.get(role));
}
return finalSet;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,9 @@
[users]
user = password,admin
user2 = password2,editor
user3 = password3,author
[roles]
admin = *
editor = articles:*
author = articles:compose,articles:save

View File

@ -0,0 +1,10 @@
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Welcome Guest!</h1>
<br>
<a href="/login">Login</a>
</body>
</html>

View File

@ -0,0 +1,27 @@
<html>
<head>
<title>Login</title>
</head>
<body style="margin-left: 30px;">
<h3>Login</h3>
<br>
<form action="/login" method="post">
<#if (error?length > 0)??>
<p style="color:darkred;">${error}</p>
<#else>
</#if>
<label for="username">Username</label>
<br>
<input type="text" name="username">
<br><br>
<label for="password">Password</label>
<br>
<input type="password" name="password">
<br><br>
<input type="checkbox" name="rememberMe"> Remember Me
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

View File

@ -0,0 +1,15 @@
<html>
<head>
<title>Secure</title>
</head>
<body style="margin-left: 30px;">
<h1>Welcome ${username}!</h1>
<p><strong>Role</strong>: ${role}</p>
<p><strong>Permissions</strong></p>
<p>${permission}</p>
<br>
<form role="form" action="/logout" method="POST">
<input type="Submit" value="Logout" />
</form>
</body>
</html>

View File

@ -1,4 +1,4 @@
resource.loader=webapp resource.loader=webapp
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path = . webapp.resource.loader.path =
webapp.resource.loader.cache = true webapp.resource.loader.cache = true

View File

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

View File

@ -35,7 +35,12 @@
<configuration> <configuration>
<sourceDirectory>src/docs/asciidoc</sourceDirectory> <sourceDirectory>src/docs/asciidoc</sourceDirectory>
<outputDirectory>target/docs/asciidoc</outputDirectory> <outputDirectory>target/docs/asciidoc</outputDirectory>
<attributes>
<pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir>
<pdf-style>custom</pdf-style>
</attributes>
<backend>pdf</backend> <backend>pdf</backend>
<doctype>book</doctype>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -1,3 +1,13 @@
== Introduction Section :icons: font
Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#.
= Generating book with AsciiDoctorj
Baeldung
[abstract]
This is the actual content.
== First Section
This is first section of the book where you can include some nice icons like icon:comment[].
You can also create http://www.baeldung.com[links]

View File

@ -0,0 +1,29 @@
title_page:
align: left
page:
layout: portrait
margin: [0.75in, 1in, 0.75in, 1in]
size: A4
base:
font_color: #333333
line_height_length: 17
line_height: $base_line_height_length / $base_font_size
link:
font_color: #009900
header:
height: 0.5in
line_height: 1
recto_content:
center: '{document-title}'
verso_content:
center: '{document-title}'
footer:
height: 0.5in
line_height: 1
recto_content:
right: '{chapter-title} | *{page-number}*'
verso_content:
left: '*{page-number}* | {chapter-title}'

View File

@ -18,9 +18,41 @@
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version> <aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version> <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version> <gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.154</aws-java-sdk.version>
<junit.version>4.12</junit.version>
<mockito-core.version>2.8.9</mockito-core.version>
<assertj-core.version>3.8.0</assertj-core.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId> <artifactId>aws-lambda-java-core</artifactId>

View File

@ -0,0 +1,87 @@
package com.baeldung.s3;
import java.io.File;
import java.util.List;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CopyObjectResult;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
public class AWSS3Service {
private final AmazonS3 s3client;
public AWSS3Service() {
this(new AmazonS3Client() {
});
}
public AWSS3Service(AmazonS3 s3client) {
this.s3client = s3client;
}
//is bucket exist?
public boolean doesBucketExist(String bucketName) {
return s3client.doesBucketExist(bucketName);
}
//create a bucket
public Bucket createBucket(String bucketName) {
return s3client.createBucket(bucketName);
}
//list all buckets
public List<Bucket> listBuckets() {
return s3client.listBuckets();
}
//delete a bucket
public void deleteBucket(String bucketName) {
s3client.deleteBucket(bucketName);
}
//uploading object
public PutObjectResult putObject(String bucketName, String key, File file) {
return s3client.putObject(bucketName, key, file);
}
//listing objects
public ObjectListing listObjects(String bucketName) {
return s3client.listObjects(bucketName);
}
//get an object
public S3Object getObject(String bucketName, String objectKey) {
return s3client.getObject(bucketName, objectKey);
}
//copying an object
public CopyObjectResult copyObject(
String sourceBucketName,
String sourceKey,
String destinationBucketName,
String destinationKey
) {
return s3client.copyObject(
sourceBucketName,
sourceKey,
destinationBucketName,
destinationKey
);
}
//deleting an object
public void deleteObject(String bucketName, String objectKey) {
s3client.deleteObject(bucketName, objectKey);
}
//deleting multiple Objects
public DeleteObjectsResult deleteObjects(DeleteObjectsRequest delObjReq) {
return s3client.deleteObjects(delObjReq);
}
}

View File

@ -0,0 +1,101 @@
package com.baeldung.s3;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class S3Application {
private static final AWSCredentials credentials;
private static String bucketName;
static {
//put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) throws IOException {
//set-up the client
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
AWSS3Service awsService = new AWSS3Service(s3client);
bucketName = "baeldung-bucket";
//creating a bucket
if(awsService.doesBucketExist(bucketName)) {
System.out.println("Bucket name is not available."
+ " Try again with a different Bucket name.");
return;
}
awsService.createBucket(bucketName);
//list all the buckets
for(Bucket s : awsService.listBuckets() ) {
System.out.println(s.getName());
}
//deleting bucket
awsService.deleteBucket("baeldung-bucket-test2");
//uploading object
awsService.putObject(
bucketName,
"Document/hello.txt",
new File("/Users/user/Document/hello.txt")
);
//listing objects
ObjectListing objectListing = awsService.listObjects(bucketName);
for(S3ObjectSummary os : objectListing.getObjectSummaries()) {
System.out.println(os.getKey());
}
//downloading an object
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
S3ObjectInputStream inputStream = s3object.getObjectContent();
FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt"));
//copying an object
awsService.copyObject(
"baeldung-bucket",
"picture/pic.png",
"baeldung-bucket2",
"Document/picture.png"
);
//deleting an object
awsService.deleteObject(bucketName, "Document/hello.txt");
//deleting multiple objects
String objkeyArr[] = {
"Document/hello2.txt",
"Document/picture.png"
};
DeleteObjectsRequest delObjReq = new DeleteObjectsRequest("baeldung-bucket")
.withKeys(objkeyArr);
awsService.deleteObjects(delObjReq);
}
}

View File

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

11
bootique/config.yml Normal file
View File

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

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>bootique-parent</artifactId>
<groupId>io.bootique.parent</groupId>
<version>0.12</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.bootique</groupId>
<artifactId>bootique</artifactId>
<name>bootique</name>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.bootique</groupId>
<artifactId>bootique-test</artifactId>
<version>0.23</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.bom</groupId>
<artifactId>bootique-bom</artifactId>
<version>0.23</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<main.class>com.baeldung.bootique.App</main.class>
</properties>
</project>

66
bootique/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.bootique</groupId>
<artifactId>bootique</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>bootique</name>
<url>http://maven.apache.org</url>
<properties>
<main.class>com.baeldung.bootique.App</main.class>
</properties>
<parent>
<groupId>io.bootique.parent</groupId>
<artifactId>bootique-parent</artifactId>
<version>0.12</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.bom</groupId>
<artifactId>bootique-bom</artifactId>
<version>0.23</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.bootique.jersey</groupId>
<artifactId>bootique-jersey</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.bootique.logback</groupId>
<artifactId>bootique-logback</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.bootique</groupId>
<artifactId>bootique-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<String> arg0) {
// ...
}
@Override
public void stdout(String arg0) {
// ...
}
@Override
public void stderr(String arg0, Throwable arg1) {
// ...
}
@Override
public void stderr(String arg0) {
// ...
}
}).autoLoadModules().exec();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,7 @@
package com.baeldung.bootique.service;
public interface HelloService {
boolean save();
}

View File

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

View File

@ -0,0 +1 @@
com.baeldung.bootique.module.ModuleProvider

View File

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

View File

@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@SpringBootApplication @SpringBootApplication
@ComponentScan(basePackages="com.baeldung.camel") @ComponentScan(basePackages="com.baeldung.camel")
public class Application extends SpringBootServletInitializer { public class Application{
@Value("${server.port}") @Value("${server.port}")
String serverPort; String serverPort;
@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer {
.bindingMode(RestBindingMode.json) .bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true"); .dataFormatProperty("prettyPrint", "true");
/** /**
The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. The Rest DSL supports automatic binding json/xml contents to/from
By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. POJOs using Camels Data Format.
You may want to use binding if you develop POJOs that maps to your REST services request and response types. By default the binding mode is off, meaning there is no automatic
This allows you, as a developer, to work with the POJOs in Java code. binding happening for incoming and outgoing messages.
You may want to use binding if you develop POJOs that maps to
your REST services request and response types.
*/ */
rest("/api/").description("Teste REST Service") rest("/api/").description("Teste REST Service")

26
core-java-8/.gitignore vendored Normal file
View File

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

32
core-java-8/README.md Normal file
View File

@ -0,0 +1,32 @@
=========
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [Guide to Java 8s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
- [Java 8 Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
- [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 Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [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)
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
- [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)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)

258
core-java-8/pom.xml Normal file
View File

@ -0,0 +1,258 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-8</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-8</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-8</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
</project>

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
@FunctionalInterface @FunctionalInterface
public interface Bar { public interface Bar {

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
@FunctionalInterface @FunctionalInterface
public interface Baz { public interface Baz {

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
@FunctionalInterface @FunctionalInterface
public interface Foo { public interface Foo {

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
@FunctionalInterface @FunctionalInterface
public interface FooExtended extends Baz, Bar { public interface FooExtended extends Baz, Bar {

View File

@ -1,5 +1,6 @@
package com.baeldung; package com.baeldung;
import java.util.function.Function; import java.util.function.Function;
public class UseFoo { public class UseFoo {

View File

@ -0,0 +1,11 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
public class UseLocalDateTime {
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
return LocalDateTime.parse(representation);
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.stream; package com.baeldung.stream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

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

View File

@ -15,7 +15,9 @@ public class UseLocalDateTimeUnitTest {
@Test @Test
public void givenString_whenUsingParse_thenLocalDateTime() { public void givenString_whenUsingParse_thenLocalDateTime() {
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate()); assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime()); .toLocalDate());
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalTime());
} }
} }

View File

@ -15,12 +15,14 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenValues_whenUsingFactoryOf_thenLocalDate() { 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 @Test
public void givenString_whenUsingParse_thenLocalDate() { 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 @Test
@ -30,12 +32,14 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenDate_whenUsingPlus_thenNextDay() { public void givenDate_whenUsingPlus_thenNextDay() {
assertEquals(LocalDate.now().plusDays(1), useLocalDate.getNextDay(LocalDate.now())); assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()));
} }
@Test @Test
public void givenDate_whenUsingMinus_thenPreviousDay() { public void givenDate_whenUsingMinus_thenPreviousDay() {
assertEquals(LocalDate.now().minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())); assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()));
} }
@Test @Test
@ -45,7 +49,8 @@ public class UseLocalDateUnitTest {
@Test @Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
assertEquals(1, useLocalDate.getFirstDayOfMonth().getDayOfMonth()); assertEquals(1, useLocalDate.getFirstDayOfMonth()
.getDayOfMonth());
} }
@Test @Test

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