Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima 2022-07-25 10:42:37 -03:00 committed by GitHub
commit e536a0335c
82 changed files with 1048 additions and 132 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.removewhitespace;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class RemoveWhitespaceUnitTest {
private final String myString = " I am a wonderful String ! ";
@Test
void givenStringWithWhitespace_whenRemoveAllWhitespace_shouldGetExpectedResult() {
String result = myString.replaceAll("\\s", "");
assertThat(result).isEqualTo("IamawonderfulString!");
}
@Test
void givenStringWithWhitespace_whenRemoveAllWhitespaceUsingStringUtils_shouldGetExpectedResult() {
String result = StringUtils.deleteWhitespace(myString);
assertThat(result).isEqualTo("IamawonderfulString!");
}
@Test
void givenStringWithWhitespace_whenReplaceConsecutiveSpacesWithSingleSpace_shouldGetExpectedResult() {
String result = myString.replaceAll("\\s+", " ");
assertThat(result).isEqualTo(" I am a wonderful String ! ");
assertThat(result.trim()).isEqualTo("I am a wonderful String !");
}
@Test
void givenStringWithWhitespace_whenNormalizeWithApacheCommons_shouldGetExpectedResult() {
String result = StringUtils.normalizeSpace(myString);
assertThat(result).isEqualTo("I am a wonderful String !");
}
}

View File

@ -2,4 +2,6 @@
- [Introduction to Docker Compose](https://www.baeldung.com/ops/docker-compose)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
- [Communication Between Multiple Docker Compose Projects](https://www.baeldung.com/ops/docker-compose-communication)
- [Difference Between links and depends_on in Docker Compose](https://www.baeldung.com/ops/docker-compose-links-depends-on)

View File

@ -0,0 +1,13 @@
services:
my_app:
image: web-app:latest
container_name: web-app
ports:
- "8080:8080"
networks:
- my-app
networks:
my-app:
name: redis_network
external: true

View File

@ -0,0 +1,13 @@
services:
redis:
image: redis:latest
container_name: redis
ports:
- '6379:6379'
networks:
- network
networks:
network:
driver: bridge
name: redis_network

View File

@ -0,0 +1,12 @@
services:
my_app:
image: web-app:latest
container_name: web-app
ports:
- "8080:8080"
networks:
- network-example
networks:
network-example:
external: true

View File

@ -0,0 +1,12 @@
services:
redis:
image: redis:latest
container_name: redis
ports:
- '6379:6379'
networks:
- network-example
networks:
network-example:
external: true

View File

@ -13,3 +13,4 @@ This module contains articles about Bean Validation.
- [Guide to ParameterMessageInterpolator](https://www.baeldung.com/hibernate-parametermessageinterpolator)
- [Hibernate Validator Annotation Processor in Depth](https://www.baeldung.com/hibernate-validator-annotation-processor)
- [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition)
- [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter)

View File

@ -6,6 +6,10 @@
</encoder>
</appender>
<logger name="org.xacml4j.v30.XacmlPolicyTestSupport" level="warn">
<appender-ref ref="STDOUT" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -0,0 +1,52 @@
<?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>maven-repository-download</artifactId>
<name>Maven Release Repository</name>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>nexus-snapshot</id>
<name>nexus-snapshot</name>
<url>http://localhost:8081/repository/maven-snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>nexus-release</id>
<name>nexus-release</name>
<url>http://localhost:8081/repository/maven-releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-release-repository</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-snapshot-repository</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>maven-release-repository</artifactId>
<name>Maven Release Repository</name>
<version>1.0.0</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>nexus</id>
<name>nexus-release</name>
<url>http://localhost:8081/repository/maven-releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>nexus</id>
<name>nexus-release</name>
<url>http://localhost:8081/repository/maven-releases/</url>
</repository>
</distributionManagement>
</project>

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>maven-snapshot-repository</artifactId>
<name>Maven Snapshot Repository</name>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>nexus</id>
<name>nexus-snapshot</name>
<url>http://localhost:8081/repository/maven-snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<distributionManagement>
<snapshotRepository>
<id>nexus</id>
<name>nexus-snapshot</name>
<url>http://localhost:8081/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>

View File

@ -0,0 +1,23 @@
<?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>maven-repositories</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Maven Repositories</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modules>
<module>maven-release-repository</module>
<module>maven-snapshot-repository</module>
<module>maven-download-artifacts</module>
</modules>
</project>

View File

@ -41,6 +41,7 @@
<module>maven-parent-pom-resolution</module>
<module>maven-simple</module>
<module>maven-classifier</module>
<module>maven-repositories</module>
</modules>
<dependencyManagement>

View File

@ -37,7 +37,7 @@ import com.netflix.spectator.atlas.AtlasConfig;
/**
* @author aiet
*/
public class MicrometerAtlasIntegrationTest {
public class MicrometerAtlasManualTest {
private AtlasConfig atlasConfig;

View File

@ -24,7 +24,8 @@ public class HibernateUtil {
settings.put(Environment.USER, "sa");
settings.put(Environment.PASS, "");
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
// enable to show Hibernate generated SQL
settings.put(Environment.SHOW_SQL, "false");
settings.put(Environment.FORMAT_SQL, "true");
settings.put(Environment.USE_SQL_COMMENTS, "true");
settings.put(Environment.HBM2DDL_AUTO, "update");

View File

@ -2,11 +2,14 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.hibernate" level="error">
<appender-ref ref="STDOUT" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -1,3 +1,4 @@
### Relevant Artilces:
- [Guide to Find in MongoDB](https://www.baeldung.com/mongodb-find)
- [Query Documents using Document ID in MongoDB](https://www.baeldung.com/mongodb-query-documents-id)

View File

@ -4,4 +4,5 @@
- [Configure MongoDB Collection Name for a Class in Spring Data](https://www.baeldung.com/spring-data-mongodb-collection-name)
- [MongoDB Composite Key With Spring Data](https://www.baeldung.com/spring-data-mongodb-composite-key)
- [Unique Field in MongoDB Document in Spring Data](https://www.baeldung.com/spring-data-mongodb-unique)
- [Count Documents Using Spring Data MongoDB Repository](https://www.baeldung.com/spring-data-mongodb-count)
- More articles: [[<--prev]](../spring-boot-persistence-mongodb)

View File

@ -6,6 +6,7 @@ This module contains articles about Spring Data REST
- [Guide to Spring Data REST Validators](https://www.baeldung.com/spring-data-rest-validators)
- [Spring Data Web Support](https://www.baeldung.com/spring-data-web-support)
- [Spring REST and HAL Browser](https://www.baeldung.com/spring-rest-hal)
- [Spring Data Rest Serializing the Entity ID](https://www.baeldung.com/spring-data-rest-serialize-entity-id)
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring

View File

@ -62,6 +62,16 @@
<artifactId>spqr</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.4.3.Final</version>
</dependency>
</dependencies>
<build>
@ -92,6 +102,27 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jboss.jandex</groupId>
<artifactId>jandex-maven-plugin</artifactId>
<version>1.2.3</version>
<executions>
<execution>
<phase>compile</phase>
<id>make-index</id>
<goals>
<goal>jandex</goal>
</goals>
<configuration>
<fileSets>
<fileSet>
<directory>${project.build.outputDirectory}</directory>
</fileSet>
</fileSets>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@ -0,0 +1,14 @@
package com.baeldung.annotation.scanner;
@SampleAnnotation(name = "SampleAnnotatedClass")
public class SampleAnnotatedClass {
@SampleAnnotation(name = "annotatedMethod")
public void annotatedMethod() {
//Do something
}
public void notAnnotatedMethod() {
//Do something
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.annotation.scanner;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({ METHOD, TYPE })
@Retention(RUNTIME)
public @interface SampleAnnotation {
String name();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.annotation.scanner;
import java.util.List;
public interface SampleAnnotationScanner {
List<String> scanAnnotatedMethods();
List<String> scanAnnotatedClasses();
boolean supportsMethodScan();
boolean supportsClassScan();
}

View File

@ -0,0 +1,4 @@
package com.baeldung.annotation.scanner;
public class ScanNotSupportedException extends RuntimeException{
}

View File

@ -0,0 +1,7 @@
package com.baeldung.annotation.scanner;
public class UnexpectedScanException extends RuntimeException {
public UnexpectedScanException(Throwable ex) {
super(ex);
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.annotation.scanner.jandexlib;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.baeldung.annotation.scanner.SampleAnnotationScanner;
import com.baeldung.annotation.scanner.UnexpectedScanException;
@Service
public class JandexScannerService implements SampleAnnotationScanner {
@Value("classpath:META-INF/jandex.idx")
private Resource appFile;
@Override
public List<String> scanAnnotatedMethods() {
try {
final IndexReader reader = new IndexReader(appFile.getInputStream());
Index jandexFile = reader.read();
final List<AnnotationInstance> appAnnotationList = jandexFile.getAnnotations(DotName.createSimple("com.baeldung.annotation.scanner.SampleAnnotation"));
List<String> annotatedMethods = new ArrayList<>();
for (AnnotationInstance annotationInstance : appAnnotationList) {
if (annotationInstance.target()
.kind() == AnnotationTarget.Kind.METHOD) {
annotatedMethods.add(annotationInstance.value("name")
.value()
.toString());
}
}
return Collections.unmodifiableList(annotatedMethods);
} catch (IOException e) {
throw new UnexpectedScanException(e);
}
}
@Override
public List<String> scanAnnotatedClasses() {
try {
final IndexReader reader = new IndexReader(appFile.getInputStream());
Index jandexFile = reader.read();
final List<AnnotationInstance> appAnnotationList = jandexFile.getAnnotations(DotName.createSimple("com.baeldung.annotation.scanner.SampleAnnotation"));
List<String> annotatedClasses = new ArrayList<>();
for (AnnotationInstance annotationInstance : appAnnotationList) {
if (annotationInstance.target()
.kind() == AnnotationTarget.Kind.CLASS) {
annotatedClasses.add(annotationInstance.value("name")
.value()
.toString());
}
}
return Collections.unmodifiableList(annotatedClasses);
} catch (IOException e) {
throw new UnexpectedScanException(e);
}
}
@Override
public boolean supportsMethodScan() {
return true;
}
@Override
public boolean supportsClassScan() {
return true;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.annotation.scanner.javareflectionlib;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.annotation.scanner.SampleAnnotation;
import com.baeldung.annotation.scanner.SampleAnnotationScanner;
import com.baeldung.annotation.scanner.UnexpectedScanException;
@Service
public class JavaReflectionsScannerService implements SampleAnnotationScanner {
@Override
public List<String> scanAnnotatedMethods() {
try {
Class<?> clazz = ClassLoader.getSystemClassLoader()
.loadClass("com.baeldung.annotation.scanner.SampleAnnotatedClass");
Method[] methods = clazz.getMethods();
List<String> annotatedMethods = new ArrayList<>();
for (Method method : methods) {
SampleAnnotation annotation = method.getAnnotation(SampleAnnotation.class);
if (annotation != null) {
annotatedMethods.add(annotation.name());
}
}
return Collections.unmodifiableList(annotatedMethods);
} catch (ClassNotFoundException e) {
throw new UnexpectedScanException(e);
}
}
@Override
public List<String> scanAnnotatedClasses() {
try {
Class<?> clazz = ClassLoader.getSystemClassLoader()
.loadClass("com.baeldung.annotation.scanner.SampleAnnotatedClass");
SampleAnnotation classAnnotation = clazz.getAnnotation(SampleAnnotation.class);
List<String> annotatedClasses = new ArrayList<>();
annotatedClasses.add(classAnnotation.name());
return Collections.unmodifiableList(annotatedClasses);
} catch (ClassNotFoundException e) {
throw new UnexpectedScanException(e);
}
}
@Override
public boolean supportsMethodScan() {
return true;
}
@Override
public boolean supportsClassScan() {
return true;
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.annotation.scanner.reflectionslib;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.reflections.Reflections;
import org.springframework.stereotype.Service;
import com.baeldung.annotation.scanner.SampleAnnotation;
import com.baeldung.annotation.scanner.SampleAnnotationScanner;
@Service
public class ReflectionsScannerService implements SampleAnnotationScanner {
@Override
public List<String> scanAnnotatedMethods() {
Reflections reflections = new Reflections("com.baeldung.annotation.scanner");
Set<Method> methods = reflections.getMethodsAnnotatedWith(SampleAnnotation.class);
return methods.stream()
.map(method -> method.getAnnotation(SampleAnnotation.class)
.name())
.collect(Collectors.toList());
}
@Override
public List<String> scanAnnotatedClasses() {
Reflections reflections = new Reflections("com.baeldung.annotation.scanner");
Set<Class<?>> types = reflections.getTypesAnnotatedWith(SampleAnnotation.class);
return types.stream()
.map(clazz -> clazz.getAnnotation(SampleAnnotation.class)
.name())
.collect(Collectors.toList());
}
@Override
public boolean supportsMethodScan() {
return true;
}
@Override
public boolean supportsClassScan() {
return true;
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.annotation.scanner.springcontextlib;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Service;
import com.baeldung.annotation.scanner.SampleAnnotation;
import com.baeldung.annotation.scanner.SampleAnnotationScanner;
import com.baeldung.annotation.scanner.ScanNotSupportedException;
@Service
public class SpringBeanAnnotationScannerService implements SampleAnnotationScanner {
@Override
public List<String> scanAnnotatedMethods() {
throw new ScanNotSupportedException();
}
@Override
public List<String> scanAnnotatedClasses() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(SampleAnnotation.class));
Set<BeanDefinition> beanDefs = provider.findCandidateComponents("com.baeldung.annotation.scanner");
List<String> annotatedBeans = new ArrayList<>();
for (BeanDefinition bd : beanDefs) {
if (bd instanceof AnnotatedBeanDefinition) {
Map<String, Object> annotAttributeMap = ((AnnotatedBeanDefinition) bd).getMetadata()
.getAnnotationAttributes(SampleAnnotation.class.getCanonicalName());
annotatedBeans.add(annotAttributeMap.get("name")
.toString());
}
}
return Collections.unmodifiableList(annotatedBeans);
}
@Override
public boolean supportsMethodScan() {
return false;
}
@Override
public boolean supportsClassScan() {
return true;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.annotation.scanner.springcorelib;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import com.baeldung.annotation.scanner.SampleAnnotationScanner;
import com.baeldung.annotation.scanner.SampleAnnotatedClass;
import com.baeldung.annotation.scanner.SampleAnnotation;
import com.baeldung.annotation.scanner.ScanNotSupportedException;
@Service
public class SpringCoreAnnotationScannerService implements SampleAnnotationScanner {
@Override
public List<String> scanAnnotatedMethods() {
final Class<?> userClass = ClassUtils.getUserClass(SampleAnnotatedClass.class);
return Arrays.stream(userClass.getMethods())
.filter(method -> AnnotationUtils.getAnnotation(method, SampleAnnotation.class) != null)
.map(method -> method.getAnnotation(SampleAnnotation.class)
.name())
.collect(Collectors.toList());
}
@Override
public List<String> scanAnnotatedClasses() {
throw new ScanNotSupportedException();
}
@Override
public boolean supportsMethodScan() {
return true;
}
@Override
public boolean supportsClassScan() {
return false;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.annotation.scanner;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleAnnotationScannerUnitTest {
@Autowired
private List<SampleAnnotationScanner> scannerList;
@Test
public void givenPackage_whenScanAnnotatedClasses_thenAnnotationValues() {
final List<String> annotatedClasses = scannerList.stream()
.filter(SampleAnnotationScanner::supportsClassScan)
.map(SampleAnnotationScanner::scanAnnotatedClasses)
.flatMap(Collection::stream)
.collect(Collectors.toList());
assertNotNull(annotatedClasses);
assertEquals(4, annotatedClasses.size());
annotatedClasses.forEach(annotValue -> assertEquals("SampleAnnotatedClass", annotValue));
}
@Test
public void givenPackage_whenScanAnnotatedMethods_thenAnnotationValues() {
final List<String> annotatedMethods = scannerList.stream()
.filter(SampleAnnotationScanner::supportsMethodScan)
.map(SampleAnnotationScanner::scanAnnotatedMethods)
.flatMap(Collection::stream)
.collect(Collectors.toList());
assertNotNull(annotatedMethods);
assertEquals(3, annotatedMethods.size());
annotatedMethods.forEach(annotValue -> assertEquals("annotatedMethod", annotValue));
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.defaultglobalsecurityscheme;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "Apply Default Global SecurityScheme in springdoc-openapi", version = "1.0.0"), security = { @SecurityRequirement(name = "api_key") })
@SecurityScheme(type = SecuritySchemeType.APIKEY, name = "api_key", in = SecuritySchemeIn.HEADER)
public class DefaultGlobalSecuritySchemeApplication {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.antMatchers("/api/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html", "/api-docs/**")
.permitAll()
.anyRequest()
.authenticated())
.build();
}
public static void main(String[] args) {
SpringApplication.run(DefaultGlobalSecuritySchemeApplication.class, args);
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.defaultglobalsecurityscheme.controller;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.defaultglobalsecurityscheme.dto.LoginDto;
import com.baeldung.defaultglobalsecurityscheme.dto.ApplicationExceptionDto;
import com.baeldung.defaultglobalsecurityscheme.dto.PingResponseDto;
import com.baeldung.defaultglobalsecurityscheme.dto.TokenDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
@RestController
@RequestMapping("/")
public class DefaultGlobalSecuritySchemeOpenApiController {
@RequestMapping(method = RequestMethod.POST, value = "/login", produces = { "application/json" }, consumes = { "application/json" })
@Operation(operationId = "login", responses = {
@ApiResponse(responseCode = "200", description = "api_key to be used in the secured-ping entry point", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = TokenDto.class)) }),
@ApiResponse(responseCode = "401", description = "Unauthorized request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }) })
@SecurityRequirements()
public ResponseEntity<TokenDto> login(@Parameter(name = "LoginDto", description = "Login") @Valid @RequestBody(required = true) LoginDto loginDto) {
TokenDto token = new TokenDto();
token.setRaw("Generated Token");
return ResponseEntity.ok(token);
}
@Operation(operationId = "ping", responses = {
@ApiResponse(responseCode = "200", description = "Ping that needs an api_key attribute in the header", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = PingResponseDto.class), examples = { @ExampleObject(value = "{ pong: '2022-06-17T18:30:33.465+02:00' }") }) }),
@ApiResponse(responseCode = "401", description = "Unauthorized request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }),
@ApiResponse(responseCode = "403", description = "Forbidden request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }) })
@RequestMapping(method = RequestMethod.GET, value = "/ping", produces = { "application/json" })
public ResponseEntity<PingResponseDto> ping(@RequestHeader(name = "api_key", required = false) String api_key) {
int year = 2000;
int month = 1;
int dayOfMonth = 1;
int hour = 0;
int minute = 0;
int second = 0;
int nanoSeccond = 0;
ZoneOffset offset = ZoneOffset.UTC;
PingResponseDto response = new PingResponseDto();
response.setPong(OffsetDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoSeccond, offset));
return ResponseEntity.ok(response);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.defaultglobalsecurityscheme.dto;
public class ApplicationExceptionDto {
private long errorCode;
private String description;
public ApplicationExceptionDto() {
super();
}
public long getErrorCode() {
return errorCode;
}
public void setErrorCode(long errorCode) {
this.errorCode = errorCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,103 @@
package com.baeldung.defaultglobalsecurityscheme.dto;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* LoginDto
*/
@JsonTypeName("Login")
public class LoginDto {
@JsonProperty("user")
private String user;
@JsonProperty("pass")
private String pass;
public LoginDto user(String user) {
this.user = user;
return this;
}
/**
* Get user
* @return user
*/
@Schema(name = "user", required = true)
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public LoginDto pass(String pass) {
this.pass = pass;
return this;
}
/**
* Get pass
* @return pass
*/
@Schema(name = "pass", required = true)
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoginDto login = (LoginDto) o;
return Objects.equals(this.user, login.user) && Objects.equals(this.pass, login.pass);
}
@Override
public int hashCode() {
return Objects.hash(user, pass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LoginDto {\n");
sb.append(" user: ")
.append(toIndentedString(user))
.append("\n");
sb.append(" pass: ")
.append(toIndentedString(pass))
.append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString()
.replace("\n", "\n ");
}
}

View File

@ -0,0 +1,84 @@
package com.baeldung.defaultglobalsecurityscheme.dto;
import java.time.OffsetDateTime;
import java.util.Objects;
import javax.validation.Valid;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* SecuredPingResponseDto
*/
@JsonTypeName("PingResponse")
public class PingResponseDto {
@JsonProperty("pong")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private OffsetDateTime pong;
public PingResponseDto pong(OffsetDateTime pong) {
this.pong = pong;
return this;
}
/**
* Get pong
* @return pong
*/
@Valid
@Schema(name = "pong", required = false)
public OffsetDateTime getPong() {
return pong;
}
public void setPong(OffsetDateTime pong) {
this.pong = pong;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PingResponseDto securedPingResponse = (PingResponseDto) o;
return Objects.equals(this.pong, securedPingResponse.pong);
}
@Override
public int hashCode() {
return Objects.hash(pong);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PingResponseDto {\n");
sb.append(" pong: ")
.append(toIndentedString(pong))
.append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString()
.replace("\n", "\n ");
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.defaultglobalsecurityscheme.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* LoginDto
*/
@JsonTypeName("Token")
public class TokenDto {
@JsonProperty("raw")
private String raw;
@Schema(name = "raw", example = "app token")
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
@Override
public String toString() {
return "TokenDto [raw=" + raw + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((raw == null) ? 0 : raw.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TokenDto other = (TokenDto) obj;
if (raw == null) {
if (other.raw != null)
return false;
} else if (!raw.equals(other.raw))
return false;
return true;
}
}

View File

@ -11,4 +11,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level)
- [Failed to Load ApplicationContext for JUnit Test of Spring Controller](https://www.baeldung.com/spring-junit-failed-to-load-applicationcontext)
- [Spring Web Service Integration Tests with @WebServiceServerTest](https://www.baeldung.com/spring-webserviceservertest)
- [Spring Boot Testing Redis With Testcontainers](https://www.baeldung.com/spring-boot-redis-testcontainers)
- [Spring Boot Keycloak Integration Testing with Testcontainers](https://www.baeldung.com/spring-boot-keycloak-integration-testing)
- More articles: [[<-- prev]](../spring-boot-testing)

View File

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

View File

@ -1,10 +0,0 @@
### Relevant articles
- [Mockitos Java 8 Features](https://www.baeldung.com/mockito-2-java-8)
- [Lazy Verification with Mockito 2](https://www.baeldung.com/mockito-2-lazy-verification)
- [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception)
- [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis)
- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value)
- [Introduction to Mockitos AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers)
- [Difference Between when() and doXxx() Methods in Mockito](https://www.baeldung.com/java-mockito-when-vs-do)
- [Overview of Mockito MockSettings](https://www.baeldung.com/mockito-mocksettings)

View File

@ -1,31 +0,0 @@
<?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>mockito-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mockito-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>testing-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,9 +1,10 @@
*.class
.settings
.project
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*

View File

@ -1,8 +1,12 @@
=========
### Relevant articles
## Mockito Cookbooks and Examples
### Relevant Articles:
- [Mockitos Java 8 Features](https://www.baeldung.com/mockito-2-java-8)
- [Lazy Verification with Mockito 2](https://www.baeldung.com/mockito-2-lazy-verification)
- [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception)
- [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis)
- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value)
- [Introduction to Mockitos AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers)
- [Difference Between when() and doXxx() Methods in Mockito](https://www.baeldung.com/java-mockito-when-vs-do)
- [Overview of Mockito MockSettings](https://www.baeldung.com/mockito-mocksettings)
- [Testing Callbacks with Mockito](https://www.baeldung.com/mockito-callbacks)
- [Quick Guide to BDDMockito](https://www.baeldung.com/bdd-mockito)

View File

@ -4,75 +4,28 @@
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>mockito</artifactId>
<version>0.1-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
<name>mockito</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
<artifactId>testing-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>${javax.persistence.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mockito</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
<spring-framework.version>5.0.8.RELEASE</spring-framework.version>
<spring-data.version>2.0.9.RELEASE</spring-data.version>
<!-- testing -->
<powermock.version>2.0.2</powermock.version>
<javax.persistence.version>2.1.1</javax.persistence.version>
</properties>
</project>

View File

@ -2,17 +2,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -29,7 +29,6 @@
<module>junit5-annotations</module>
<module>junit5-migration</module>
<module>load-testing-comparison</module>
<module>mockito-2</module>
<module>mockito</module>
<module>mockito-simple</module>
<module>mocks</module>

View File

@ -5,3 +5,4 @@ This module contains articles about eXtensible Markup Language (XML)
### Relevant Articles:
- [Pretty-Print XML in Java](https://www.baeldung.com/java-pretty-print-xml)
- [Validate an XML File against an XSD File](https://www.baeldung.com/java-validate-xml-xsd)