Skip to content

Commit

Permalink
Polish code with code cleanup rules
Browse files Browse the repository at this point in the history
  • Loading branch information
philwebb committed Dec 4, 2024
1 parent 1edc997 commit 9e7972a
Show file tree
Hide file tree
Showing 19 changed files with 72 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.ManagedBeanSettings;

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
Expand Down Expand Up @@ -121,7 +121,7 @@ private List<HibernatePropertiesCustomizer> determineHibernatePropertiesCustomiz
List<HibernatePropertiesCustomizer> customizers = new ArrayList<>();
if (ClassUtils.isPresent("org.hibernate.resource.beans.container.spi.BeanContainer",
getClass().getClassLoader())) {
customizers.add((properties) -> properties.put(AvailableSettings.BEAN_CONTAINER,
customizers.add((properties) -> properties.put(ManagedBeanSettings.BEAN_CONTAINER,
new SpringBeanContainer(beanFactory)));
}
if (physicalNamingStrategy != null || implicitNamingStrategy != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
import java.util.function.Supplier;

import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.MappingSettings;
import org.hibernate.cfg.PersistenceSettings;
import org.hibernate.cfg.SchemaToolingSettings;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
Expand Down Expand Up @@ -86,10 +88,10 @@ private Map<String, Object> getAdditionalProperties(Map<String, String> existing
getNaming().applyNamingStrategies(result);
String ddlAuto = determineDdlAuto(existing, settings::getDdlAuto);
if (StringUtils.hasText(ddlAuto) && !"none".equals(ddlAuto)) {
result.put(AvailableSettings.HBM2DDL_AUTO, ddlAuto);
result.put(SchemaToolingSettings.HBM2DDL_AUTO, ddlAuto);
}
else {
result.remove(AvailableSettings.HBM2DDL_AUTO);
result.remove(SchemaToolingSettings.HBM2DDL_AUTO);
}
Collection<HibernatePropertiesCustomizer> customizers = settings.getHibernatePropertiesCustomizers();
if (!ObjectUtils.isEmpty(customizers)) {
Expand All @@ -99,20 +101,20 @@ private Map<String, Object> getAdditionalProperties(Map<String, String> existing
}

private void applyScanner(Map<String, Object> result) {
if (!result.containsKey(AvailableSettings.SCANNER) && ClassUtils.isPresent(DISABLED_SCANNER_CLASS, null)) {
result.put(AvailableSettings.SCANNER, DISABLED_SCANNER_CLASS);
if (!result.containsKey(PersistenceSettings.SCANNER) && ClassUtils.isPresent(DISABLED_SCANNER_CLASS, null)) {
result.put(PersistenceSettings.SCANNER, DISABLED_SCANNER_CLASS);
}
}

private String determineDdlAuto(Map<String, String> existing, Supplier<String> defaultDdlAuto) {
String ddlAuto = existing.get(AvailableSettings.HBM2DDL_AUTO);
String ddlAuto = existing.get(SchemaToolingSettings.HBM2DDL_AUTO);
if (ddlAuto != null) {
return ddlAuto;
}
if (this.ddlAuto != null) {
return this.ddlAuto;
}
if (existing.get(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION) != null) {
if (existing.get(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION) != null) {
return null;
}
return defaultDdlAuto.get();
Expand Down Expand Up @@ -147,9 +149,9 @@ public void setPhysicalStrategy(String physicalStrategy) {
}

private void applyNamingStrategies(Map<String, Object> properties) {
applyNamingStrategy(properties, AvailableSettings.IMPLICIT_NAMING_STRATEGY, this.implicitStrategy,
applyNamingStrategy(properties, MappingSettings.IMPLICIT_NAMING_STRATEGY, this.implicitStrategy,
SpringImplicitNamingStrategy.class::getName);
applyNamingStrategy(properties, AvailableSettings.PHYSICAL_NAMING_STRATEGY, this.physicalStrategy,
applyNamingStrategy(properties, MappingSettings.PHYSICAL_NAMING_STRATEGY, this.physicalStrategy,
CamelCaseToUnderscoresNamingStrategy.class::getName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,20 @@ private OAuth2TokenValidator<Jwt> getValidators(OAuth2TokenValidator<Jwt> defaul
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(defaultValidator);
if (!CollectionUtils.isEmpty(audiences)) {
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
validators.add(audValidator(audiences));
}
validators.addAll(this.additionalValidators);
return new DelegatingOAuth2TokenValidator<>(validators);
}

private JwtClaimValidator<List<String>> audValidator(List<String> audiences) {
return new JwtClaimValidator<>(JwtClaimNames.AUD, (aud) -> nullSafeDisjoint(aud, audiences));
}

private boolean nullSafeDisjoint(List<String> c1, List<String> c2) {
return c1 != null && !Collections.disjoint(c1, c2);
}

@Bean
@Conditional(KeyValueCondition.class)
NimbusReactiveJwtDecoder jwtDecoderByPublicKeyValue() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,20 @@ private OAuth2TokenValidator<Jwt> getValidators(OAuth2TokenValidator<Jwt> defaul
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(defaultValidator);
if (!CollectionUtils.isEmpty(audiences)) {
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
(aud) -> aud != null && !Collections.disjoint(aud, audiences)));
validators.add(audValidator(audiences));
}
validators.addAll(this.additionalValidators);
return new DelegatingOAuth2TokenValidator<>(validators);
}

private JwtClaimValidator<List<String>> audValidator(List<String> audiences) {
return new JwtClaimValidator<>(JwtClaimNames.AUD, (aud) -> nullSafeDisjoint(aud, audiences));
}

private boolean nullSafeDisjoint(List<String> c1, List<String> c2) {
return c1 != null && !Collections.disjoint(c1, c2);
}

@Bean
@Conditional(KeyValueCondition.class)
JwtDecoder jwtDecoderByPublicKeyValue() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ void renderTemplate() throws Exception {
MarkupTemplateEngine engine = config.getTemplateEngine();
Writer writer = new StringWriter();
engine.createTemplate(new ClassPathResource("templates/message.tpl").getFile())
.make(new HashMap<String, Object>(Collections.singletonMap("greeting", "Hello World")))
.make(new HashMap<>(Collections.singletonMap("greeting", "Hello World")))
.writeTo(writer);
assertThat(writer.toString()).contains("Hello World");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import java.util.function.Supplier;

import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.MappingSettings;
import org.hibernate.cfg.PersistenceSettings;
import org.hibernate.cfg.SchemaToolingSettings;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
Expand Down Expand Up @@ -59,9 +61,9 @@ class HibernatePropertiesTests {
void noCustomNamingStrategy() {
this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> {
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
assertThat(hibernateProperties).containsEntry(AvailableSettings.PHYSICAL_NAMING_STRATEGY,
assertThat(hibernateProperties).containsEntry(MappingSettings.PHYSICAL_NAMING_STRATEGY,
CamelCaseToUnderscoresNamingStrategy.class.getName());
assertThat(hibernateProperties).containsEntry(AvailableSettings.IMPLICIT_NAMING_STRATEGY,
assertThat(hibernateProperties).containsEntry(MappingSettings.IMPLICIT_NAMING_STRATEGY,
SpringImplicitNamingStrategy.class.getName());
}));
}
Expand All @@ -73,8 +75,8 @@ void hibernate5CustomNamingStrategies() {
"spring.jpa.hibernate.naming.physical-strategy:com.example.Physical")
.run(assertHibernateProperties((hibernateProperties) -> {
assertThat(hibernateProperties).contains(
entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"),
entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical"));
entry(MappingSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"),
entry(MappingSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical"));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
}));
}
Expand All @@ -87,24 +89,24 @@ void hibernate5CustomNamingStrategiesViaJpaProperties() {
.run(assertHibernateProperties((hibernateProperties) -> {
// You can override them as we don't provide any default
assertThat(hibernateProperties).contains(
entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"),
entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical"));
entry(MappingSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"),
entry(MappingSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical"));
assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy");
}));
}

@Test
void scannerUsesDisabledScannerByDefault() {
this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties)
.containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner")));
.containsEntry(PersistenceSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner")));
}

@Test
void scannerCanBeCustomized() {
this.contextRunner.withPropertyValues(
"spring.jpa.properties.hibernate.archive.scanner:org.hibernate.boot.archive.scan.internal.StandardScanner")
.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties)
.containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner")));
.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties).containsEntry(
PersistenceSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner")));
}

@Test
Expand All @@ -125,16 +127,16 @@ void defaultDdlAutoIsNotInvokedAndDdlAutoIsNotSetIfJpaDbActionPropertyIsSet() {
.withPropertyValues(
"spring.jpa.properties.jakarta.persistence.schema-generation.database.action=drop-and-create")
.run(assertHibernateProperties((hibernateProperties) -> {
assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO);
assertThat(hibernateProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION,
assertThat(hibernateProperties).doesNotContainKey(SchemaToolingSettings.HBM2DDL_AUTO);
assertThat(hibernateProperties).containsEntry(SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION,
"drop-and-create");
then(this.ddlAutoSupplier).should(never()).get();
}));
}

private ContextConsumer<AssertableApplicationContext> assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) {
return assertHibernateProperties((hibernateProperties) -> {
assertThat(hibernateProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, expectedDdlAuto);
assertThat(hibernateProperties).containsEntry(SchemaToolingSettings.HBM2DDL_AUTO, expectedDdlAuto);
then(this.ddlAutoSupplier).should(never()).get();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
import org.assertj.core.api.MapAssert;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
import org.mockito.Mockito;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.TestConfiguration;
Expand Down Expand Up @@ -143,7 +143,7 @@ void whenHasUserDefinedFailoverPropertiesAddsToClient() {
.getField(clientFactory, "customizer");
customizeAction.accept(pulsarClientBuilderCustomizer, target);
InOrder ordered = inOrder(target);
ordered.verify(target).serviceUrlProvider(Mockito.any(AutoClusterFailover.class));
ordered.verify(target).serviceUrlProvider(ArgumentMatchers.any(AutoClusterFailover.class));
assertThat(pulsarProperties.getClient().getFailover().getDelay()).isEqualTo(Duration.ofSeconds(15));
assertThat(pulsarProperties.getClient().getFailover().getSwitchBackDelay())
.isEqualTo(Duration.ofSeconds(30));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ void wrapLocalValidatorFactoryBean() {
this.contextRunner.withUserConfiguration(LocalValidatorFactoryBeanConfig.class).run((context) -> {
ValidatorAdapter wrapper = context.getBean(ValidatorAdapter.class);
assertThat(wrapper.supports(SampleData.class)).isTrue();
MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(), "test");
MapBindingResult errors = new MapBindingResult(new HashMap<>(), "test");
wrapper.validate(new SampleData(40), errors);
assertThat(errors.getErrorCount()).isOne();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ private static BeanDefinition getOrAddBeanDefinition(BeanDefinitionRegistry regi
RootBeanDefinition definition = new RootBeanDefinition(postProcessor);
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<MockDefinition>());
constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<>());
registry.registerBeanDefinition(BEAN_NAME, definition);
return definition;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,13 @@ void deleteHandlesRelativeUris() throws IOException {
@Test
void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), String.class));
.exchange(new RequestEntity<>(HttpMethod.GET, relativeUri), String.class));
}

@Test
void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), new ParameterizedTypeReference<String>() {
.exchange(new RequestEntity<>(HttpMethod.GET, relativeUri), new ParameterizedTypeReference<String>() {
}));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public StringSequence subSequence(int start, int end) {
* Returns {@code true} if the sequence is empty. Public to be compatible with JDK 15.
* @return {@code true} if {@link #length()} is {@code 0}, otherwise {@code false}
*/
@Override
public boolean isEmpty() {
return length() == 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ private void registerServletContainerInitializerToDriveServletContextInitializer
ServletContextInitializer[] mergedInitializers = mergeInitializers(initializers);
Initializer initializer = new Initializer(mergedInitializers);
deployment.addServletContainerInitializer(new ServletContainerInitializerInfo(Initializer.class,
new ImmediateInstanceFactory<ServletContainerInitializer>(initializer), NO_CLASSES));
new ImmediateInstanceFactory<>(initializer), NO_CLASSES));
}

private ClassLoader getServletClassLoader() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ void addServletRegistrationBeanMustNotBeNull() {
void setServletRegistrationBeanReplacesValue() throws Exception {
given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration);
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean(mockServletRegistration("a"));
bean.setServletRegistrationBeans(
new LinkedHashSet<ServletRegistrationBean<?>>(Collections.singletonList(mockServletRegistration("b"))));
bean.setServletRegistrationBeans(new LinkedHashSet<>(Collections.singletonList(mockServletRegistration("b"))));
bean.onStartup(this.servletContext);
then(this.registration).should().addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), false, "b");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ void testHome() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
.exchange("/", HttpMethod.GET, new HttpEntity<>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("<title>Hello");
}
Expand All @@ -74,7 +74,7 @@ void testError() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.exchange("/error", HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
.exchange("/error", HttpMethod.GET, new HttpEntity<>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(entity.getBody()).contains("<html>")
.contains("<body>")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class SampleServletApplicationTests {
void testHomeIsSecure() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers),
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>(headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class SampleMethodSecurityApplicationTests {
void testHome() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers),
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>(headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
Expand Down Expand Up @@ -87,7 +87,7 @@ void testDenied() {
String cookie = entity.getHeaders().getFirst("Set-Cookie");
headers.set("Cookie", cookie);
ResponseEntity<String> page = this.restTemplate.exchange(entity.getHeaders().getLocation(), HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
new HttpEntity<>(headers), String.class);
assertThat(page.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(page.getBody()).contains("Access denied");
}
Expand All @@ -97,7 +97,7 @@ void testManagementProtected() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
ResponseEntity<String> entity = this.restTemplate.exchange("/actuator/beans", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
new HttpEntity<>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class SampleWebSecureCustomApplicationTests {
void testHome() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<Void>(headers),
ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, new HttpEntity<>(headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
assertThat(entity.getHeaders().getLocation().toString()).endsWith(this.port + "/login");
Expand All @@ -65,8 +65,8 @@ void testHome() {
void testLoginPage() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET,
new HttpEntity<Void>(headers), String.class);
ResponseEntity<String> entity = this.restTemplate.exchange("/login", HttpMethod.GET, new HttpEntity<>(headers),
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("<title>Login</title>");
}
Expand Down
Loading

0 comments on commit 9e7972a

Please sign in to comment.