Merge branch 'master' into BAEL-5197/new_features_in_javav17

This commit is contained in:
Thiago dos Santos Hora
2021-11-06 12:19:15 +01:00
committed by GitHub
284 changed files with 3627 additions and 1081 deletions
-19
View File
@@ -32,24 +32,6 @@
<artifactId>mockserver-junit-jupiter</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
@@ -106,7 +88,6 @@
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version>
<junit.jupiter.version>5.7.0</junit.jupiter.version>
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
-12
View File
@@ -22,18 +22,6 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
-12
View File
@@ -27,18 +27,6 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
-12
View File
@@ -28,18 +28,6 @@
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
+2
View File
@@ -1 +1,3 @@
### Relevant articles:
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)
@@ -0,0 +1,25 @@
package com.baeldung.switchpatterns;
public class GuardedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
yield Double.parseDouble(s);
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingGuardedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 -> Double.parseDouble(s);
default -> 0d;
};
}
}
@@ -0,0 +1,20 @@
package com.baeldung.switchpatterns;
public class HandlingNullValues {
static double getDoubleUsingSwitchNullCase(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case null -> 0d;
default -> 0d;
};
}
static double getDoubleUsingSwitchTotalType(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case Object ob -> 0d;
};
}
}
@@ -0,0 +1,29 @@
package com.baeldung.switchpatterns;
public class ParenthesizedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
if (s.contains("#") || s.contains("@")) {
yield 0d;
} else {
yield Double.parseDouble(s);
}
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingParenthesizedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 && !(s.contains("#") || s.contains("@")) -> Double.parseDouble(s);
default -> 0d;
};
}
}
@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class PatternMatching {
public static void main(String[] args) {
Object o = args[0];
if (o instanceof String s) {
System.out.printf("Object is a string %s", s);
} else if(o instanceof Number n) {
System.out.printf("Object is a number %n", n);
}
}
}
@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class SwitchStatement {
public static void main(String[] args) {
final String b = "B";
switch (args[0]) {
case "A" -> System.out.println("Parameter is A");
case b -> System.out.println("Parameter is b");
default -> System.out.println("Parameter is unknown");
};
}
}
@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
public class TypePatterns {
static double getDoubleUsingIf(Object o) {
double result;
if (o instanceof Integer) {
result = ((Integer) o).doubleValue();
} else if (o instanceof Float) {
result = ((Float) o).doubleValue();
} else if (o instanceof String) {
result = Double.parseDouble(((String) o));
} else {
result = 0d;
}
return result;
}
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case Integer i -> i.doubleValue();
case Float f -> f.doubleValue();
case String s -> Double.parseDouble(s);
default -> 0d;
};
}
}
@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.GuardedPatterns.*;
class GuardedPatternsUnitTest {
@Test
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf(""));
}
@Test
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingIf("10"));
}
@Test
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingGuardedPatterns(""));
}
@Test
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingGuardedPatterns("10"));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.HandlingNullValues.*;
class HandlingNullValuesUnitTest {
@Test
void givenNullCaseInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitchNullCase("10"));
}
@Test
void givenTotalTypeInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitchNullCase(null));
}
@Test
void givenTotalTypeInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitchTotalType("10"));
}
@Test
void givenNullCaseInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitchTotalType(null));
}
}
@@ -0,0 +1,40 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.ParenthesizedPatterns.*;
class ParenthesizedPatternsUnitTest {
@Test
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf(""));
}
@Test
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingIf("10"));
}
@Test
void givenIfImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf("@10"));
}
@Test
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns(""));
}
@Test
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingParenthesizedPatterns("10"));
}
@Test
void givenPatternsImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns("@10"));
}
}
@@ -0,0 +1,49 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.TypePatterns.*;
class TypePatternsUnitTest {
@Test
void givenIfImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf(10));
}
@Test
void givenIfImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf(10.0f));
}
@Test
void givenIfImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf("10"));
}
@Test
void givenIfImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingIf('c'));
}
@Test
void givenSwitchImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch(10));
}
@Test
void givenSwitchImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch(10.0f));
}
@Test
void givenSwitchImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch("10"));
}
@Test
void givenSwitchImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitch('c'));
}
}
@@ -40,7 +40,7 @@
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -70,7 +70,6 @@
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
@@ -29,7 +29,7 @@
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -158,7 +158,6 @@
<rxjava.version>3.0.0</rxjava.version>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>4.0.2</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
+1 -2
View File
@@ -35,7 +35,7 @@
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -80,7 +80,6 @@
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
@@ -5,3 +5,4 @@ This module contains articles about arrays conversion in Java
## Relevant Articles
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
@@ -43,7 +43,7 @@
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -52,7 +52,6 @@
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.11.1</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
@@ -15,12 +15,6 @@
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
@@ -32,6 +26,12 @@
<artifactId>tempus-fugit</artifactId>
<version>${tempus-fugit.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
@@ -96,7 +96,6 @@
</build>
<properties>
<junit.version>4.13</junit.version>
<threadweaver.version>0.2</threadweaver.version>
<tempus-fugit.version>1.1</tempus-fugit.version>
<multithreadedtc.version>1.01</multithreadedtc.version>
@@ -2,3 +2,4 @@
### Relevant Articles:
- [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi)
- [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth)
+13 -18
View File
@@ -15,23 +15,6 @@
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
@@ -58,6 +41,18 @@
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-test-framework</artifactId>
<version>${apacheds.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.21.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -76,7 +71,7 @@
<properties>
<spring.version>5.0.9.RELEASE</spring.version>
<h2.version>1.4.199</h2.version>
<jupiter.version>5.5.1</jupiter.version>
<apacheds.version>2.0.0.AM26</apacheds.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
@@ -0,0 +1,165 @@
package com.baeldung.jndi.ldap.auth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(FrameworkRunner.class)
@CreateLdapServer(transports = { @CreateTransport(protocol = "LDAP", address = "localhost", port = 10390)})
@CreateDS(
allowAnonAccess = false, partitions = {@CreatePartition(name = "TestPartition", suffix = "dc=baeldung,dc=com")})
@ApplyLdifFiles({"users.ldif"})
// class marked as manual test, as it has to run independently from the other unit tests in the module
public class JndiLdapAuthManualTest extends AbstractLdapTestUnit {
private static void authenticateUser(Hashtable<String, String> environment) throws Exception {
DirContext context = new InitialDirContext(environment);
context.close();
}
@Test
public void givenPreloadedLDAPUserJoe_whenAuthUserWithCorrectPW_thenAuthSucceeds() throws Exception {
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
environment.put(Context.SECURITY_CREDENTIALS, "12345");
assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();
}
@Test
public void givenPreloadedLDAPUserJoe_whenAuthUserWithWrongPW_thenAuthFails() throws Exception {
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
environment.put(Context.SECURITY_CREDENTIALS, "wronguserpw");
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticateUser(environment));
}
@Test
public void givenPreloadedLDAPUserJoe_whenSearchAndAuthUserWithCorrectPW_thenAuthSucceeds() throws Exception {
// first authenticate against LDAP as admin to search up DN of user : Joe Simms
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
environment.put(Context.SECURITY_CREDENTIALS, "secret");
DirContext adminContext = new InitialDirContext(environment);
// define the search filter to find the person with CN : Joe Simms
String filter = "(&(objectClass=person)(cn=Joe Simms))";
// declare the attributes we want returned for the object being searched
String[] attrIDs = { "cn" };
// define the search controls
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// search for User with filter cn=Joe Simms
NamingEnumeration<SearchResult> searchResults = adminContext.search("dc=baeldung,dc=com", filter, searchControls);
if (searchResults.hasMore()) {
SearchResult result = (SearchResult) searchResults.next();
Attributes attrs = result.getAttributes();
String distinguishedName = result.getNameInNamespace();
assertThat(distinguishedName).isEqualTo("cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
String commonName = attrs.get("cn").toString();
assertThat(commonName).isEqualTo("cn: Joe Simms");
// authenticate new context with DN for user Joe Simms, using correct password
environment.put(Context.SECURITY_PRINCIPAL, distinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, "12345");
assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();
}
adminContext.close();
}
@Test
public void givenPreloadedLDAPUserJoe_whenSearchAndAuthUserWithWrongPW_thenAuthFails() throws Exception {
// first authenticate against LDAP as admin to search up DN of user : Joe Simms
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10390");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
environment.put(Context.SECURITY_CREDENTIALS, "secret");
DirContext adminContext = new InitialDirContext(environment);
// define the search filter to find the person with CN : Joe Simms
String filter = "(&(objectClass=person)(cn=Joe Simms))";
// declare the attributes we want returned for the object being searched
String[] attrIDs = { "cn" };
// define the search controls
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// search for User with filter cn=Joe Simms
NamingEnumeration<SearchResult> searchResults = adminContext.search("dc=baeldung,dc=com", filter, searchControls);
if (searchResults.hasMore()) {
SearchResult result = (SearchResult) searchResults.next();
Attributes attrs = result.getAttributes();
String distinguishedName = result.getNameInNamespace();
assertThat(distinguishedName).isEqualTo("cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
String commonName = attrs.get("cn").toString();
assertThat(commonName).isEqualTo("cn: Joe Simms");
// authenticate new context with DN for user Joe Simms, using wrong password
environment.put(Context.SECURITY_PRINCIPAL, distinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, "wronguserpassword");
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticateUser(environment));
}
adminContext.close();
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,20 @@
version: 1
dn: dc=baeldung,dc=com
objectClass: domain
objectClass: top
dc: baeldung
dn: ou=Users,dc=baeldung,dc=com
objectClass: organizationalUnit
objectClass: top
ou: Users
dn: cn=Joe Simms,ou=Users,dc=baeldung,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Joe Simms
sn: Simms
uid: user1
userPassword: 12345
@@ -15,12 +15,6 @@
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
-6
View File
@@ -16,12 +16,6 @@
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
@@ -0,0 +1,34 @@
package com.baeldung.constructorchaining;
import java.util.Objects;
public class Customer extends Person {
private final String loyaltyCardId;
public Customer(String firstName, String lastName, int age, String loyaltyCardId) {
this(firstName, null, lastName, age, loyaltyCardId);
}
public Customer(String firstName, String middleName, String lastName, int age, String loyaltyCardId) {
super(firstName, middleName, lastName, age);
this.loyaltyCardId = loyaltyCardId;
}
public String getLoyaltyCardId() {
return loyaltyCardId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Customer customer = (Customer) o;
return Objects.equals(loyaltyCardId, customer.loyaltyCardId);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), loyaltyCardId);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.constructorchaining;
import java.util.Objects;
public class Person {
private final String firstName;
private final String middleName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this(firstName, null, lastName, age);
}
public Person(String firstName, String middleName, String lastName, int age) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getMiddleName() {
return middleName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(middleName, person.middleName) && Objects.equals(lastName, person.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, middleName, lastName, age);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.constructorchaining;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CustomerUnitTest {
@Test
public void givenNameLastNameAndAge_whenUsingDedicatedConstructor_shouldInitializeFieldsAndNullifyMiddleName() {
Customer mark = new Customer("Mark", "Johnson", 23, "abcd1234");
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Johnson", mark.getLastName());
assertEquals("abcd1234", mark.getLoyaltyCardId());
assertNull(mark.getMiddleName());
}
@Test
public void givenAllFieldsRequired_whenUsingDedicatedConstructor_shouldInitializeAllFields() {
Customer mark = new Customer("Mark", "Andrew", "Johnson", 23, "abcd1234");
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Andrew", mark.getMiddleName());
assertEquals("Johnson", mark.getLastName());
assertEquals("abcd1234", mark.getLoyaltyCardId());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.constructorchaining;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class PersonUnitTest {
@Test
public void givenNameLastNameAndAge_whenUsingDedicatedConstructor_shouldInitializeFieldsAndNullifyMiddleName() {
Person mark = new Person("Mark", "Johnson", 23);
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Johnson", mark.getLastName());
assertNull(mark.getMiddleName());
}
@Test
public void givenAllFieldsRequired_whenUsingDedicatedConstructor_shouldInitializeAllFields() {
Person mark = new Person("Mark", "Andrew", "Johnson", 23);
assertEquals(23, mark.getAge());
assertEquals("Mark", mark.getFirstName());
assertEquals("Andrew", mark.getMiddleName());
assertEquals("Johnson", mark.getLastName());
}
}
@@ -35,12 +35,6 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
-7
View File
@@ -16,12 +16,6 @@
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter-engine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
@@ -94,7 +88,6 @@
<guava.version>25.1-jre</guava.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<junit-jupiter-engine.version>5.7.2</junit-jupiter-engine.version>
</properties>
</project>
@@ -1,5 +1,6 @@
package com.baeldung.example.soundapi;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
@@ -37,6 +38,7 @@ public class AppUnitTest {
}
@Test
@Disabled
public void Given_TargetLineDataObject_When_Run_Then_GeneratesOutputStream() {
soundRecorder.setFormat(af);
@@ -52,6 +54,7 @@ public class AppUnitTest {
}
@Test
@Disabled
public void Given_AudioInputStream_When_NotNull_Then_SaveToWavFile() {
soundRecorder.setFormat(af);
soundRecorder.build(af);
@@ -30,13 +30,6 @@
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -26,11 +26,6 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
@@ -10,3 +10,4 @@ This module contains articles about string APIs.
- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string)
- [StringBuilder vs StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Getting a Character by Index From a String in Java](https://www.baeldung.com/java-character-at-position)
@@ -0,0 +1,29 @@
package com.baeldung.stringapi;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class StringCharAtUnitTest {
@Test
public void whenCallCharAt_thenSuccess() {
String sample = "abcdefg";
assertEquals('d', sample.charAt(3));
}
@Test()
public void whenCharAtNonExist_thenIndexOutOfBoundsExceptionThrown() {
String sample = "abcdefg";
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(sample.length()));
}
@Test
public void whenCallCharAt_thenReturnString() {
String sample = "abcdefg";
assertEquals("a", Character.toString(sample.charAt(0)));
assertEquals("a", String.valueOf(sample.charAt(0)));
}
}
@@ -20,12 +20,6 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
@@ -6,3 +6,6 @@
- [Split a String in Java and Keep the Delimiters](https://www.baeldung.com/java-split-string-keep-delimiters)
- [Validate String as Filename in Java](https://www.baeldung.com/java-validate-filename)
- [Count Spaces in a Java String](https://www.baeldung.com/java-string-count-spaces)
- [Remove Accents and Diacritics From a String in Java](https://www.baeldung.com/java-remove-accents-from-text)
- [Remove Beginning and Ending Double Quotes from a String](https://www.baeldung.com/java-remove-start-end-double-quote)
- [Splitting a Java String by Multiple Delimiters](https://www.baeldung.com/java-string-split-multiple-delimiters)
@@ -52,6 +52,11 @@
<artifactId>semver4j</artifactId>
<version>${semver4j.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
@@ -80,6 +85,7 @@
<assertj.version>3.6.1</assertj.version>
<spring-core.version>5.3.9</spring-core.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
<guava.version>31.0.1-jre</guava.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>
@@ -0,0 +1,66 @@
package com.baeldung.multipledelimiterssplit;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.Arrays;
import java.util.regex.Pattern;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MultipleDelimitersSplitUnitTest {
@Test
public void givenString_whenSplittingByMultipleDelimitersWithRegEx_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] names = example.split(";|:|-");
String[] expectedNames = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Assertions.assertEquals(4, names.length);
Assertions.assertArrayEquals(expectedNames, names);
}
@Test
public void givenString_whenSplittingByWithCharMatcherAndOnMethod_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.on(CharMatcher.anyOf(";:-")).split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByWithRegexAndOnPatternMethod_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.on(Pattern.compile(";|:|-")).split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByMultipleDelimitersWithGuava_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedArray = new String[]{"Mary", "Thomas", "Jane", "Kate"};
Iterable<String> expected = Arrays.asList(expectedArray);
Iterable<String> names = Splitter.onPattern(";|:|-").split(example);
Assertions.assertEquals(4, Iterators.size(names.iterator()));
Assertions.assertIterableEquals(expected, names);
}
@Test
public void givenString_whenSplittingByMultipleDelimitersWithApache_thenStringSplit() {
String example = "Mary;Thomas:Jane-Kate";
String[] expectedNames = new String[]{"Mary", "Thomas", "Jane", "Kate"};
String[] names = StringUtils.split(example, ";:-");
Assertions.assertEquals(4, names.length);
Assertions.assertArrayEquals(expectedNames, names);
}
}
@@ -75,8 +75,8 @@
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
@@ -97,8 +97,6 @@
<asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.7</powermock.version>
<jmockit.version>1.44</jmockit.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties>
</project>
@@ -25,12 +25,6 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
-5
View File
@@ -134,9 +134,4 @@
</dependencies>
</dependencyManagement>
<properties>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>