This commit is contained in:
Jonathan Cook 2020-07-13 11:32:51 +02:00
commit df6546ff28
383 changed files with 5480 additions and 1403 deletions

2
.gitignore vendored
View File

@ -85,3 +85,5 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
libraries-2/*.db

View File

@ -1,16 +1,21 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
@ -20,7 +25,7 @@ public class GraphImageGenerationUnitTest {
@Before
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png");
File imgFile = new File("src/test/resources/graph1.png");
imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1";
@ -34,12 +39,18 @@ public class GraphImageGenerationUnitTest {
g.addEdge(x3, x1);
}
@After
public void cleanup() {
File imgFile = new File("src/test/resources/graph1.png");
imgFile.deleteOnExit();
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png");
File imgFile = new File("src/test/resources/graph1.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists());

View File

@ -1,7 +1,7 @@
package com.baeldung.algorithms.play2048;
public class Play2048 {
private static final int SIZE = 3;
private static final int SIZE = 4;
private static final int INITIAL_NUMBERS = 2;
public static void main(String[] args) {

View File

@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-miscellaneous-1</artifactId>
<artifactId>apache-libraries</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-libraries</name>

View File

@ -39,10 +39,19 @@
<artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- spring-sec -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<apache-shiro-core-version>1.5.3</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
</properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.comparison.shiro;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
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;
public class CustomRealm extends JdbcRealm {
private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> permissions = new HashMap<>();
{
credentials.put("Tom", "password");
credentials.put("Jerry", "password");
roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN")));
roles.put("Tom", new HashSet<>(Arrays.asList("USER")));
permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE")));
permissions.put("USER", new HashSet<>(Arrays.asList("READ")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (userToken.getUsername() == null || userToken.getUsername()
.isEmpty() || !credentials.containsKey(userToken.getUsername())) {
throw new UnknownAccountException("User doesn't exist");
}
return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new HashSet<>();
Set<String> permissions = new HashSet<>();
for (Object user : principals) {
try {
roles.addAll(getRoleNamesForUser(null, (String) user));
permissions.addAll(getPermissions(null, null, roles));
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles);
authInfo.setStringPermissions(permissions);
return authInfo;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if (!roles.containsKey(username)) {
throw new SQLException("User doesn't exist");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException {
Set<String> userPermissions = new HashSet<>();
for (String role : roles) {
if (!permissions.containsKey(role)) {
throw new SQLException("Role doesn't exist");
}
userPermissions.addAll(permissions.get(role));
}
return userPermissions;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.comparison.shiro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroApplication {
public static void main(String... args) {
SpringApplication.run(ShiroApplication.class, args);
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition filter = new DefaultShiroFilterChainDefinition();
filter.addPathDefinition("/home", "authc");
filter.addPathDefinition("/**", "anon");
return filter;
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.comparison.shiro.controllers;
import javax.servlet.http.HttpServletRequest;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.servlet.mvc.support.RedirectAttributes;
import com.baeldung.comparison.shiro.models.UserCredentials;
@Controller
public class ShiroController {
private Logger logger = LoggerFactory.getLogger(ShiroController.class);
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword());
try {
subject.login(token);
} catch (AuthenticationException ae) {
logger.error(ae.getMessage());
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/home";
}
@GetMapping("/home")
public String getMeHome(Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(Model model) {
addUserAttributes(model);
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("adminContent", "only admin can view this");
}
return "comparison/home";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
private void addUserAttributes(Model model) {
Subject currentUser = SecurityUtils.getSubject();
String permission = "";
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("role", "ADMIN");
} else if (currentUser.hasRole("USER")) {
model.addAttribute("role", "USER");
}
if (currentUser.isPermitted("READ")) {
permission = permission + " READ";
}
if (currentUser.isPermitted("WRITE")) {
permission = permission + " WRITE";
}
model.addAttribute("username", currentUser.getPrincipal());
model.addAttribute("permission", permission);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.comparison.shiro.models;
public class UserCredentials {
private String username;
private String password;
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 = " + getUsername();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.comparison.springsecurity;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {ShiroAutoConfiguration.class,
ShiroAnnotationProcessorAutoConfiguration.class,
ShiroWebAutoConfiguration.class,
ShiroWebFilterConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.comparison.springsecurity.config;
import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests(authorize -> authorize.antMatchers("/index", "/login")
.permitAll()
.antMatchers("/home", "/logout")
.authenticated()
.antMatchers("/admin/**")
.hasRole("ADMIN"))
.formLogin(formLogin -> formLogin.loginPage("/login")
.failureUrl("/login-error"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("Jerry")
.password(passwordEncoder().encode("password"))
.authorities("READ", "WRITE")
.roles("ADMIN")
.and()
.withUser("Tom")
.password(passwordEncoder().encode("password"))
.authorities("READ")
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.comparison.springsecurity.web;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
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.RequestMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", "Invalid Credentials");
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req) {
return "redirect:/home";
}
@GetMapping("/home")
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this");
return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import java.sql.Connection;
import java.sql.SQLException;

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
@ -7,12 +7,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* Created by smatt on 21/08/2017.
*/
@SpringBootApplication
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroSpringApplication {
private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class);
@ -29,7 +30,7 @@ public class ShiroSpringApplication {
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
public ShiroFilterChainDefinition filterChainDefinition() {
DefaultShiroFilterChainDefinition filter
= new DefaultShiroFilterChainDefinition();

View File

@ -1,6 +1,5 @@
package com.baeldung.controllers;
package com.baeldung.intro.controllers;
import com.baeldung.models.UserCredentials;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
@ -13,6 +12,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.intro.models.UserCredentials;
import javax.servlet.http.HttpServletRequest;
@Controller

View File

@ -1,4 +1,4 @@
package com.baeldung.models;
package com.baeldung.intro.models;
public class UserCredentials {

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;

View File

@ -0,0 +1,19 @@
<html>
<head>
<title>Home Page</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>
<a href="/admin">Admin only</a>
<#if adminContent??>
${adminContent}
</#if>
<br>
<form role="form" action="/logout" method="POST">
<input type="Submit" value="Logout" />
</form>
</body>
</html>

View File

@ -0,0 +1,10 @@
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Welcome Guest!</h1>
<br>
Go to the <a href="/home">secured page
</body>
</html>

View File

@ -0,0 +1,25 @@
<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="submit" value="Submit">
</form>
</body>
</html>

View File

@ -0,0 +1,20 @@
package com.baeldung.comparison.shiro;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.shiro.ShiroApplication;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { ShiroApplication.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.comparison.springsecurity;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.springsecurity.Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { Application.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -13,10 +13,6 @@
<relativePath>../parent-boot-2</relativePath>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>

View File

@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>cf-uaa-oauth2-client</artifactId>
<name>uaa-client-webapp</name>
<name>cf-uaa-oauth2-client</name>
<description>Demo project for Spring Boot</description>
<parent>

View File

@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-8-datetime-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

View File

@ -0,0 +1,23 @@
package com.baeldung.java9.currentmethod;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CurrentExecutingMethodUnitTest {
@Test
public void givenJava9_whenWalkingTheStack_thenFindMethod() {
StackWalker walker = StackWalker.getInstance();
Optional<String> methodName = walker.walk(frames -> frames
.findFirst()
.map(StackWalker.StackFrame::getMethodName)
);
assertTrue(methodName.isPresent());
assertEquals("givenJava9_whenWalkingTheStack_thenFindMethod", methodName.get());
}
}

View File

@ -13,32 +13,6 @@
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@ -66,6 +40,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

View File

@ -14,32 +14,6 @@
<name>core-java-arrays-sorting</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Utilities -->
<dependency>
@ -74,6 +48,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

View File

@ -27,6 +27,11 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,47 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
public class ConvertPrimitivesArrayToList {
public static void failConvert() {
int[] input = new int[]{1,2,3,4};
// List<Integer> inputAsList = Arrays.asList(input);
}
public static List<Integer> iterateConvert(int[] input) {
List<Integer> output = new ArrayList<Integer>();
for (int value : input) {
output.add(value);
}
return output;
}
public static List<Integer> streamConvert(int[] input) {
List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> streamConvertIntStream(int[] input) {
List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> guavaConvert(int[] input) {
List<Integer> output = Ints.asList(input);
return output;
}
public static List<Integer> apacheCommonConvert(int[] input) {
Integer[] outputBoxed = ArrayUtils.toObject(input);
List<Integer> output = Arrays.asList(outputBoxed);
return output;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.google.common.primitives.Ints;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConvertPrimitivesArrayToListUnitTest {
@Test
public void givenArrayWithPrimitives_whenIterativeConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.iterateConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenIntStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvertIntStream(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenGuavaConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.guavaConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenApacheCommonConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.apacheCommonConvert(new int[]{1,2,3,4}));
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.concurrent.localvariables;
public class LocalAndLambda {
public static void main(String... args) {
String text = "";
// Un-commenting the next line will break compilation, because text is no longer effectively final
// text = "675";
new Thread(() -> System.out.println(text)).start();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.localvariables;
import java.security.SecureRandom;
public class LocalVariables implements Runnable {
private int field;
public static void main(String... args) {
LocalVariables target = new LocalVariables();
new Thread(target).start();
new Thread(target).start();
}
@Override
public void run() {
field = new SecureRandom().nextInt();
int local = new SecureRandom().nextInt();
System.out.println(field + " - " + local);
}
}

View File

@ -33,7 +33,6 @@
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.lang3.version>3.10</commons.lang3.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>

View File

@ -0,0 +1,55 @@
package com.baeldung.exceptionininitializererror;
import org.junit.Test;
import java.lang.reflect.Constructor;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExceptionInInitializerErrorUnitTest {
@Test
public void givenStaticVar_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticVar::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(RuntimeException.class);
}
@Test
public void givenStaticBlock_whenThrows_thenWrapsItInAnExceptionInInitializerError() {
assertThatThrownBy(StaticBlock::new)
.isInstanceOf(ExceptionInInitializerError.class)
.hasCauseInstanceOf(ArithmeticException.class);
}
private static class CheckedConvention {
private static Constructor<?> constructor;
static {
try {
constructor = CheckedConvention.class.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e);
}
}
}
private static class StaticVar {
private static int state = initializeState();
private static int initializeState() {
throw new RuntimeException();
}
}
private static class StaticBlock {
private static int state;
static {
state = 42 / 0;
}
}
}

View File

@ -2,4 +2,10 @@
This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:
### Relevant Articles:
- [Memory Layout of Objects in Java](https://www.baeldung.com/java-memory-layout)
- [Measuring Object Sizes in the JVM](https://www.baeldung.com/jvm-measuring-object-sizes)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)

View File

@ -0,0 +1,10 @@
package com.baeldung.objectsize;
public class Course {
private String name;
public Course(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.objectsize;
public class InstrumentedSize {
public static void main(String[] args) {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println(ObjectSizeCalculator.sizeOf(course));
}
}

View File

@ -0,0 +1 @@
Premain-Class: com.baeldung.objectsize.ObjectSizeCalculator

View File

@ -0,0 +1,16 @@
package com.baeldung.objectsize;
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long sizeOf(Object o) {
return instrumentation.getObjectSize(o);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.objectsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import org.openjdk.jol.vm.VM;
public class ObjectSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheProfClassLayout() {
System.out.println(ClassLayout.parseClass(Professor.class).toPrintable());
}
@Test
public void printingTheCourseClassLayout() {
System.out.println(ClassLayout.parseClass(Course.class).toPrintable());
}
@Test
public void printingACourseInstanceLayout() {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println("The shallow size is :" + VM.current().sizeOf(course));
System.out.println(ClassLayout.parseInstance(course).toPrintable());
System.out.println(ClassLayout.parseInstance(ds).toPrintable());
System.out.println(ClassLayout.parseInstance(ds.toCharArray()).toPrintable());
System.out.println(GraphLayout.parseInstance(course).totalSize());
System.out.println(GraphLayout.parseInstance(course).toFootprint());
System.out.println(GraphLayout.parseInstance(course).toPrintable());
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.objectsize;
import java.time.LocalDate;
import java.util.List;
public class Professor {
private String name;
private boolean tenured;
private List<Course> courses;
private int level;
private LocalDate birthDay;
private double lastEvaluation;
public Professor(String name, boolean tenured, List<Course> courses,
int level, LocalDate birthDay, double lastEvaluation) {
this.name = name;
this.tenured = tenured;
this.courses = courses;
this.level = level;
this.birthDay = birthDay;
this.lastEvaluation = lastEvaluation;
}
}

View File

@ -11,8 +11,7 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [A Guide to System.exit()](https://www.baeldung.com/java-system-exit)
- [Guide to System.gc()](https://www.baeldung.com/java-system-gc)
- [Runtime.getRuntime().halt() vs System.exit() in Java](https://www.baeldung.com/java-runtime-halt-vs-system-exit)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
- [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread)
- [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- More articles: [[next -->]](/core-java-modules/core-java-jvm-2)

View File

@ -13,4 +13,4 @@ This module contains articles about core features in the Java language
- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values)
- [Comparing Objects in Java](https://www.baeldung.com/java-comparing-objects)
- [Casting int to Enum in Java](https://www.baeldung.com/java-cast-int-to-enum)
- [[<-- Prev]](/core-java-modules/core-java-lang)
[[ <-- Prev]](/core-java-modules/core-java-lang)[[Next --> ]](/core-java-modules/core-java-lang-3)

View File

@ -0,0 +1,5 @@
## Core Java Lang (Part 3)
This module contains articles about core features in the Java language
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj.version>3.12.2</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class IsoscelesTriangle extends Triangle {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public interface Shape {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.isinstancevsisassignablefrom;
public class Triangle implements Shape {
}

View File

@ -0,0 +1,67 @@
package com.baeldung.isinstancevsisassignablefrom;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsInstanceIsAssignableFromUnitTest {
@Test
public void whenUsingIsInstanceProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
Shape nonspecificShape = null;
assertTrue(Shape.class.isInstance(shape));
assertTrue(Shape.class.isInstance(triangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle2));
assertFalse(Shape.class.isInstance(nonspecificShape));
assertTrue(Triangle.class.isInstance(shape));
assertTrue(Triangle.class.isInstance(triangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle2));
assertFalse(IsoscelesTriangle.class.isInstance(shape));
assertFalse(IsoscelesTriangle.class.isInstance(triangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle2));
}
@Test
public void whenUsingIsAssignableFromProperly_desiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
assertFalse(shape.getClass().isAssignableFrom(Shape.class));
assertTrue(shape.getClass().isAssignableFrom(shape.getClass()));
assertTrue(shape.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(triangle.getClass().isAssignableFrom(Shape.class));
assertTrue(triangle.getClass().isAssignableFrom(shape.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.stringtoboolean;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StringToBooleanUnitTest {
@Test
public void givenStringTrue_whenUsingParseBoolean_thenTrue() {
assertThat(Boolean.parseBoolean("true")).isTrue();
}
@Test
public void givenStringTrue_whenUsingValueOf_thenTrue() {
assertThat(Boolean.valueOf("true")).isTrue();
}
@Test
public void givenStringTrue_whenUsingGetBoolean_thenFalse() {
assertThat(Boolean.getBoolean("true")).isFalse();
}
@Test
public void givenSystemProperty_whenUsingGetBoolean_thenTrue() {
System.setProperty("CODING_IS_FUN", "true");
assertThat(Boolean.getBoolean("CODING_IS_FUN")).isTrue();
}
}

View File

@ -13,4 +13,5 @@ This module contains articles about core features in the Java language
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [[More --> ]](/core-java-modules/core-java-lang-2)
[[Next --> ]](/core-java-modules/core-java-lang-2)

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-reflection-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-reflection-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<build>
<finalName>core-java-reflection-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>

View File

@ -0,0 +1,87 @@
package com.baeldung.reflection.access.privatefields;
public class Person {
private String name = "John";
private byte age = 30;
private short uidNumber = 5555;
private int pinCode = 452002;
private long contactNumber = 123456789L;
private float height = 6.1242f;
private double weight = 75.2564;
private char gender = 'M';
private boolean active = true;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public short getUidNumber() {
return uidNumber;
}
public void setUidNumber(short uidNumber) {
this.uidNumber = uidNumber;
}
public int getPinCode() {
return pinCode;
}
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}
public long getContactNumber() {
return contactNumber;
}
public void setContactNumber(long contactNumber) {
this.contactNumber = contactNumber;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}

View File

@ -0,0 +1,168 @@
package com.baeldung.reflection.access.privatefields;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class AccessPrivateFieldsUnitTest {
@Test
public void whenGetIntegerFields_thenSuccess() throws Exception {
Person person = new Person();
Field ageField = person.getClass()
.getDeclaredField("age");
ageField.setAccessible(true);
byte age = ageField.getByte(person);
Assertions.assertEquals(30, age);
Field uidNumberField = person.getClass()
.getDeclaredField("uidNumber");
uidNumberField.setAccessible(true);
short uidNumber = uidNumberField.getShort(person);
Assertions.assertEquals(5555, uidNumber);
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
int pinCode = pinCodeField.getInt(person);
Assertions.assertEquals(452002, pinCode);
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
long contactNumber = contactNumberField.getLong(person);
Assertions.assertEquals(123456789L, contactNumber);
}
@Test
public void whenDoAutoboxing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Integer pinCode = pinCodeField.getInt(person);
Assertions.assertEquals(452002, pinCode);
}
@Test
public void whenDoWidening_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Long pinCode = pinCodeField.getLong(person);
Assertions.assertEquals(452002L, pinCode);
}
@Test
public void whenGetFloatingTypeFields_thenSuccess() throws Exception {
Person person = new Person();
Field heightField = person.getClass()
.getDeclaredField("height");
heightField.setAccessible(true);
float height = heightField.getFloat(person);
Assertions.assertEquals(6.1242f, height);
Field weightField = person.getClass()
.getDeclaredField("weight");
weightField.setAccessible(true);
double weight = weightField.getDouble(person);
Assertions.assertEquals(75.2564, weight);
}
@Test
public void whenGetCharacterFields_thenSuccess() throws Exception {
Person person = new Person();
Field genderField = person.getClass()
.getDeclaredField("gender");
genderField.setAccessible(true);
char gender = genderField.getChar(person);
Assertions.assertEquals('M', gender);
}
@Test
public void whenGetBooleanFields_thenSuccess() throws Exception {
Person person = new Person();
Field activeField = person.getClass()
.getDeclaredField("active");
activeField.setAccessible(true);
boolean active = activeField.getBoolean(person);
Assertions.assertTrue(active);
}
@Test
public void whenGetObjectFields_thenSuccess() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
String name = (String) nameField.get(person);
Assertions.assertEquals("John", name);
}
@Test
public void givenInt_whenGetStringField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.getInt(person));
}
@Test
public void givenInt_whenGetLongField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> contactNumberField.getInt(person));
}
@Test
public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
Assertions.assertThrows(IllegalAccessException.class, () -> nameField.get(person));
}
@Test
public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass()
.getDeclaredField("firstName"));
}
@Test
public void whenAccessingNullProperty_thenNullPointerException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NullPointerException.class, () -> person.getClass()
.getDeclaredField(null));
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.regex.countmatches;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* Unit Test intended to count number of matches of a RegEx using Java 8 and 9.
*
* Java 9 is needed to run the commented out tests.
*/
public class CountMatchesUnitTest {
private static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("([a-z0-9_.-]+)@([a-z0-9_.-]+[a-z])");
private static final String TEXT_CONTAINING_EMAIL_ADDRESSES = "You can contact me through: writer@baeldung.com, editor@baeldung.com and team@bealdung.com";
private static final String TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES = "Valid emails are: me@gmail.com, you@baeldung.com, contact@hotmail.com, press@anysite.com and support@bealdung.com";
private static final String TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES = "Try to contact us at team@baeldung.comeditor@baeldung.com, support@baeldung.com.";
@Test
public void givenContainingEmailString_whenJava8Match_thenCountMacthesFound() {
Matcher countEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_EMAIL_ADDRESSES);
int count = 0;
while (countEmailMatcher.find()) {
count++;
}
assertEquals(3, count);
}
@Test
public void givenContainingFiveEmailsString_whenJava8Match_thenCountMacthesFound() {
Matcher countFiveEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES);
int count = 0;
while (countFiveEmailsMatcher.find()) {
count++;
}
assertEquals(5, count);
}
@Test
public void givenStringWithoutEmails_whenJava8Match_thenCountMacthesNotFound() {
Matcher noEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher("Simple text without emails.");
int count = 0;
while (noEmailMatcher.find()) {
count++;
}
assertEquals(0, count);
}
@Test
public void givenStringWithOverlappingEmails_whenJava8Match_thenCountWrongMatches() {
Matcher countOverlappingEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES);
int count = 0;
while (countOverlappingEmailsMatcher.find()) {
count++;
}
assertNotEquals(3, count);
}
@Test
public void givenContainingEmailString_whenStartingInJava9Match_thenCountMacthesFound() {
// uncomment to try with Java 9
// Matcher countEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_EMAIL_ADDRESSES);
// long count = countEmailMatcher.results().count();
// assertEquals(3, count);
}
@Test
public void givenContainingFiveEmailsString_whenStartingInJava9Match_thenCountMacthesFound() {
// uncomment to try with Java 9
// Matcher countFiveEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_FIVE_EMAIL_ADDRESSES);
// long count = countFiveEmailsMatcher.results().count();
// assertEquals(5, count);
}
@Test
public void givenStringWithoutEmails_whenJava9Match_thenCountMacthesNotFound() {
// uncomment to try with Java 9
// Matcher noEmailMatcher = EMAIL_ADDRESS_PATTERN.matcher("Simple text without emails.");
// long count = noEmailMatcher.results().count();
// assertEquals(0, count);
}
@Test
public void givenStringWithOverlappingEmails_whenJava9Match_thenCountWrongMatches() {
// uncomment to try with Java 9
// Matcher countOverlappingEmailsMatcher = EMAIL_ADDRESS_PATTERN.matcher(TEXT_CONTAINING_OVERLAP_EMAIL_ADDRESSES);
// long count = countOverlappingEmailsMatcher.results().count();
// assertNotEquals(3, count);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.pem;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class JavaSecurityPemUtils {
public static RSAPrivateKey readPKCS8PrivateKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String privateKeyPEM = key
.replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PRIVATE KEY-----", "");
byte[] encoded = Base64.decodeBase64(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
public static RSAPublicKey readX509PublicKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String publicKeyPEM = key
.replace("-----BEGIN PUBLIC KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
}

View File

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCyO0YiTxLEP44S
IGk/b9MlQAXS6nC4oYyTrAfxHCi/zxW/MmtWbY0K2JxOTkVSD5QbmvwkCutXi0k9
EdDK+orAXg2KSy686O/cfIh/iho6FmNPyEOd7UF+/5wWpknrUaTQyMA2H9Pmr2/E
RH/tN1Q0cqmhFX41WUo3lsRT81DkVCNVeJx+zDGHpjp+XY8gWpPYJ+MP4WQE9TWJ
P2rIlgcDfwhG/A21yK0WAJ5nB0Y+jGI8+HVYdjxXGlRUG//YmxS2sH+sAhsapmjE
Aha+KMk972jVNjdWU7OT0BJnUB5q286Kv6INUnk6kqYufNzjpCAY9SyMjKjpKN71
3Gka2gZBAgMBAAECggEAFlPam12wiik0EQ1CYhIOL3JvyFZaPKbwR2ebrxbJ/A1j
OgqE69TZgGxWWHDxui/9a9/kildb2CG40Q+0SllMnICrzZFRj5TWx5ZKOz//vRsk
4c/CuLwKInC/Cw9V30bhEM61VZJzJ0j/BWVXaU4vHEro+ScKIoDHDWOzwJiQn6m9
C+Ti5lFpax3hx8ZrgPqmBCFYNvErrWkOr7mCYl0jS+E22c68yn8+LjdlF1LWUa6N
zutk3MPj5UwEyR0h7EZReCeGkPTMQNyOBhDcmAtlEno4fjtZzUDHRjh8/QpG1Mz/
alavvrkjswc1DmRUOdgiYu+Waxan5noBhxEAvd/hyQKBgQDjYJD0n+m0tUrpNtX0
+mdzHstClHrpx5oNxs4sIBjCoCwEXaSpeY8+JxCdnZ6n29mLZLq/wPXxZ3EJcOSZ
PYUvZJfV/IUvoLPFbtT3ILzDTcAAeHj2GAOpzYP8J1JSFsc78ZjKMF1XeNjXcq8T
XNXoWfY7N/fShoycVeG42JJCFwKBgQDIqvHL0QfJ8r6yM8Efj7Zq6Wa4C9okORes
8UVWfBoO6UOWvpK+D9IjnaEisJcnEalwNi8/eKudR9hfvmzATV+t3YJIgktto3TT
BWLsEyniNU4vSTl7GPBrV2xabWogbChlt7TXUfw6YogaBKm43snYXBbJFc+NcpQH
ONB5igppZwKBgGDyYHvc3wGsttb/CXTde1RLUfD+a/XXpCixlmCcAtKhBoOKBdY4
vUmL0HrTpLz/cR8NAM8XkAWwzDJxTxbDc1EEu/SCKatoAp5wph8Ed1dyhCXvN+v9
yzoQJXFStrfHfIVjenji7DmKjjI2dM11rMLX8LPJJkI+Gh/iQk7VEG9bAoGAH/aS
sztleTZwR6RUw7k5fkgVM4W3xoNNkR+RQthbsjpXqMBMUXflqgSmsQbd3LxEd/o5
hmurMk9KWN3VJsBsWB5rbS9L4nfh2OcHvcDDsCN7g66vODtduEthl/nLqMRxnton
NRD7EzW0pihN/IOINS1d98PAnrA8gfX7xxBE3ksCgYBvoljHGjvy3bPJ++vDGKJK
y6JuEeRVzgdPXEb60uU+BR7kdh+MMsZLmgfFTgza3R+/xeZcC/cuOPsbzeooRQi/
9NpKwSCXjVNk9nglUWBoPRh4uYqrArWn+HoR7MI/BxeRJm5e1+ii8P19Y9joX5s0
Q3OLn8GeH56ClJmNiWDhsA==
-----END PRIVATE KEY-----

View File

@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjtGIk8SxD+OEiBpP2/T
JUAF0upwuKGMk6wH8Rwov88VvzJrVm2NCticTk5FUg+UG5r8JArrV4tJPRHQyvqK
wF4NiksuvOjv3HyIf4oaOhZjT8hDne1Bfv+cFqZJ61Gk0MjANh/T5q9vxER/7TdU
NHKpoRV+NVlKN5bEU/NQ5FQjVXicfswxh6Y6fl2PIFqT2CfjD+FkBPU1iT9qyJYH
A38IRvwNtcitFgCeZwdGPoxiPPh1WHY8VxpUVBv/2JsUtrB/rAIbGqZoxAIWvijJ
Pe9o1TY3VlOzk9ASZ1AeatvOir+iDVJ5OpKmLnzc46QgGPUsjIyo6Sje9dxpGtoG
QQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,33 @@
package com.baeldung.pem;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JavaSecurityPemUtilsUnitTest {
@Test
public void whenReadPublicKeyFromPEMFile_thenSuccess() throws Exception {
File pemFile = new File(JavaSecurityPemUtilsUnitTest.class.getResource("/pem/public-key.pem").getFile());
RSAPublicKey publicKey = JavaSecurityPemUtils.readX509PublicKey(pemFile);
assertEquals("X.509", publicKey.getFormat());
assertEquals("RSA", publicKey.getAlgorithm());
}
@Test
public void whenReadPrivateKeyFromPEMFile_thenSuccess() throws Exception {
File pemFile = new File(JavaSecurityPemUtilsUnitTest.class.getResource("/pem/private-key-pkcs8.pem").getFile());
RSAPrivateKey privateKey = JavaSecurityPemUtils.readPKCS8PrivateKey(pemFile);
assertEquals("PKCS#8", privateKey.getFormat());
assertEquals("RSA", privateKey.getAlgorithm());
}
}

View File

@ -9,7 +9,6 @@ This module contains articles about the Stream API in Java.
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)

View File

@ -10,7 +10,6 @@ This module contains articles about string operations.
- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase)
- [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching)
- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives)
- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64)
- [Encode a String to UTF-8 in Java](https://www.baeldung.com/java-string-encode-utf-8)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file

View File

@ -85,6 +85,7 @@
<module>core-java-lambdas</module>
<module>core-java-lang</module>
<module>core-java-lang-2</module>
<module>core-java-lang-3</module>
<module>core-java-lang-math</module>
<module>core-java-lang-math-2</module>
<module>core-java-lang-oop-constructors</module>
@ -110,6 +111,7 @@
<module>core-java-perf</module>
<module>core-java-reflection</module>
<module>core-java-reflection-2</module>
<module>core-java-security</module>
<module>core-java-security-2</module>
@ -134,18 +136,6 @@
<module>pre-jpms</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
@ -163,6 +153,18 @@
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>

View File

@ -17,16 +17,6 @@
<relativePath>../parent-boot-2</relativePath>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
@ -105,6 +95,16 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>

7
guava-2/README.md Normal file
View File

@ -0,0 +1,7 @@
## Guava
This module contains articles a Google Guava
### Relevant Articles:
- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables)
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)

48
guava-2/pom.xml Normal file
View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>guava-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,113 @@
package com.baeldung.guava.charmatcher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.junit.Test;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicate;
public class GuavaCharMatcherUnitTest {
@Test
public void whenRemoveSpecialCharacters_thenRemoved() {
final String input = "H*el.lo,}12";
final CharMatcher matcher = CharMatcher.javaLetterOrDigit();
final String result = matcher.retainFrom(input);
assertEquals("Hello12", result);
}
@Test
public void whenRemoveNonASCIIChars_thenRemoved() {
final String input = "あhello₤";
String result = CharMatcher.ascii().retainFrom(input);
assertEquals("hello", result);
result = CharMatcher.inRange('0', 'z').retainFrom(input);
assertEquals("hello", result);
}
@Test
public void whenValidateString_thenValid() {
final String input = "hello";
boolean result = CharMatcher.javaLowerCase().matchesAllOf(input);
assertTrue(result);
result = CharMatcher.is('e').matchesAnyOf(input);
assertTrue(result);
result = CharMatcher.javaDigit().matchesNoneOf(input);
assertTrue(result);
}
@Test
public void whenTrimString_thenTrimmed() {
final String input = "---hello,,,";
String result = CharMatcher.is('-').trimLeadingFrom(input);
assertEquals("hello,,,", result);
result = CharMatcher.is(',').trimTrailingFrom(input);
assertEquals("---hello", result);
result = CharMatcher.anyOf("-,").trimFrom(input);
assertEquals("hello", result);
}
@Test
public void whenCollapseFromString_thenCollapsed() {
final String input = " hel lo ";
String result = CharMatcher.is(' ').collapseFrom(input, '-');
assertEquals("-hel-lo-", result);
result = CharMatcher.is(' ').trimAndCollapseFrom(input, '-');
assertEquals("hel-lo", result);
}
@Test
public void whenReplaceFromString_thenReplaced() {
final String input = "apple-banana.";
String result = CharMatcher.anyOf("-.").replaceFrom(input, '!');
assertEquals("apple!banana!", result);
result = CharMatcher.is('-').replaceFrom(input, " and ");
assertEquals("apple and banana.", result);
}
@Test
public void whenCountCharInString_thenCorrect() {
final String input = "a, c, z, 1, 2";
int result = CharMatcher.is(',').countIn(input);
assertEquals(4, result);
result = CharMatcher.inRange('a', 'h').countIn(input);
assertEquals(2, result);
}
@Test
public void whenRemoveCharsNotInCharset_thenRemoved() {
final Charset charset = Charset.forName("cp437");
final CharsetEncoder encoder = charset.newEncoder();
final Predicate<Character> inRange = new Predicate<Character>() {
@Override
public boolean apply(final Character c) {
return encoder.canEncode(c);
}
};
final String result = CharMatcher.forPredicate(inRange).retainFrom("helloは");
assertEquals("hello", result);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.guava;
package com.baeldung.guava.throwables;
import com.google.common.base.Throwables;
import org.junit.Test;

13
guava-2/src/test/resources/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1 @@
John Jane Adam Tom

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Test

View File

@ -0,0 +1,4 @@
John
Jane
Adam
Tom

View File

@ -0,0 +1 @@
Hello world

Binary file not shown.

View File

@ -14,6 +14,21 @@
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava-collections-map</finalName>
@ -33,21 +48,6 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>

View File

@ -13,18 +13,6 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava-collections-set</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!-- test scoped -->
<dependency>
@ -47,6 +35,18 @@
</dependency>
</dependencies>
<build>
<finalName>guava-collections-set</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>

View File

@ -14,4 +14,3 @@ This module contains articles about Google Guava collections
- [Guava Lists](https://www.baeldung.com/guava-lists)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Guide to Guava Table](https://www.baeldung.com/guava-table)
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)

View File

@ -15,25 +15,6 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!-- utils -->
<dependency>
@ -76,6 +57,25 @@
</dependency>
</dependencies>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>

View File

@ -4,20 +4,19 @@ import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.common.collect.*;
import org.junit.Test;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class GuavaStringUnitTest {
@ -113,102 +112,4 @@ public class GuavaStringUnitTest {
assertEquals(4, result.size());
assertThat(result, contains("a", "b", "c", "d,e"));
}
@Test
public void whenRemoveSpecialCharacters_thenRemoved() {
final String input = "H*el.lo,}12";
final CharMatcher matcher = CharMatcher.javaLetterOrDigit();
final String result = matcher.retainFrom(input);
assertEquals("Hello12", result);
}
@Test
public void whenRemoveNonASCIIChars_thenRemoved() {
final String input = "あhello₤";
String result = CharMatcher.ascii().retainFrom(input);
assertEquals("hello", result);
result = CharMatcher.inRange('0', 'z').retainFrom(input);
assertEquals("hello", result);
}
@Test
public void whenValidateString_thenValid() {
final String input = "hello";
boolean result = CharMatcher.javaLowerCase().matchesAllOf(input);
assertTrue(result);
result = CharMatcher.is('e').matchesAnyOf(input);
assertTrue(result);
result = CharMatcher.javaDigit().matchesNoneOf(input);
assertTrue(result);
}
@Test
public void whenTrimString_thenTrimmed() {
final String input = "---hello,,,";
String result = CharMatcher.is('-').trimLeadingFrom(input);
assertEquals("hello,,,", result);
result = CharMatcher.is(',').trimTrailingFrom(input);
assertEquals("---hello", result);
result = CharMatcher.anyOf("-,").trimFrom(input);
assertEquals("hello", result);
}
@Test
public void whenCollapseFromString_thenCollapsed() {
final String input = " hel lo ";
String result = CharMatcher.is(' ').collapseFrom(input, '-');
assertEquals("-hel-lo-", result);
result = CharMatcher.is(' ').trimAndCollapseFrom(input, '-');
assertEquals("hel-lo", result);
}
@Test
public void whenReplaceFromString_thenReplaced() {
final String input = "apple-banana.";
String result = CharMatcher.anyOf("-.").replaceFrom(input, '!');
assertEquals("apple!banana!", result);
result = CharMatcher.is('-').replaceFrom(input, " and ");
assertEquals("apple and banana.", result);
}
@Test
public void whenCountCharInString_thenCorrect() {
final String input = "a, c, z, 1, 2";
int result = CharMatcher.is(',').countIn(input);
assertEquals(4, result);
result = CharMatcher.inRange('a', 'h').countIn(input);
assertEquals(2, result);
}
@Test
public void whenRemoveCharsNotInCharset_thenRemoved() {
final Charset charset = Charset.forName("cp437");
final CharsetEncoder encoder = charset.newEncoder();
final Predicate<Character> inRange = new Predicate<Character>() {
@Override
public boolean apply(final Character c) {
return encoder.canEncode(c);
}
};
final String result = CharMatcher.forPredicate(inRange).retainFrom("helloは");
assertEquals("hello", result);
}
}

View File

@ -16,6 +16,21 @@
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava-io</finalName>
@ -35,18 +50,4 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -22,16 +22,6 @@
<module>guava-21</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -46,4 +36,15 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -12,5 +12,4 @@ This module contains articles a Google Guava
- [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math)
- [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter)
- [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter)
- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables)
- [Guava Cache](https://www.baeldung.com/guava-cache)

View File

@ -15,25 +15,6 @@
<relativePath>../parent-java</relativePath>
</parent>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@ -62,6 +43,25 @@
</dependency>
</dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<!-- testing -->
<junit-jupiter.version>5.6.2</junit-jupiter.version>

View File

@ -60,6 +60,27 @@
<artifactId>tesseract-platform</artifactId>
<version>${tesseract-platform.version}</version>
</dependency>
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>${imgscalr-version}</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>${thumbnailator-version}</version>
</dependency>
<dependency>
<groupId>com.github.downgoon</groupId>
<artifactId>marvin</artifactId>
<version>${marvin-version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.github.downgoon</groupId>
<artifactId>MarvinPlugins</artifactId>
<version>${marvin-version}</version>
</dependency>
</dependencies>
<properties>
@ -69,6 +90,9 @@
<tess4j.version>4.5.1</tess4j.version>
<tesseract-platform.version>4.1.0-1.5.2</tesseract-platform.version>
<opencv.version>3.4.2-0</opencv.version>
<imgscalr-version>4.2</imgscalr-version>
<thumbnailator-version>0.4.11</thumbnailator-version>
<marvin-version>1.5.5</marvin-version>
</properties>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldung.image.resize.core;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Graphics2DExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
return resizedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-graphics2d.jpg"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.image.resize.core;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageScaledInstanceExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage bufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics()
.drawImage(resultingImage, 0, 0, null);
return bufferedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-scaledinstance.jpg"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.image.resize.imgscalr;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class ImgscalrExample {
public static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) {
return Scalr.resize(originalImage, targetWidth);
}
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
return Scalr.resize(originalImage, Scalr.Method.AUTOMATIC, Scalr.Mode.AUTOMATIC, targetWidth, targetHeight, Scalr.OP_ANTIALIAS);
}
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-imgscalr.jpg"));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.image.resize.marvin;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.marvinproject.image.transform.scale.Scale;
import marvin.image.MarvinImage;
public class MarvinExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
MarvinImage image = new MarvinImage(originalImage);
Scale scale = new Scale();
scale.load();
scale.setAttribute("newWidth", targetWidth);
scale.setAttribute("newHeight", targetHeight);
scale.process(image.clone(), image, null, null, false);
return image.getBufferedImageNoAlpha();
}
public static void main(String args[]) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-marvin.jpg"));
}
}

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