Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima
2022-07-20 11:29:49 -03:00
committed by GitHub
60 changed files with 572 additions and 673 deletions
@@ -7,15 +7,35 @@ import java.util.List;
public class FileSizeFormatUtil {
private static final long BYTE = 1L;
private static final long KB = BYTE << 10;
private static final long MB = KB << 10;
private static final long GB = MB << 10;
private static final long TB = GB << 10;
private static final long PB = TB << 10;
private static final long EB = PB << 10;
private static final long KiB = BYTE << 10;
private static final long MiB = KiB << 10;
private static final long GiB = MiB << 10;
private static final long TiB = GiB << 10;
private static final long PiB = TiB << 10;
private static final long EiB = PiB << 10;
private static final long KB = BYTE * 1000;
private static final long MB = KB * 1000;
private static final long GB = MB * 1000;
private static final long TB = GB * 1000;
private static final long PB = TB * 1000;
private static final long EB = PB * 1000;
private static final DecimalFormat DEC_FORMAT = new DecimalFormat("#.##");
public static String toHumanReadable(long size) {
public static String toHumanReadableBinaryPrefixes(long size) {
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
if (size >= EiB) return formatSize(size, EiB, "EiB");
if (size >= PiB) return formatSize(size, PiB, "PiB");
if (size >= TiB) return formatSize(size, TiB, "TiB");
if (size >= GiB) return formatSize(size, GiB, "GiB");
if (size >= MiB) return formatSize(size, MiB, "MiB");
if (size >= KiB) return formatSize(size, KiB, "KiB");
return formatSize(size, BYTE, "Bytes");
}
public static String toHumanReadableSIPrefixes(long size) {
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
if (size >= EB) return formatSize(size, EB, "EB");
@@ -26,23 +46,37 @@ public class FileSizeFormatUtil {
if (size >= KB) return formatSize(size, KB, "KB");
return formatSize(size, BYTE, "Bytes");
}
private static String formatSize(long size, long divider, String unitName) {
return DEC_FORMAT.format((double) size / divider) + " " + unitName;
}
public static String toHumanReadableWithEnum(long size) {
final List<SizeUnit> units = SizeUnit.unitsInDescending();
public static String toHumanReadableBinaryPrefixesWithEnum(long size) {
final List<SizeUnitBinaryPrefixes> units = SizeUnitBinaryPrefixes.unitsInDescending();
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
String result = null;
for (SizeUnit unit : units) {
for (SizeUnitBinaryPrefixes unit : units) {
if (size >= unit.getUnitBase()) {
result = formatSize(size, unit.getUnitBase(), unit.name());
break;
}
}
return result == null ? formatSize(size, SizeUnit.Bytes.getUnitBase(), SizeUnit.Bytes.name()) : result;
return result == null ? formatSize(size, SizeUnitBinaryPrefixes.Bytes.getUnitBase(), SizeUnitBinaryPrefixes.Bytes.name()) : result;
}
public static String toHumanReadableSIPrefixesWithEnum(long size) {
final List<SizeUnitSIPrefixes> units = SizeUnitSIPrefixes.unitsInDescending();
if (size < 0)
throw new IllegalArgumentException("Invalid file size: " + size);
String result = null;
for (SizeUnitSIPrefixes unit : units) {
if (size >= unit.getUnitBase()) {
result = formatSize(size, unit.getUnitBase(), unit.name());
break;
}
}
return result == null ? formatSize(size, SizeUnitSIPrefixes.Bytes.getUnitBase(), SizeUnitSIPrefixes.Bytes.name()) : result;
}
public static String toHumanReadableByNumOfLeadingZeros(long size) {
@@ -50,22 +84,22 @@ public class FileSizeFormatUtil {
throw new IllegalArgumentException("Invalid file size: " + size);
if (size < 1024) return size + " Bytes";
int unitIdx = (63 - Long.numberOfLeadingZeros(size)) / 10;
return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "B");
return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "iB");
}
enum SizeUnit {
enum SizeUnitBinaryPrefixes {
Bytes(1L),
KB(Bytes.unitBase << 10),
MB(KB.unitBase << 10),
GB(MB.unitBase << 10),
TB(GB.unitBase << 10),
PB(TB.unitBase << 10),
EB(PB.unitBase << 10);
KiB(Bytes.unitBase << 10),
MiB(KiB.unitBase << 10),
GiB(MiB.unitBase << 10),
TiB(GiB.unitBase << 10),
PiB(TiB.unitBase << 10),
EiB(PiB.unitBase << 10);
private final Long unitBase;
public static List<SizeUnit> unitsInDescending() {
List<SizeUnit> list = Arrays.asList(values());
public static List<SizeUnitBinaryPrefixes> unitsInDescending() {
List<SizeUnitBinaryPrefixes> list = Arrays.asList(values());
Collections.reverse(list);
return list;
}
@@ -74,7 +108,33 @@ public class FileSizeFormatUtil {
return unitBase;
}
SizeUnit(long unitBase) {
SizeUnitBinaryPrefixes(long unitBase) {
this.unitBase = unitBase;
}
}
enum SizeUnitSIPrefixes {
Bytes(1L),
KB(Bytes.unitBase * 1000),
MB(KB.unitBase * 1000),
GB(MB.unitBase * 1000),
TB(GB.unitBase * 1000),
PB(TB.unitBase * 1000),
EB(PB.unitBase * 1000);
private final Long unitBase;
public static List<SizeUnitSIPrefixes> unitsInDescending() {
List<SizeUnitSIPrefixes> list = Arrays.asList(values());
Collections.reverse(list);
return list;
}
public Long getUnitBase() {
return unitBase;
}
SizeUnitSIPrefixes(long unitBase) {
this.unitBase = unitBase;
}
}
@@ -8,33 +8,53 @@ import java.util.HashMap;
import java.util.Map;
public class FileSizeFormatUtilUnitTest {
private final static Map<Long, String> DATA_MAP = new HashMap<Long, String>() {{
private final static Map<Long, String> DATA_MAP_BINARY_PREFIXES = new HashMap<Long, String>() {{
put(0L, "0 Bytes");
put(1023L, "1023 Bytes");
put(1024L, "1 KB");
put(12_345L, "12.06 KB");
put(10_123_456L, "9.65 MB");
put(10_123_456_798L, "9.43 GB");
put(1_777_777_777_777_777_777L, "1.54 EB");
put(1024L, "1 KiB");
put(12_345L, "12.06 KiB");
put(10_123_456L, "9.65 MiB");
put(10_123_456_798L, "9.43 GiB");
put(1_777_777_777_777_777_777L, "1.54 EiB");
}};
private final static Map<Long, String> DATA_MAP_SI_PREFIXES = new HashMap<Long, String>() {{
put(0L, "0 Bytes");
put(999L, "999 Bytes");
put(1000L, "1 KB");
put(12_345L, "12.35 KB");
put(10_123_456L, "10.12 MB");
put(10_123_456_798L, "10.12 GB");
put(1_777_777_777_777_777_777L, "1.78 EB");
}};
@Test
public void givenBytes_whenCalltoHumanReadableMethod_thenGetExpectedResults() {
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadable(in)));
public void givenBytes_whenCalltoHumanReadableBinaryPrefixesMethod_thenGetExpectedResults() {
DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableBinaryPrefixes(in)));
}
@Test
public void givenBytes_whenCalltoHumanReadableSIPrefixesMethod_thenGetExpectedResults() {
DATA_MAP_SI_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableSIPrefixes(in)));
}
@Test
public void givenBytes_whenCalltoHumanReadableWithEnumMethod_thenGetExpectedResults() {
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableWithEnum(in)));
public void givenBytes_whenCalltoHumanReadableBinaryPrefixesWithEnumMethod_thenGetExpectedResults() {
DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableBinaryPrefixesWithEnum(in)));
}
@Test
public void givenBytes_whenCalltoHumanReadableSIPrefixesWithEnumMethod_thenGetExpectedResults() {
DATA_MAP_SI_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableSIPrefixesWithEnum(in)));
}
@Test
public void givenBytes_whenCalltoHumanReadableByLeadingZeros_thenGetExpectedResults() {
DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in)));
DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in)));
}
@Test
public void givenBytes_whenCalltoHumanReadableByFileUtils_thenOutputExpectedResults() {
DATA_MAP.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in)));
DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in)));
}
}
+4
View File
@@ -0,0 +1,4 @@
FROM openjdk:11
MAINTAINER baeldung.com
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
@@ -0,0 +1,14 @@
services:
db:
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
web-app:
image: web-app:latest
ports:
- 8080:8080
depends_on:
- db
@@ -0,0 +1,14 @@
services:
db:
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
web-app:
image: web-app:latest
ports:
- 8080:8080
links:
- db
@@ -0,0 +1,36 @@
services:
db:
image: postgres:latest
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
volumes:
- db:/var/lib/postgresql/data
networks:
- mynet
web-app:
image: web-app:latest
depends_on:
- db
networks:
- mynet
ports:
- 8080:8080
environment:
DB_HOST: db
DB_PORT: 5432
DB_USER: postgres
DB_PASSWORD: postgres
DB_NAME: postgres
networks:
mynet:
driver: bridge
volumes:
db:
driver: local
+10
View File
@@ -34,6 +34,16 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.docker.app.DockAppApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
+15 -3
View File
@@ -34,8 +34,19 @@
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- uncomment in order to enable Hibernate Validator Anotation Processor -->
<!-- <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version> <configuration> <source>${maven.compiler.source}</source>
@@ -46,13 +57,14 @@
</plugin> </plugins> </build> -->
<properties>
<hibernate-validator.version>6.0.13.Final</hibernate-validator.version>
<hibernate-validator.version>6.2.3.Final</hibernate-validator.version>
<hibernate-validator.ap.version>6.2.0.Final</hibernate-validator.ap.version>
<maven.compiler.version>3.6.1</maven.compiler.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<javax.el.version>3.0.0</javax.el.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.version>5.3.21</org.springframework.version>
<spring.boot.version>2.7.1</spring.boot.version>
</properties>
</project>
@@ -0,0 +1,22 @@
package com.baeldung.javaxval.notnull;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
public class NotNullMethodParameter {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
public int doesNotValidateNotNull(@NotNull String myString) {
return myString.length();
}
public int validateNotNull(@NotNull String myString) {
validator.validate(myString);
return myString.length();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.javaxval.notnull;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@Component
@Validated
public class ValidatingComponent {
public int validateNotNull(@NotNull String data)
{
return data.length();
}
public int callAnnotatedMethod(String data) {
return validateNotNull(data);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.javaxval.notnull;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class NotNullMethodParameterUnitTest {
private NotNullMethodParameter demo = new NotNullMethodParameter();
@Test
public void givenNull_whenInvokedwithNoValidator_thenNullPointerException() {
assertThrows(NullPointerException.class, () -> demo.doesNotValidateNotNull(null));
}
@Test
public void givenNull_whenInvokedWithValidator_thenIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> demo.validateNotNull(null));
}
}
@@ -0,0 +1,43 @@
package com.baeldung.javaxval.notnull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.NotNull;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
class ValidatingComponentIntegrationTest {
@Autowired ValidatingComponent component;
@Test
void givenValue_whenValidate_thenSuccess() {
assertThat(component.validateNotNull("Not null!"), is(9));
}
@Test
void givenNull_whenValidate_thenConstraintViolationException() {
ConstraintViolationException constraintViolationException = assertThrows(ConstraintViolationException.class, () -> component.validateNotNull(null));
Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
assertThat(constraintViolations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType(), is(NotNull.class));
}
@Test
void givenNull_whenOnlyCalledMethodHasAnnotation_thenNoValidation() {
assertThrows(NullPointerException.class, () -> component.callAnnotatedMethod(null));
}
@SpringBootApplication
static class TestApplication {
}
}
@@ -82,6 +82,16 @@ class WebClientIntegrationTest {
.verify();
}
@Test
void givenWebClientCreationWithoutUri_whenUsed_thenObtainExpectedResponse() {
WebClient client = WebClient.create();
StepVerifier.create(retrieveResponse(client))
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
.contains("Connection refused"))
.verify();
}
@Test
void givenDifferentMethodSpecifications_whenUsed_thenObtainExpectedResponse() {
// request specification
@@ -111,12 +121,6 @@ class WebClientIntegrationTest {
.build());
RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(
URI.create("http://localhost:" + port + "/resource"));
RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource"));
RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder()
.baseUrl("http://localhost:" + port)
.build()
.post()
.uri(URI.create("/resource"));
// response assertions
StepVerifier.create(retrieveResponse(bodySpecUsingString))
@@ -128,12 +132,22 @@ class WebClientIntegrationTest {
StepVerifier.create(retrieveResponse(bodySpecusingURI))
.expectNext("processed-bodyValue")
.verifyComplete();
// assert sending request overriding base URI
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri))
}
@Test
void givenOverriddenUriSpecifications_whenUsed_thenObtainExpectedResponse() {
RequestBodySpec bodySpecOverriddenBaseUri = createDefaultPostRequest().uri(URI.create("/resource"));
StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri))
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
.contains("Connection refused"))
.verify();
StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2))
RequestBodySpec bodySpecOverriddenBaseUri2 = WebClient.builder()
.baseUrl("http://localhost:" + port)
.build()
.post()
.uri(URI.create("/resource"));
StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri2))
.expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage()
.contains("Connection refused"))
.verify();
@@ -301,30 +315,35 @@ class WebClientIntegrationTest {
.uri("/resource")
.bodyValue(BODY_VALUE)
.retrieve()
.bodyToMono(String.class);
.bodyToMono(String.class)
.log();
}
private Mono<String> retrieveResponse(RequestBodyUriSpec spec) {
return spec.uri("/resource")
.bodyValue(BODY_VALUE)
.retrieve()
.bodyToMono(String.class);
.bodyToMono(String.class)
.log();
}
private Mono<Map<String, String>> retrieveGetResponse(RequestHeadersUriSpec<?> spec) {
return spec.uri("/resource")
.retrieve()
.bodyToMono(MAP_RESPONSE_REF);
.bodyToMono(MAP_RESPONSE_REF)
.log();
}
private Mono<String> retrieveResponse(RequestBodySpec spec) {
return spec.bodyValue(BODY_VALUE)
.retrieve()
.bodyToMono(String.class);
.bodyToMono(String.class)
.log();
}
private Mono<String> retrieveResponse(RequestHeadersSpec<?> spec) {
return spec.retrieve()
.bodyToMono(String.class);
.bodyToMono(String.class)
.log();
}
}
@@ -10,8 +10,12 @@ import org.testcontainers.utility.DockerImageName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Requires Docker running on the machine to run without errors
* Therefore, skipped from pipeline
*/
@SpringBootTest
public class ProductServiceIntegrationTest {
public class ProductServiceManualTest {
static {
GenericContainer<?> redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine"))
+2 -2
View File
@@ -14,8 +14,7 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>spring-5-security</module>
<modules>
<module>spring-security-acl</module>
<module>spring-security-auth0</module>
<module>spring-security-cognito</module>
@@ -35,6 +34,7 @@
<module>spring-security-web-boot-3</module>
<module>spring-security-web-digest-auth</module>
<module>spring-security-web-login</module>
<module>spring-security-web-login-2</module>
<module>spring-security-web-mvc-custom</module>
<module>spring-security-web-mvc</module>
<module>spring-security-web-persistent-login</module>
@@ -1,13 +0,0 @@
## Spring 5 Security
This module contains articles about Spring Security 5
## Relevant articles:
- [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer)
- [New Password Storage In Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage)
- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder)
- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver)
- [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout)
- [How to Disable Spring Security Logout Redirects](https://www.baeldung.com/spring-security-disable-logout-redirects)
- [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss)
File diff suppressed because it is too large Load Diff
@@ -1,11 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Home
Welcome!
</body>
</html>
@@ -5,6 +5,9 @@ This module contains articles about core Spring Security
### Relevant Articles:
- [Handle Spring Security Exceptions](https://www.baeldung.com/spring-security-exceptions)
- [Handle Spring Security Exceptions With @ExceptionHandler](https://www.baeldung.com/spring-security-exceptionhandler)
- [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss)
- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver)
- [A Custom Spring SecurityConfigurer|https://www.baeldung.com/spring-security-custom-configurer]
### Build the Project
@@ -1,5 +1,6 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;

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