commit
7e89531ef6
|
@ -7,4 +7,5 @@
|
|||
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
|
||||
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
|
||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
List<Integer> array = new ArrayList<>(input);
|
||||
List<Integer> topKList = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < k; i++) {
|
||||
int maxIndex = 0;
|
||||
|
||||
for (int j = 1; j < array.size(); j++) {
|
||||
if (array.get(j) > array.get(maxIndex)) {
|
||||
maxIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
topKList.add(array.remove(maxIndex));
|
||||
}
|
||||
|
||||
return topKList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
|
||||
|
||||
input.forEach(number -> {
|
||||
maxHeap.add(number);
|
||||
|
||||
if (maxHeap.size() > k) {
|
||||
maxHeap.poll();
|
||||
}
|
||||
});
|
||||
|
||||
List<Integer> topKList = new ArrayList<>(maxHeap);
|
||||
Collections.reverse(topKList);
|
||||
|
||||
return topKList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TopKElementsFinder<T extends Comparable<T>> {
|
||||
List<T> findTopK(List<T> input, int k);
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
|
||||
sortedSet.addAll(input);
|
||||
|
||||
return sortedSet.stream().limit(k).collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
|
||||
public class TopKElementsFinderUnitTest {
|
||||
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
|
||||
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
|
||||
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
|
||||
|
||||
private final int k = 4;
|
||||
private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12);
|
||||
private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12);
|
||||
private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12);
|
||||
private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12);
|
||||
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
|
||||
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
|
||||
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
|
||||
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
|
||||
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
|
||||
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.intro;
|
||||
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.intro;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
|
@ -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();
|
||||
|
|
@ -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
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.models;
|
||||
package com.baeldung.intro.models;
|
||||
|
||||
public class UserCredentials {
|
||||
|
|
@ -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;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.shiro.permissions.custom;
|
||||
package com.baeldung.permissions.custom;
|
||||
|
||||
import org.apache.shiro.authz.Permission;
|
||||
|
|
@ -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;
|
|
@ -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>
|
|
@ -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>
|
|
@ -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>
|
|
@ -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() {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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() {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -46,7 +46,4 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts
|
|||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
||||
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
|
||||
- [Groovy Variable Scope](https://www.baeldung.com/groovy/variable-scope)
|
||||
- [[More -->]](/core-groovy-2)
|
||||
|
|
|
@ -8,7 +8,7 @@ This module contains articles about Java 11 core features
|
|||
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [Exploring the New HTTP Client in Java](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||
|
|
|
@ -1,12 +1,15 @@
|
|||
package com.baeldung.modules.main;
|
||||
|
||||
import com.baeldung.modules.hello.HelloInterface;
|
||||
import com.baeldung.modules.hello.HelloModules;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
HelloModules.doSomething();
|
||||
|
||||
HelloModules module = new HelloModules();
|
||||
module.sayHello();
|
||||
|
||||
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
|
||||
HelloInterface service = services.iterator().next();
|
||||
service.sayHello();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,3 +13,4 @@ This module contains articles about core Java features that have been introduced
|
|||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
||||
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
|
||||
|
|
|
@ -9,3 +9,4 @@ This module contains articles about Java 9 core features
|
|||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
|
||||
- [Easy Ways to Write a Java InputStream to an OutputStream](https://www.baeldung.com/java-inputstream-to-outputstream)
|
||||
|
|
|
@ -5,4 +5,4 @@ This module contains complete guides about arrays in Java
|
|||
### Relevant Articles:
|
||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [What is [Ljava.lang.Object;?]](https://www.baeldung.com/java-tostring-array)
|
||||
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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}));
|
||||
}
|
||||
}
|
|
@ -15,4 +15,5 @@ This module contains articles about advanced topics about multithreading with co
|
|||
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
|
||||
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
|
||||
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
|
||||
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
|
||||
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -1,3 +1,5 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)
|
||||
|
|
|
@ -3,9 +3,16 @@
|
|||
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.concurrent.lock</groupId>
|
||||
<artifactId>core-java-concurrency-collections-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-concurrency-collections-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>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -30,19 +37,6 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
|
|
|
@ -19,7 +19,7 @@ import org.junit.FixMethodOrder;
|
|||
import org.junit.Test;
|
||||
|
||||
@FixMethodOrder
|
||||
public class TestConcurrentLinkedQueue {
|
||||
public class ConcurrentLinkedQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
|
|
@ -18,7 +18,7 @@ import org.junit.FixMethodOrder;
|
|||
import org.junit.Test;
|
||||
|
||||
@FixMethodOrder
|
||||
public class TestLinkedBlockingQueue {
|
||||
public class LinkedBlockingQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {
|
|
@ -4,7 +4,11 @@ import org.junit.FixMethodOrder;
|
|||
import org.junit.Test;
|
||||
import org.junit.runners.MethodSorters;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedTransferQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TransferQueue;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
|
@ -10,7 +10,7 @@ This module contains articles about concurrent Java collections
|
|||
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
|
||||
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
|
||||
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
|
||||
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||
- [LinkedBlockingQueue vs ConcurrentLinkedQueue](https://www.baeldung.com/java-queue-linkedblocking-concurrentlinked)
|
||||
- [[Next -->]](/core-java-modules/core-java-concurrency-collections-2)
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy)
|
||||
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
|
||||
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
|
||||
|
@ -9,4 +10,5 @@ This module contains articles about date operations in Java.
|
|||
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
|
||||
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [Getting the Week Number From Any Date](https://www.baeldung.com/java-get-week-number)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about core java exceptions
|
|||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
|
||||
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||
- [Java IOException “Too many open files”](https://www.baeldung.com/java-too-many-open-files)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -13,4 +13,4 @@ This module contains articles about core Java input and output (IO)
|
|||
- [How to Copy a File with Java](https://www.baeldung.com/java-copy-file)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io)[[More -->]](/core-java-modules/core-java-io-3)
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
## Core Java IO
|
||||
|
||||
This module contains articles about core Java input and output (IO)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java – Create a File](https://www.baeldung.com/java-how-to-create-a-file)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io-2)
|
|
@ -0,0 +1,86 @@
|
|||
<?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-io-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-io-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>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.github.tomakehurst/wiremock -->
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>${wiremock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-3</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<wiremock.version>2.26.3</wiremock.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.createfile;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class CreateFileUnitTest {
|
||||
|
||||
private final String FILE_NAME = "src/test/resources/fileToCreate.txt";
|
||||
|
||||
@AfterEach
|
||||
@BeforeEach
|
||||
public void cleanUpFiles() {
|
||||
File targetFile = new File(FILE_NAME);
|
||||
targetFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException {
|
||||
Path newFilePath = Paths.get(FILE_NAME);
|
||||
Files.createFile(newFilePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException {
|
||||
File newFile = new File(FILE_NAME);
|
||||
boolean success = newFile.createNewFile();
|
||||
assertTrue(success);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||
com.google.common.io.Files.touch(new File(FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(FILE_NAME));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.emptiness;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DirectoryEmptinessUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInvalid_thenReturnsFalse() throws IOException {
|
||||
assertThat(isEmpty(Paths.get("invalid-addr"))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
|
||||
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
|
||||
assertThat(isEmpty(aFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenNotEmptyDir_thenReturnsFalse() throws IOException {
|
||||
Path currentDir = new File("").toPath().toAbsolutePath();
|
||||
assertThat(isEmpty(currentDir)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenIsEmpty_thenReturnsTrue() throws Exception {
|
||||
Path path = Files.createTempDirectory("baeldung-empty");
|
||||
assertThat(isEmpty(path)).isTrue();
|
||||
}
|
||||
|
||||
private static boolean isEmpty(Path path) throws IOException {
|
||||
if (Files.isDirectory(path)) {
|
||||
try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
|
||||
return !directory.iterator().hasNext();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isEmpty2(Path path) throws IOException {
|
||||
if (Files.isDirectory(path)) {
|
||||
try (Stream<Path> entries = Files.list(path)) {
|
||||
return !entries.findFirst().isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isEmptyInefficient(Path path) {
|
||||
return path.toFile().listFiles().length == 0;
|
||||
}
|
||||
}
|
|
@ -7,7 +7,6 @@ This module contains articles about core Java input/output(IO) APIs.
|
|||
- [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader)
|
||||
- [The Java File Class](https://www.baeldung.com/java-io-file)
|
||||
- [Java FileWriter](https://www.baeldung.com/java-filewriter)
|
||||
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](https://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
|
||||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](https://www.baeldung.com/java-path)
|
||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
|
|
|
@ -6,4 +6,6 @@ This module contains articles about core Java input/output(IO) conversions.
|
|||
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
|
||||
- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
|
||||
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
|
||||
|
|
|
@ -26,6 +26,12 @@
|
|||
<artifactId>json</artifactId>
|
||||
<version>${json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -40,6 +46,7 @@
|
|||
|
||||
<properties>
|
||||
<json.version>20200518</json.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,20 +1,11 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.opencsv.CSVReader;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.opencsv.CSVReader;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class ReadCSVInArrayUnitTest {
|
||||
public static final String COMMA_DELIMITER = ",";
|
|
@ -1,7 +1,9 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
|
@ -10,10 +12,8 @@ import java.io.PrintWriter;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
|
@ -8,10 +8,9 @@ This module contains articles about core Java input and output (IO)
|
|||
- [Java – Directory Size](https://www.baeldung.com/java-folder-size)
|
||||
- [File Size in Java](https://www.baeldung.com/java-file-size)
|
||||
- [Zipping and Unzipping in Java](https://www.baeldung.com/java-compress-and-uncompress)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [How to Get the File Extension of a File in Java](https://www.baeldung.com/java-file-extension)
|
||||
- [Getting a File’s Mime Type in Java](https://www.baeldung.com/java-file-mime-type)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
- [Java – Rename or Move a File](https://www.baeldung.com/java-how-to-rename-or-move-a-file)
|
||||
- [[More -->]](/core-java-modules/core-java-io-2)
|
||||
|
|
|
@ -29,12 +29,6 @@
|
|||
<version>${hsqldb.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
|
@ -142,8 +136,6 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- maven plugins -->
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.rename;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystemException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class RenameFileUnitTest {
|
||||
|
||||
private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt";
|
||||
private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt";
|
||||
|
||||
@BeforeEach
|
||||
public void createFileToMove() throws IOException {
|
||||
File fileToMove = new File(FILE_TO_MOVE);
|
||||
fileToMove.createNewFile();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void cleanUpFiles() {
|
||||
File targetFile = new File(TARGET_FILE);
|
||||
targetFile.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException {
|
||||
Path fileToMovePath = Paths.get(FILE_TO_MOVE);
|
||||
Path targetPath = Paths.get(TARGET_FILE);
|
||||
Files.move(fileToMovePath, targetPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException {
|
||||
File fileToMove = new File(FILE_TO_MOVE);
|
||||
boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE));
|
||||
if (!isMoved) {
|
||||
throw new FileSystemException(TARGET_FILE);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenMovingFile_thenCorrect()
|
||||
throws IOException {
|
||||
File fileToMove = new File(FILE_TO_MOVE);
|
||||
File targetFile = new File(TARGET_FILE);
|
||||
|
||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||
FileUtils.moveFile(
|
||||
FileUtils.getFile(FILE_TO_MOVE),
|
||||
FileUtils.getFile(TARGET_FILE));
|
||||
}
|
||||
|
||||
}
|
|
@ -2,4 +2,11 @@
|
|||
|
||||
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)
|
||||
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.memaddress;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jol.vm.VM;
|
||||
|
||||
public class MemoryAddressUnitTest {
|
||||
|
||||
@Test
|
||||
public void printTheMemoryAddress() {
|
||||
String answer = "42";
|
||||
|
||||
System.out.println("The memory address is " + VM.current().addressOf(answer));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void identityHashCodeAndMemoryAddress() {
|
||||
Object obj = new Object();
|
||||
|
||||
System.out.println("Memory address: " + VM.current().addressOf(obj));
|
||||
System.out.println("hashCode: " + obj.hashCode());
|
||||
System.out.println("hashCode: " + System.identityHashCode(obj));
|
||||
System.out.println("toString: " + obj);
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -2,5 +2,5 @@
|
|||
|
||||
This module contains articles about core features in the Java language
|
||||
|
||||
### Relevant Articles:
|
||||
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
|
||||
|
|
|
@ -8,6 +8,7 @@
|
|||
<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>
|
||||
|
@ -16,7 +17,12 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -30,7 +36,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
<assertj.version>3.12.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.staticvariables;
|
||||
|
||||
public class StaticVariableDemo {
|
||||
public static int i;
|
||||
public static int j = 20;
|
||||
public static int z;
|
||||
|
||||
static {
|
||||
z = 30;
|
||||
a = 40;
|
||||
}
|
||||
|
||||
public static int a = 50;
|
||||
|
||||
public static final int b = 100;
|
||||
|
||||
public StaticVariableDemo() {
|
||||
}
|
||||
|
||||
static class Nested {
|
||||
public static String nestedClassStaticVariable = "test";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,113 @@
|
|||
package com.baeldung.staticvariables;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StaticVariableUnitTest {
|
||||
|
||||
@Test
|
||||
public void initializeStaticVariable_checkAssignedValues() {
|
||||
|
||||
try {
|
||||
Class<?> staticVariableDemo = this.getClass()
|
||||
.getClassLoader()
|
||||
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
|
||||
|
||||
Field field1 = staticVariableDemo.getField("i");
|
||||
|
||||
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(0);
|
||||
|
||||
Field field2 = staticVariableDemo.getField("j");
|
||||
|
||||
assertThat(field2.getInt(staticVariableDemo)).isEqualTo(20);
|
||||
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializeStaticVariable_checkStaticBlock() {
|
||||
|
||||
try {
|
||||
Class<?> staticVariableDemo = this.getClass()
|
||||
.getClassLoader()
|
||||
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
|
||||
|
||||
Field field1 = staticVariableDemo.getField("z");
|
||||
|
||||
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(30);
|
||||
|
||||
Field field2 = staticVariableDemo.getField("a");
|
||||
|
||||
assertThat(field2.getInt(staticVariableDemo)).isEqualTo(50);
|
||||
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializeStaticVariable_checkFinalValues() {
|
||||
|
||||
try {
|
||||
Class<?> staticVariableDemo = this.getClass()
|
||||
.getClassLoader()
|
||||
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
|
||||
|
||||
Field field1 = staticVariableDemo.getField("b");
|
||||
|
||||
assertThat(field1.getInt(staticVariableDemo)).isEqualTo(100);
|
||||
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializeStaticVariable_checkInnerClassValues() {
|
||||
|
||||
try {
|
||||
Class<?> staticVariableDemo = this.getClass()
|
||||
.getClassLoader()
|
||||
.loadClass("com.baeldung.staticvariables.StaticVariableDemo");
|
||||
|
||||
Class<?>[] nestedClasses = staticVariableDemo.getClasses();
|
||||
|
||||
for (Class<?> nestedClass : nestedClasses) {
|
||||
if (nestedClass.getName()
|
||||
.equals("Nested")) {
|
||||
|
||||
Field field1 = nestedClass.getField("nestedClassStaticVariable");
|
||||
assertThat(field1.get(nestedClass)).isEqualTo("test");
|
||||
}
|
||||
}
|
||||
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -3,7 +3,9 @@
|
|||
This module contains articles about methods in Java
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Methods in Java](https://www.baeldung.com/java-methods)
|
||||
- [Method Overloading and Overriding in Java](https://www.baeldung.com/java-method-overload-override)
|
||||
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
|
||||
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
|
||||
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -12,4 +12,5 @@ This module contains articles about networking in Java
|
|||
- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection)
|
||||
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
|
||||
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
|
||||
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-networking)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
|
|
@ -8,5 +8,4 @@
|
|||
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||
|
@ -11,3 +12,4 @@
|
|||
- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement)
|
||||
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
|
||||
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)
|
||||
- [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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-----
|
|
@ -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-----
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Version Comparison in Java](https://www.baeldung.com/java-comparing-versions)
|
|
@ -0,0 +1,61 @@
|
|||
<?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-string-operations-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-string-operations-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>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven</groupId>
|
||||
<artifactId>maven-artifact</artifactId>
|
||||
<version>${maven-artifact.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.gradle</groupId>
|
||||
<artifactId>gradle-core</artifactId>
|
||||
<version>${gradle-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>semver4j</artifactId>
|
||||
<version>${semver4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven-artifact.version>3.6.3</maven-artifact.version>
|
||||
<gradle-core.version>6.1.1</gradle-core.version>
|
||||
<jackson-core.version>2.11.1</jackson-core.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>gradle-repo</id>
|
||||
<url>https://repo.gradle.org/gradle/libs-releases-local/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.versioncomparison;
|
||||
|
||||
public class VersionCompare {
|
||||
|
||||
public static int compareVersions(String version1, String version2) {
|
||||
int comparisonResult = 0;
|
||||
|
||||
String[] version1Splits = version1.split("\\.");
|
||||
String[] version2Splits = version2.split("\\.");
|
||||
|
||||
int maxLengthOfVersionSplits = Math.max(version1Splits.length, version2Splits.length);
|
||||
for (int i = 0; i < maxLengthOfVersionSplits; i++){
|
||||
Integer v1 = i < version1Splits.length ? Integer.parseInt(version1Splits[i]) : 0;
|
||||
Integer v2 = i < version2Splits.length ? Integer.parseInt(version2Splits[i]) : 0;
|
||||
int compare = v1.compareTo(v2);
|
||||
if (compare != 0) {
|
||||
comparisonResult = compare;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return comparisonResult;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,136 @@
|
|||
package com.baeldung.versioncomparison;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.Version;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import com.vdurmont.semver4j.Semver.VersionDiff;
|
||||
|
||||
import org.apache.maven.artifact.versioning.ComparableVersion;
|
||||
import org.gradle.util.VersionNumber;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class VersionComparisonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenVersionStrings_whenUsingMavenArtifact_thenCompareVersions() {
|
||||
ComparableVersion version1_1 = new ComparableVersion("1.1");
|
||||
ComparableVersion version1_2 = new ComparableVersion("1.2");
|
||||
ComparableVersion version1_3 = new ComparableVersion("1.3");
|
||||
|
||||
assertTrue(version1_1.compareTo(version1_2) < 0);
|
||||
assertTrue(version1_3.compareTo(version1_2) > 0);
|
||||
|
||||
ComparableVersion version1_1_0 = new ComparableVersion("1.1.0");
|
||||
assertEquals(0, version1_1.compareTo(version1_1_0));
|
||||
|
||||
ComparableVersion version1_1_alpha = new ComparableVersion("1.1-alpha");
|
||||
assertTrue(version1_1.compareTo(version1_1_alpha) > 0);
|
||||
|
||||
ComparableVersion version1_1_beta = new ComparableVersion("1.1-beta");
|
||||
ComparableVersion version1_1_milestone = new ComparableVersion("1.1-milestone");
|
||||
ComparableVersion version1_1_rc = new ComparableVersion("1.1-rc");
|
||||
ComparableVersion version1_1_snapshot = new ComparableVersion("1.1-snapshot");
|
||||
|
||||
assertTrue(version1_1_alpha.compareTo(version1_1_beta) < 0);
|
||||
assertTrue(version1_1_beta.compareTo(version1_1_milestone) < 0);
|
||||
assertTrue(version1_1_rc.compareTo(version1_1_snapshot) < 0);
|
||||
assertTrue(version1_1_snapshot.compareTo(version1_1) < 0);
|
||||
|
||||
ComparableVersion version1_1_c = new ComparableVersion("1.1-c");
|
||||
ComparableVersion version1_1_z = new ComparableVersion("1.1-z");
|
||||
ComparableVersion version1_1_1 = new ComparableVersion("1.1.1");
|
||||
|
||||
assertTrue(version1_1_c.compareTo(version1_1_z) < 0);
|
||||
assertTrue(version1_1_z.compareTo(version1_1_1) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVersionStrings_whenUsingGradle_thenCompareVersions() {
|
||||
VersionNumber version1_1 = VersionNumber.parse("1.1");
|
||||
VersionNumber version1_2 = VersionNumber.parse("1.2");
|
||||
VersionNumber version1_3 = VersionNumber.parse("1.3");
|
||||
|
||||
assertTrue(version1_1.compareTo(version1_2) < 0);
|
||||
assertTrue(version1_3.compareTo(version1_2) > 0);
|
||||
|
||||
VersionNumber version1_1_0 = VersionNumber.parse("1.1.0");
|
||||
assertEquals(0, version1_1.compareTo(version1_1_0));
|
||||
|
||||
VersionNumber version1_1_1_1_alpha = VersionNumber.parse("1.1.1.1-alpha");
|
||||
assertTrue(version1_1.compareTo(version1_1_1_1_alpha) < 0);
|
||||
|
||||
VersionNumber version1_1_beta = VersionNumber.parse("1.1.0.0-beta");
|
||||
assertTrue(version1_1_beta.compareTo(version1_1_1_1_alpha) < 0);
|
||||
|
||||
VersionNumber version1_1_1_snapshot = VersionNumber.parse("1.1.1-snapshot");
|
||||
assertTrue(version1_1_1_1_alpha.compareTo(version1_1_1_snapshot) < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVersionStrings_whenUsingJackson_thenCompareVersions() {
|
||||
Version version1_1 = new Version(1, 1, 0, null, null, null);
|
||||
Version version1_2 = new Version(1, 2, 0, null, null, null);
|
||||
Version version1_3 = new Version(1, 3, 0, null, null, null);
|
||||
|
||||
assertTrue(version1_1.compareTo(version1_2) < 0);
|
||||
assertTrue(version1_3.compareTo(version1_2) > 0);
|
||||
|
||||
Version version1_1_1 = new Version(1, 1, 1, null, null, null);
|
||||
assertTrue(version1_1.compareTo(version1_1_1) < 0);
|
||||
|
||||
Version version1_1_maven = new Version(1, 1, 0, null, "org.apache.maven", null);
|
||||
Version version1_1_gradle = new Version(1, 1, 0, null, "org.gradle", null);
|
||||
assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0);
|
||||
|
||||
Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null);
|
||||
assertEquals(0, version1_1.compareTo(version1_1_snapshot));
|
||||
|
||||
assertTrue(version1_1_snapshot.isSnapshot());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVersionStrings_whenUsingSemver_thenCompareVersions() {
|
||||
Semver version1_1 = new Semver("1.1.0");
|
||||
Semver version1_2 = new Semver("1.2.0");
|
||||
Semver version1_3 = new Semver("1.3.0");
|
||||
|
||||
assertTrue(version1_1.compareTo(version1_2) < 0);
|
||||
assertTrue(version1_3.compareTo(version1_2) > 0);
|
||||
|
||||
Semver version1_1_alpha = new Semver("1.1.0-alpha");
|
||||
assertTrue(version1_1.isGreaterThan(version1_1_alpha));
|
||||
|
||||
Semver version1_1_beta = new Semver("1.1.0-beta");
|
||||
Semver version1_1_milestone = new Semver("1.1.0-milestone");
|
||||
Semver version1_1_rc = new Semver("1.1.0-rc");
|
||||
Semver version1_1_snapshot = new Semver("1.1.0-snapshot");
|
||||
|
||||
assertTrue(version1_1_alpha.isLowerThan(version1_1_beta));
|
||||
assertTrue(version1_1_beta.compareTo(version1_1_milestone) < 0);
|
||||
assertTrue(version1_1_rc.compareTo(version1_1_snapshot) < 0);
|
||||
assertTrue(version1_1_snapshot.compareTo(version1_1) < 0);
|
||||
|
||||
assertTrue(version1_1.isEqualTo("1.1.0"));
|
||||
|
||||
assertEquals(VersionDiff.MAJOR, version1_1.diff("2.1.0"));
|
||||
assertEquals(VersionDiff.MINOR, version1_1.diff("1.2.3"));
|
||||
assertEquals(VersionDiff.PATCH, version1_1.diff("1.1.1"));
|
||||
|
||||
assertTrue(version1_1.isStable());
|
||||
assertFalse(version1_1_alpha.isStable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVersionStrings_whenUsingCustomVersionCompare_thenCompareVersions() {
|
||||
assertTrue(VersionCompare.compareVersions("1.0.1", "1.1.2") < 0);
|
||||
assertTrue(VersionCompare.compareVersions("1.0.1", "1.10") < 0);
|
||||
assertTrue(VersionCompare.compareVersions("1.1.2", "1.0.1") > 0);
|
||||
assertTrue(VersionCompare.compareVersions("1.1.2", "1.2") < 0);
|
||||
assertEquals(0, VersionCompare.compareVersions("1.3.0", "1.3"));
|
||||
}
|
||||
|
||||
}
|
|
@ -72,6 +72,7 @@
|
|||
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-io-2</module>
|
||||
<module>core-java-io-3</module>
|
||||
<module>core-java-io-apis</module>
|
||||
<module>core-java-io-conversions</module>
|
||||
<module>core-java-io-conversions-2</module>
|
||||
|
@ -85,6 +86,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>
|
||||
|
@ -125,6 +127,7 @@
|
|||
<module>core-java-string-conversions-2</module>
|
||||
<module>core-java-string-operations</module>
|
||||
<module>core-java-string-operations-2</module>
|
||||
<module>core-java-string-operations-3</module>
|
||||
<module>core-java-strings</module>
|
||||
<module>core-java-sun</module>
|
||||
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.index
|
||||
|
||||
fun main() {
|
||||
|
||||
// Index only
|
||||
val colors = listOf("Red", "Green", "Blue")
|
||||
for (i in colors.indices) {
|
||||
println(colors[i])
|
||||
}
|
||||
|
||||
val colorArray = arrayOf("Red", "Green", "Blue")
|
||||
for (i in colorArray.indices) {
|
||||
println(colorArray[i])
|
||||
}
|
||||
|
||||
(0 until colors.size).forEach { println(colors[it]) }
|
||||
for (i in 0 until colors.size) {
|
||||
println(colors[i])
|
||||
}
|
||||
|
||||
// Index and Value
|
||||
colors.forEachIndexed { i, v -> println("The value for index $i is $v") }
|
||||
for (indexedValue in colors.withIndex()) {
|
||||
println("The value for index ${indexedValue.index} is ${indexedValue.value}")
|
||||
}
|
||||
|
||||
for ((i, v) in colors.withIndex()) {
|
||||
println("The value for index $i is $v")
|
||||
}
|
||||
|
||||
colors.filterIndexed { i, _ -> i % 2 == 0 }
|
||||
colors.filterIndexed { _, v -> v == "RED" }
|
||||
}
|
|
@ -7,7 +7,6 @@ This module contains articles about core features in the Kotlin language.
|
|||
- [Infix Functions in Kotlin](https://www.baeldung.com/kotlin-infix-functions)
|
||||
- [Lambda Expressions in Kotlin](https://www.baeldung.com/kotlin-lambda-expressions)
|
||||
- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final)
|
||||
- [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array)
|
||||
- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization)
|
||||
- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety)
|
||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||
|
|
|
@ -1,49 +0,0 @@
|
|||
package com.baeldung.arrayinitialization
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class ArrayInitializationTest {
|
||||
|
||||
@Test
|
||||
fun givenArrayOfStrings_thenValuesPopulated() {
|
||||
val strings = arrayOf("January", "February", "March")
|
||||
|
||||
assertEquals(3, strings.size)
|
||||
assertEquals("March", strings[2])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArrayOfIntegers_thenValuesPopulated() {
|
||||
val integers = intArrayOf(1, 2, 3, 4)
|
||||
|
||||
assertEquals(4, integers.size)
|
||||
assertEquals(1, integers[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArrayOfNulls_whenPopulated_thenValuesPresent() {
|
||||
val array = arrayOfNulls<Number>(5)
|
||||
|
||||
for (i in array.indices) {
|
||||
array[i] = i * i
|
||||
}
|
||||
|
||||
assertEquals(16, array[4])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGeneratorUsed_thenValuesPresent() {
|
||||
val generatedArray = IntArray(10) { i -> i * i }
|
||||
|
||||
assertEquals(81, generatedArray[9])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenStringGenerated_thenValuesPresent() {
|
||||
val generatedStringArray = Array(10) { i -> "Number of index: $i" }
|
||||
|
||||
assertEquals("Number of index: 0", generatedStringArray[0])
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.anonymous
|
||||
|
||||
import java.io.Serializable
|
||||
import java.nio.channels.Channel
|
||||
|
||||
fun main() {
|
||||
val channel = object : Channel {
|
||||
override fun isOpen() = false
|
||||
|
||||
override fun close() {
|
||||
}
|
||||
}
|
||||
|
||||
val maxEntries = 10
|
||||
val lruCache = object : LinkedHashMap<String, Int>(10, 0.75f) {
|
||||
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Int>?): Boolean {
|
||||
return size > maxEntries
|
||||
}
|
||||
}
|
||||
|
||||
val map = object : LinkedHashMap<String, Int>() {
|
||||
// omitted
|
||||
}
|
||||
|
||||
val serializableChannel = object : Channel, Serializable {
|
||||
override fun isOpen(): Boolean {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
}
|
||||
|
||||
val obj = object {
|
||||
val question = "answer"
|
||||
val answer = 42
|
||||
}
|
||||
println("The ${obj.question} is ${obj.answer}")
|
||||
}
|
|
@ -11,3 +11,4 @@ This module contains articles about data structures in Java
|
|||
- [Introduction to Big Queue](https://www.baeldung.com/java-big-queue)
|
||||
- [Guide to AVL Trees in Java](https://www.baeldung.com/java-avl-trees)
|
||||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Implementing a Ring Buffer in Java](https://www.baeldung.com/java-ring-buffer)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue