โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Select parent and only some fields from child in @OneToMany relationships using JPA and Criteria Builder

Implemented one to many relationship and select parent and child I have a onetomany relationship. Using criteria builder, i need to get parent and all related childs but selecting only some fields from each child.

@Entity
@Table(name="transaction_status")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TransactionStatus implements Serializable {
@Id
@Column(name = "id")
@JsonProperty("id")
public String id;

@SerializedName("status")
public String status;

@Column(name="lastUpdatedDate")
@JsonProperty("lastUpdatedDate")
@SerializedName("lastUpdatedDate")
private Date lastUpdatedDate;

@JsonProperty("generatedAt")
@SerializedName("generatedAt")
@JsonIgnore
private Date generatedAt;

@JsonProperty("invoices")
@SerializedName("invoices")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="transactionstatusId",referencedColumnName = "xmlFilename")
private List<InvoiceTransaction> invoiceTransactions = new ArrayList<>();

}

@Entity
@Table(name="invoice_transaction")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

public class InvoiceTransaction implements Serializable {
    @Column(name = "status", nullable = false)
    @JsonProperty("status")
    @SerializedName("status")
    private String status;
    @Column(name = "originalStatus", nullable = false)
    @JsonProperty("originalStatus")
    @SerializedName("originalStatus")
    private String originalStatus;
    
    @Column(name = "errorMessage")
    @JsonProperty("errorMessage")
    @SerializedName("errorMessage")
    private String errorMessage;

    @Column(name = "generatedAt" )
    @JsonProperty("generatedAt")
    @SerializedName("generatedAt")
    private Date generatedAt;
}

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransactionStatus> cq = builder.createQuery(TransactionStatus.class);
Root<TransactionStatus> rootTrnStatus = cq.from(TransactionStatus.class);
List<TransactionStatus> resultList = entityManager.createQuery(cq).getResultList();

this implementation, gives me list of Transactionstatus objetc with list of its childs. what im seraching to get is: list of Transactionstatus object with list of its childs with olny status and errorMessage fileds. How can i get this result using Crtiteria builder? thank you

Application.properties boolean defined value not used in bean

I have a bean class that I want to load a boolean value that is defined in the application.properties file of a springboot app. This is my application.properties file:

APP_CONTAINERIZED_VALUE=true

My class is annotated as @Component and uses this value like so:

@Value("${APP_CONTAINERIZED_VALUE:false}")
private boolean APP_CONTAINERIZED;

When I try yo run the spring server I get this exception:

Caused by: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'APP_CONTAINERIZED_VALUE' in value "${APP_CONTAINERIZED_VALUE}"

Am I doing anything wrong? I have checked other similar posts but nothing seems to work for me.

Thanks in advance

How to use BycrpytEncoder without springsecurity?

So previously i was using bcrpytEncoder / passwordEncoder in the springboot to register the user with the encrypted password in the JPA like this :

import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class PasswordEncoderUtil {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

then i configure the springsecurity in my application using other dependencies :


    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
//  implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5'
//  implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web-services'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'

Now i want to remove springsecurity from the application and only want to use PasswordEncoder ,how should i do it ?

I don't want this login page : Login Page

Problem with automate refresh Azure App Configuration with Spring Boot and enabled global method security

I have a Spring Boot (2.6.6) application which is connected to the Azure App Configuration. I also use the automated refresh mechanisms from the Azure App Configuration, which works fine - I change a value in Azure App Configuration and also update the sentinel value, then the application detects the changes and update the bean values (properties) by calling the setter methods without restarting the application.

But after I added a class with @EnableGlobalMethodSecurity(prePostEnabled = true), then the refresh mechanisms is not working anymore. Only during startup, the values are set, then never again. I see in the log that the application detects the changes, but never calls the setter of the bean to update the values.

How can I solve this problem to have the automated refresh mechanisms and the PreAuthorize working together?

MethodSecurityConfiguration.class:

@Configuration
@AllArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
...
}



ConfigurationProperties.class:

public interface AppConfigurationProperties {

    void setExample(String example);

    String getExample();
}



AzureAppConfigurationProperties.class:

@Configuration
@ConfigurationProperties(prefix = "config")
public class AzureAppConfigurationProperties implements AppConfigurationProperties {

    private String example;

    @Override
    public void setExample(String example) {
        this.example = example;
    }

    @Override
    public String getExample() {
        return this.example;
    }
}

Spring boot upgrade from 3.1.9 to 3.2.3 Caused by: java.lang.IllegalArgumentException: authenticationManager cannot be null

I am upgrading my spring boot project from 3.1.9 to 3.2.3, I am getting error while running the tests. Found that below line of code is causing the issue. httpsecurity.anonymous(AbstractHttpConfigurer::disable)

Below is the exception stack trace

[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.test.AuthenticationPropertiesTest
                                                                                                                            
OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
2024-04-24T10:41:55.505+05:30  INFO 24448 --- [           main] org.ehcache.core.EhcacheManager          : Cache 'authenticationCache' created in EhcacheManager.
10:41:56.565 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'filterChain' defined in class path resource [com/sample/WebSecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: authenticationManager cannot be null
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:895) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:848) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:508) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1419) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:959) ~[spring-context-6.1.4.jar:6.1.4]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624) ~[spring-context-6.1.4.jar:6.1.4]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.2.3.jar:3.2.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.2.3.jar:3.2.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:334) ~[spring-boot-3.2.3.jar:3.2.3]
    at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) ~[spring-boot-test-3.2.3.jar:3.2.3]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) ~[spring-core-6.1.4.jar:6.1.4]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) ~[spring-core-6.1.4.jar:6.1.4]
    at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1454) ~[spring-boot-3.2.3.jar:3.2.3]
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:553) ~[spring-boot-test-3.2.3.jar:3.2.3]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) ~[spring-boot-test-3.2.3.jar:3.2.3]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) ~[spring-boot-test-3.2.3.jar:3.2.3]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260) ~[spring-test-6.1.4.jar:6.1.4]
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:163) ~[spring-test-6.1.4.jar:6.1.4]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:378) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:383) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:378) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[?:?]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[?:?]
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[?:?]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[?:?]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[?:?]
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) ~[?:?]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) ~[?:?]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) ~[?:?]
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[?:?]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:290) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:289) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:279) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at java.util.Optional.orElseGet(Optional.java:364) ~[?:?]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:278) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69) ~[junit-jupiter-engine-5.10.2.jar:5.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at java.util.ArrayList.forEach(ArrayList.java:1511) ~[?:?]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at java.util.ArrayList.forEach(ArrayList.java:1511) ~[?:?]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:198) ~[junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:169) ~[junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:93) ~[junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:58) ~[junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:141) [junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:57) [junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:103) [junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:85) [junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.junit.platform.launcher.core.DelegatingLauncher.execute(DelegatingLauncher.java:47) [junit-platform-launcher-1.10.2.jar:1.10.2]
    at org.apache.maven.surefire.junitplatform.LazyLauncher.execute(LazyLauncher.java:56) [surefire-junit-platform-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.execute(JUnitPlatformProvider.java:184) [surefire-junit-platform-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:148) [surefire-junit-platform-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:122) [surefire-junit-platform-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:385) [surefire-booter-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162) [surefire-booter-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:507) [surefire-booter-3.1.2.jar:3.1.2]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:495) [surefire-booter-3.1.2.jar:3.1.2]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filterChain' defined in class path resource [com/sample/WebSecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: authenticationManager cannot be null
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:639) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1335) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1165) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1689) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1653) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1543) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1511) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1392) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:887) ~[spring-beans-6.1.4.jar:6.1.4]
    ... 98 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: authenticationManager cannot be null
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:177) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:647) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:639) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1335) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1165) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1689) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1653) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1543) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1511) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1392) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:887) ~[spring-beans-6.1.4.jar:6.1.4]
    ... 98 more
Caused by: java.lang.IllegalArgumentException: authenticationManager cannot be null
    at org.springframework.util.Assert.notNull(Assert.java:172) ~[spring-core-6.1.4.jar:6.1.4]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.<init>(BasicAuthenticationFilter.java:135) ~[spring-security-web-6.2.2.jar:6.2.2]
    at org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer.configure(HttpBasicConfigurer.java:211) ~[spring-security-config-6.2.2.jar:6.2.2]
    at org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer.configure(HttpBasicConfigurer.java:83) ~[spring-security-config-6.2.2.jar:6.2.2]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure(AbstractConfiguredSecurityBuilder.java:376) ~[spring-security-config-6.2.2.jar:6.2.2]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:330) ~[spring-security-config-6.2.2.jar:6.2.2]
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:38) ~[spring-security-config-6.2.2.jar:6.2.2]
    at com.sample.WebSecurityConfig.filterChain(WebSecurityConfig.java:85) ~[classes/:?]
    at com.sample.WebSecurityConfig$$SpringCGLIB$$0.CGLIB$filterChain$0(<generated>) ~[classes/:?]
    at com.sample.WebSecurityConfig$$SpringCGLIB$$FastClass$$1.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258) ~[spring-core-6.1.4.jar:6.1.4]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-6.1.4.jar:6.1.4]
    at com.sample.audit.WebSecurityConfig$$SpringCGLIB$$0.filterChain(<generated>) ~[classes/:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:140) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:647) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:639) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1335) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1165) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1689) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1653) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1543) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1511) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1392) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.4.jar:6.1.4]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:887) ~[spring-beans-6.1.4.jar:6.1.4]
    ... 98 more

And SecurityFilterChain configuration as below

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.securityContext(a->a.requireExplicitSave(false))
               .authorizeHttpRequests(a->a.dispatcherTypeMatchers(DispatcherType.ERROR, DispatcherType.FORWARD).permitAll());
        http.csrf(AbstractHttpConfigurer::disable).sessionManagement(a->a.sessionCreationPolicy(SessionCreationPolicy.ALWAYS));
        http.authorizeHttpRequests(a->a.requestMatchers(HttpMethod.GET, "/**").hasAnyAuthority(getAppPermissions())
                .requestMatchers(HttpMethod.PUT, "/**").hasAnyAuthority(getAppPermissions())
                .anyRequest().denyAll())
                .anonymous(AbstractHttpConfigurer::disable)
                .exceptionHandling(b->b.accessDeniedPage("/unauthorized"));
        http.httpBasic(a->a.authenticationEntryPoint(authenticationEntryPoint));
        http.headers(a->a.addHeaderWriter(new StaticHeadersWriter("Content-Security-Policy",getContentSecurityPolicy())));
       
        return http.build();
    }

From the above code if I comment .anonymous(AbstractHttpConfigurer::disable) the build is successful, Please let me know if I am missing anything as commenting it is not a solution for me.

Spring boot embedded Tomcat; how to set CertificateKeystoreFile

We are using Spring Boot 3.2.3 with embedded Tomcat 10.1.19.

We set SSL Bundle configuration

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.ssl.jks

server.ssl.bundle=web-server
spring.ssl.bundle.jks.web-server.key.alias=ourAlias
spring.ssl.bundle.jks.web-server.key.password=thepassword
spring.ssl.bundle.jks.web-server.keystore.location=the/path/to/jks/file
spring.ssl.bundle.jks.web-server.keystore.password=thepassword

In org.springframework.boot.web.embedded.tomcat.SslConnectorCustomizer#applySslBundle

private void applySslBundle(SslBundle sslBundle, AbstractHttp11JsseProtocol<?> protocol, SSLHostConfig sslHostConfig) {
...
    certificate.setCertificateKeystorePassword(keystorePassword);
    if (key.getPassword() != null) {
        certificate.setCertificateKeyPassword(key.getPassword());
    }

    if (key.getAlias() != null) {
        certificate.setCertificateKeyAlias(key.getAlias());
    }
...
}

We see calls to org.apache.tomcat.util.net.SSLHostConfigCertificate#setCertificateKeyAlias and org.apache.tomcat.util.net.SSLHostConfigCertificate#setCertificateKeyPassword

but we don't see any call to org.apache.tomcat.util.net.SSLHostConfigCertificate#setCertificateKeystoreFile

How do we set a value to org.apache.tomcat.util.net.SSLHostConfigCertificate#certificateKeystoreFile?

How to solve the error of Spring content-type = utf8?

"org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/json;charset=UTF-8' is not supported\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:213)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:159)\r\n

I tried by giving @JsonManagedReference and @JsonBackReference annotations

Dependency injection in JavaFX application with Spring Boot

How do I properly use dependency injection in a Spring Boot application?

My software has a JavaFX main window and multiple sub-dialogs that are opened and closed from the main window. I need to use REST clients in the sub-dialogs that are injected by Spring Boot. However, each client instance requires a constructor parameter for initialization.

So I end up with a multitude of REST clients in my main window's controller that are then passed down to the controllers of the sub-dialogs. Is there any better way to implement this to get rid of all the constructor parameters?

@Component
@Scope("prototype")
public class MainController {

  private final FirstClient first;
  private final SecondClient second;
  private final ThirdClient third;

  @Autowired
  public MainController(FirstClient first, SecondClient second, ThirdClient third) {
    this.first = first;
    this.second = second;
    this.third = third;
  }

  private void openSubDialog() {
    // ...
    SubController subController = new SubController(first, second);
    // ...
  }

  private void openAnotherSubDialog() {
    // ...
    AnotherSubController anotherSubController = new AnotherSubController(first, third);
    // ...
  }

}

My controller classes are annotated with @Component and @Scope("prototype").

@Component
@Scope("prototype")
public class SubController {

  private final FirstClient first;
  private final SecondClient second;

  @Autowired
  public SubController(FirstClient first, SecondClient second) {
    this.first = first;
    this.second = second;
  }

  private void doSomething() {
    var result = first.callSomeService();
  }

}

And finally, my REST clients look somewhat like this:

@Service
public class FirstClient {

  public SomeType callSomeService() {
    return restClient.getSomeData();
  }

}

I'm looking for a way to directly inject the REST clients in the controllers of the sub-dialogs without the need to add constructor parameters and pass them down from the main view. In pseudo-code, something like this:

@Component
@Scope("prototype")
public class ImprovedController {

  @InjectHereDirectly
  private final FirstClient first;

  @InjectHereDirectly
  private final SecondClient second;

  // No constructor needed

  private void doSomething() {
    var result = first.callSomeService();
  }

}

Best way of modeling nutrition facts in Product Entity

I'm developing an e-commerce website where I need to manage different products with varying nutrition facts. I've structured my Product and NutritionFacts entities as follows:

@Entity
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Table(name = "product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "product_id", updatable = false, nullable = false)
    private Long id;

    private String name;

    private String title;

    private String imageUrl;

    @OneToMany(mappedBy = "product",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonManagedReference
    private List<NutritionFacts> NutritionFacts;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "category_id")
    private Category category;

    private int price;

    @ElementCollection
    private List<String> flavors;

    @ElementCollection
    private List<String> ingredients;

    private int weight;

    @Column(name = "serving_amount")
    private int servingAmount;

    private int quantity;

    private String description;

    private String usageDescription;
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Table(name = "nutrition_facts")
public class NutritionFacts {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "nutrition_fact_id", updatable = false, nullable = false)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "product_id")
    @JsonBackReference
    private Product product;

    private String nutrientName;
    private double amount;
}

However, I'm uncertain about the best approach for managing nutrition facts. Some products have a standard set of nutrition facts (e.g., protein powder), while others may not have any (e.g., accessories) nutrition facts or other products may have some unique nutrition facts(e.g., vitamins)

My question is

Is it a good practice to maintain nutrition facts in a separate entity linked to the Product entity through a one-to-many relationship or alternatively, would it be better to just implement like below?

@ElementCollection
private List<List<String>> nutritionFacts;

Any insights or suggestions on the most efficient and scalable way to model this aspect of my e-commerce application would be greatly appreciated.

At the end I want to create products with just one json request like below

{ "name": "Protein Powder", "flavors": ["Chocolate", "Vanilla"], "ingredients": ["Whey Protein Concentrate", "Whey Protein Isolate"] ... "nutritionFacts": { "Energy": 120, "Protein": 24, "Carbohydrates": 3, ... } }

Is it possible to avoid Tomcat related folders being created in /tmp at all?

I've recently tried to set my Spring Boot container FS as read-only but it would complain that it can't write some folders as /tmp/tomcat.8080.7493782654123481360/work/Tomcat/localhost/ROOT, and also with 8081 instead of 8080.

I've read that this is due to POST body content being stored in there, and also if the app allows multipart uploads those will end up there too. All this folders that get created overtime are empty as far as I've seen.

In order to make the FS read-only I would like to disable the creation of those folders. Is that possible?

I've already tried with:

spring.servlet.multipart.enabled = false
server.tomcat.access-log-enabled = false

But they are still being created.

OptaPlanner: Issue Optimizing Vehicle Routing by Passing Problem as a Parameter

I am working on optimizing a vehicle routing problem using OptaPlanner in Spring Boot, and I've encountered a challenge when attempting to pass my problem instance as a parameter(the parameter contains demo data) to the solve method. Unfortunately, the optimization process is not yielding the expected result and throws "java.lang.IllegalArgumentException: The solutionClass (class org.acme.vehiclerouting.domain.VehicleRoutingSolution)'s entityCollectionProperty (field private java.util.List org.acme.vehiclerouting.domain.VehicleRoutingSolution.vehicleList) should never return null".

Here's a detailed summary of the issue: Objective: I aim to optimize a vehicle routing problem by passing my problem instance as a parameter to the solve method in OptaPlanner.

Issue Faced: Despite passing the problem instance, the optimization process is not producing the desired result. The solution does not reflect the expected improvements in the vehicle routing.

Expectation: I expect the solve method to optimize the vehicle routing problem based on the provided problem instance, producing an improved solution.

  • I have Verified the contents of the solver configuration XML file (optaplanerConfig.xml) to ensure it accurately represents the problem requirements.
  • Confirmed the presence of appropriate and elements in the configuration.
  • Reviewed scoring rules and constraints to ensure they accurately represent the business rules of the vehicle routing problem.
  • Temporarily simplified scoring rules to identify whether they might be causing the issue.
  • Confirmed that the solver termination conditions in the element are appropriate for the problem.
  • Adjusted termination conditions based on the problem requirements.
  • Enabled debug logging in OptaPlanner to gain more insights into the optimization process.

JobRunr: Disable NoSQL Storage Configuration

I am using the jobrunr-spring-boot-3-starter, version 7.0.0-RC.1, and have a PostgreSQL database set up - which is picked up as the default storage provider by JobRunr.

Now, I have added a Redis integration (via Lettuce), and JobRunr has started picking it up as the default storage, which I don't want.

I haven't applied any custom configuration to JobRunr. What is the best approach to force JobRunr to stick with the PostgreSQL datasource?

Validation failed for query for method public abstract util.List

I am new to Spring Data JPA, so I am having a trouble writing queries. I want to get all actors that had role in a certain movie that I get from movieID.

When trying this, I get error while trying to start :

Validation failed for query for method public abstract java.util.List

@Repository
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {

    @Query(value = "select distinct r.actor from RoleEntity r " +
            "where r.movie.movieID = ?1")
    List<ActorEntity> findByMovieID(Long movieID);

}

Here are my entities:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "roles")
public class RoleEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long roleID;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "actor_id", referencedColumnName = "id")
    private ActorEntity actor;

    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    @JoinColumn(name = "movie_id", referencedColumnName = "id")
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private MovieEntity movie;

    private String roleName;

}
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name="actor")
public class ActorEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long actorID;

    @NotEmpty
    private String firstName;

    @NotEmpty
    private String lastName;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    @OneToMany(mappedBy = "actor", cascade = CascadeType.ALL)
    @JsonBackReference
    private Set<RoleEntity> roles = new HashSet<>();

}




@Getter
@Setter
@ToString
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "movie")
public class MovieEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long movieID;

    @NotEmpty
    private String name;

    @NotEmpty
    private String description;

    @NotEmpty
    private String duration;

    @NotNull
    private LocalDate startTime;

    private LocalDate endTime;

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<RoleEntity> roles = new HashSet<>();

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<ProjectEntity> projects = new HashSet<>();

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "movie_genres",
            joinColumns = @JoinColumn(name = "movie_id"),
            inverseJoinColumns = @JoinColumn(name = "genre_id"))
    private Set<GenreEntity> genres;

}

I tried using native query, but it says it returns Long?!

@Query(value = "select a.id, a.first_name, a.last_name, a.gender " +
        "from actor a " +
        "join roles r on r.actor_id = a.id " +
        "where r.movie_id = ?1", nativeQuery = true)
List<ActorEntity> findByMovieID(Long movieID);

Thank you very much in advance!!! :D

Different context path for local and dev env using springdoc open api3

I am using spring boot 3.2.3 and spring doc openAPI 3. I have just migrated from springboot 2.5 and sprignfox and facing these issues. My requirement is I want my apis to work seamlessly in local as well as higher environments for swagger. But its not happening as of now. Say the name of my application is 'abc', Below is what I am doing...

springdoc dependency:

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.5.0</version>
        </dependency>

application.properties:

springdoc.packagesToScan=com.abc.controller
springdoc.swagger-ui.use-root-path=false
springdoc.swagger-ui.path=/abc-swagger-ui.html
springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.enabled=true
springdoc.swagger-ui.url=/abc/v3/api-docs
springdoc.swagger-ui.configUrl=/abc/v3/api-docs/swagger-config

SwaggerConfig:

@Bean
    public OpenAPI api() {

        return new OpenAPI()
                .info(getApiInfo())
                .addSecurityItem(new SecurityRequirement().
                        addList("Bearer Authentication"))
                .components(new Components().addSecuritySchemes
                ("Bearer Authentication", createAPIKeyScheme()))
                .servers(Collections.singletonList(new Server().url("/"))); // line 1

    }

the above code works on local but not on dev environment

if I change 'line 1' as

.servers(Collections.singletonList(new Server().url("/abc"))); // line 1

then it works on dev but not on local.

Also I need to manually add /v3/api-docs in explorer bar to load the endpoints else I get the below error..

Failed to load remote configuration.

What am I missing in this configuration.

I was referring the official documentation of spring doc for this migration.

https://springdoc.org/

Mockito Junit test case for while loop with break statement

I am writing Junit test case(Junit 5 with jupitar) for existing code that has while loop with break statement.

public int deleteRecords(int batchsize) {
   //some code here 
   int totalDeletedRecords = 0;
   while(true) {
       int deleted = deleteRecord();
       if (deleted == 0) { //means no record found to delete
          break;
       }
       totalDeletedRecords += deleted;
   }
}
private int deleteRecord()  {
    List<User> usersList = repository.findAll();  //get the records from the database; 
    if (CollectUtils.isEmpty()) {
        return 0;
    }
    //then deleting the total records batch wise
    //construct list with ids and pass that to delete method
    repository.delete(List of ids);
    return userList.size();
}

My Junit test case,

@Test
public void testDeleteRecordSuccess() {
    //mock repository call
    User user = User.builder().name("xyz").build();
    when(repository.findAll()).thenReturn(Arrays.asList(user));
    doNothing().when(repository).delete(anyList());
    int deleted = service.deleteRecords(1000);
    assertEquals(1, deleted);
}

As per the mock, always record has size of 1 and loop executes infinite. The loop needs to stop and also all lines of code should coverage.

Let me know how to mock the repository call in such scenario's.

Aspects not working in spring boot application

I am creating a Spring boot application with Aspects, but it is not working. It is not getting picked up.

I have defined EnableAspectJAutoProxy in a custom configuration class.

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AppConfig {

@Bean
public ModelMapper modelMapper() {
    return new ModelMapper();
}

Going through multiple solutions on stack overflow, I found that adding @Component might solve my issue but when I add @Component, my application fails to start.

please find the error below-

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectingArgumentResolverBeanPostProcessor' defined in class path resource [org/springframework/data/web/config/ProjectingArgumentResolverRegistrar.class]: BeanPostProcessor before instantiation of bean failed at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:277) ~[spring-context-6.1.4.jar:6.1.4] at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:805) ~[spring-context-6.1.4.jar:6.1.4] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) ~[spring-context-6.1.4.jar:6.1.4] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.2.3.jar:3.2.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.2.3.jar:3.2.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.2.3.jar:3.2.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:334) ~[spring-boot-3.2.3.jar:3.2.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354) ~[spring-boot-3.2.3.jar:3.2.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-3.2.3.jar:3.2.3] at com.dimensions.inc.personalTrackerbank.PersonalTrackerbankApplication.main(PersonalTrackerbankApplication.java:10) ~[classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': warning no match for this type name: com.dimensions.inc.personalTrackerbank.bankInfoInterface [Xlint:invalidAbsoluteTypeName] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:607) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:409) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1335) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1165) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:91) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:111) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator.java:92) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:101) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:280) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1130) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1105) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:511) ~[spring-beans-6.1.4.jar:6.1.4] ... 14 common frames omitted Caused by: java.lang.IllegalArgumentException: warning no match for this type name: com.dimensions.inc.personalTrackerbank.bankInfoInterface [Xlint:invalidAbsoluteTypeName] at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:319) ~[aspectjweaver-1.9.21.jar:na] at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:223) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.aspectj.AspectJExpressionPointcut.obtainPointcutExpression(AspectJExpressionPointcut.java:194) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:173) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:233) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:295) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:327) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:128) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:97) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:78) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:366) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:318) ~[spring-aop-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:438) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1789) ~[spring-beans-6.1.4.jar:6.1.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600) ~[spring-beans-6.1.4.jar:6.1.4]

My code -

resource file -

@RestController
@RequestMapping("/data")
public class PtbBankResource {

     @GetMapping("/ret")
     @ValidateUser(headerName = "Authorization")
     public ResponseEntity<?> getCall()
     {
          return ResponseEntity.ok().body("data Successfull");
     }
}

custom annotation -

@Component
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValidateUser {    
    String headerName() default "";
}

Aspect class -

@Aspect
public class AuthAspect {

private static final Logger logger = LoggerFactory.getLogger(AuthAspect.class);

@Autowired
PtbUtils ptbUtils;

@Around(value = "execution(* *(..)) && @annotation(ValidateUser)")
public Object authValidation(ProceedingJoinPoint joinPoint, ValidateUser validateUser) throws Throwable
{
    logger.info("Inside authValidation class");

    String headerName = validateUser.headerName().isEmpty() ? HttpHeaders.AUTHORIZATION : validateUser.headerName();
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    logger.info("headerName = " + headerName);
    logger.info("request = " + request);
    String token = request.getHeader(headerName);
    logger.info("token = " + token);
    Boolean value = ptbUtils.validateJwtToken(token);
    System.out.println("value = " + value);
    return joinPoint.proceed();
}
โŒ
โŒ