How can I fix deployment problems in quarkus - quarkus

I am trying to migrate project from SpringBoot to Quarkus.
Currently deps in module looks like this (+ some vertx deps):
plugins {
id 'io.quarkus'
id 'org.kordamp.gradle.jandex' version '0.7.0'
}
dependencies {
compile 'io.quarkus:quarkus-vertx'
compile 'io.quarkus:quarkus-vertx-web'
compile enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
compile "io.quarkus:quarkus-spring-boot-properties:${quarkusPlatformVersion}"
compile 'io.quarkus:quarkus-spring-di'
compile 'io.quarkus:quarkus-spring-web'
implementation ("org.springframework.boot:spring-boot-starter-aop")
implementation ("org.springframework.boot:spring-boot-starter-webflux")
}
As far as I understand, there is no need replacing spring annotations (except #SpringBootApplication).
Other test projects worked just fine, but in this case quarkusDev task fails with error:
2020-10-15 18:56:26,745 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 15 deployment problems:
[1] Unsatisfied dependency for type com./.../.service.autoconfigure.MyProperties and qualifiers [#Default]
- java member: com./.../.http.tracing.MyService#<init>()
- declared on CLASS bean [types=[com./.../.http.tracing.MyService, java.lang.Object], qualifiers=[#Default, #Any], target=com./.../.http.tracing.MyService]
And so on. Some failed deps from adjacent modules, others from external libs.
At this point I don't understand what causes this error.
MyProperties:
package com./.../.core.service.autoconfigure;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.HashMap;
import java.util.Map;
#Data
#ConfigurationProperties("grpc.client")
#ToString
public class MyProperties {
private boolean abortOnCallCancel = false;
private Map<String, ClientSettings> settings = new HashMap<>();
private Long dynamicChannelCacheSize = 1000L;
public ClientSettings getDefaultSettings() {
return settings.get(ClientSettings.DEFAULT_KEY);
}
#Data
public static class ClientSettings {
public static final String DEFAULT_KEY = "default";
private String hostname;
private int port;
private Long timeout;
private Map<String, Object> serviceConfig = new HashMap<>();
}
}

Related

Autowire Bean and application.yml file in another jar file

I am experimenting with spring boot multi module projects for my understanding.
My Over All Goal is :
1.Build Spring boot project as independent jar and utilise it on another project.
2.Autowire Bean properties inside jar as per new project. Make it independent.
Things I have done so far.
Project providerModule1
Declare a Service(MyService).
#Component
public class MyService {
#Autowired
ServiceProperties serviceProperties;
public String getInfoFromProperties() {
return serviceProperties.toString();
}
}
Create a bean called ServiceProperties that will be used in to MyService.
package com.demo.multimodule.providerModule1.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.Data;
#Component
#Data
public class ServiceProperties {
#Value("${default.userName}")
private String name;
#Value("${default.email}")
private String email;
#Value("${default.age}")
private String age;
}
Load the bean ServiceProperties by reading propeties from yml file.
default:
userName: userName1
email: default#email.com
age: 18
Build the Project ProviderModule1 using maven plugin
Project ParentProjectApplication
5. Load the maven dependency.
<dependency>
<groupId>com.demo.multimodule</groupId>
<artifactId>providerModule1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<classifier>app-to-import</classifier>
</dependency>
Autowire the MyService from project providerModule1
package com.multimodule.demo.parentProject.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.multimodule.providerModule1.service.MyService;
#Service
public class HomeService {
#Autowired
private MyService myService;
public String getHomeInfo() {
return "Home Info from Home service : "+myService.getInfoFromProperties();
}
}
Initially myservice was not getting loaded .Hence I added this step to main application class:
#SpringBootApplication(scanBasePackages= {"com.demo.multimodule.providerModule1.service",
"com.demo.multimodule.providerModule1.util"})
public class ParentProjectApplication {
}
Question 1 : Is this the only way using which I can autowire bean from a jar. If there is another way let me know.
I executed the Project ParentProjectApplication and it seem to work as expected.
Question 2 : Is it possible to autowire new yml property from Project ParentProjectApplication and make ServiceProperties bean of project ProviderModule1 utilise it.
you can try spring.factory to create beans.
refer the link below
https://docs.spring.io/spring-boot/docs/2.0.0.M3/reference/html/boot-features-developing-auto-configuration.html

What causes "Unsatisfied dependency expressed through method 'setTargetDatastore' parameter 0"?

I'm a complete novice regarding Spring applications, and I'm trying to integrate a project using Kotlin + Spring + GORM (Which requires usage of Groovy). When I try to run it I get:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'messageController': Unsatisfied dependency expressed through method 'setTargetDatastore' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException
I have just 5 files in the project, including the build.gradle.
Message.groovy
import grails.gorm.annotation.Entity
import groovy.transform.ToString
import org.grails.datastore.gorm.GormEntity
#ToString
#Entity
class Message implements GormEntity<Message> {
String user;
String date;
String message;
}
Message.service
import domain.Message
import groovy.transform.CompileStatic
import org.springframework.stereotype.Service
#CompileStatic
#grails.gorm.services.Service(Message)
#Service
interface MessageService {
List<Message> findAll()
}
MessageController.groovy
#RestController
#Transactional
class MessageController {
#Autowired
MessageService messageService
#RequestMapping("/")
List<String> index() {
return messageService.findAll().collect { "[" + it.user + "#" + it.date + ": " + it.message + "]" }
}
#RequestMapping(value = "/save/", method = RequestMethod.POST)
String save(#RequestBody Message message) {
message.save()
return "Saved"
}
}
App.kt
#SpringBootApplication
class SimManagerApplication
fun main(args: Array<String>) {
SpringApplication.run(SimManagerApplication::class.java, *args)
}
build.gradle dependencies
dependencies {
compile('org.springframework.boot:spring-boot-starter-quartz')
compile('org.springframework.boot:spring-boot-starter-web')
compile('com.fasterxml.jackson.module:jackson-module-kotlin')
compile('com.vaadin:vaadin-spring-boot-starter')
compile('org.flywaydb:flyway-core')
compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
compile("org.jetbrains.kotlin:kotlin-reflect")
compile("com.h2database:h2")
compile("eu.vaadinonkotlin:vok-rest:0.6.2")
compile('org.codehaus.groovy:groovy-all:2.5.4')
compile("org.flywaydb:flyway-core:5.2.0")
compile "org.grails:gorm-hibernate5-spring-boot:6.1.6.RELEASE"
compile "org.hibernate:hibernate-core:5.1.0.Final"
compile "org.hibernate:hibernate-ehcache:5.1.0.Final"
runtime "org.apache.tomcat:tomcat-jdbc:8.5.0"
runtime "org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.0"
runtime "org.slf4j:slf4j-api:1.7.10"
}
and as simple as that, the project fails to start. What, exactly, causes the UnsatisfiedDependencyException? Is there a simple straightforward way to solve it?.
Thank you very much in advance.

#Autowired and UnsatisfiedDependencyException in a junit test

i am writing a junit test that have to invoke some method from some autowired dependency which has to interact with Cassandra, but i am getting this exception:
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.21 s <<< FAILURE! - in unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests
[ERROR] testFindByUsername(unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests) Time elapsed: 0.001 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the junit test:
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.ClassRule;
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.data.util.Version;
import org.springframework.test.context.junit4.SpringRunner;
import example.springdata.cassandra.util.CassandraKeyspace;
import unicon.matthews.admin.AdminUser;
import unicon.matthews.admin.service.repository.AdminUserRepository;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = CassandraConfiguration.class)
public class AdminUserRepositoryTests {
#ClassRule public final static CassandraKeyspace CASSANDRA_KEYSPACE = CassandraKeyspace.onLocalhost().atLeast(Version.parse("3.0"));
#Autowired AdminUserRepository repository;
#Before
public void setUp() throws Exception {
repository.deleteAll();
}
#Test
public void testFindByUsername() {
try {
final String userName = "aironman";
AdminUser.Builder myBuilderAdmin = AdminUser.Builder.class.newInstance();
myBuilderAdmin.withId("id");
myBuilderAdmin.withEmailAddress("some#domain.com");
myBuilderAdmin.withOrgId("orgId");
myBuilderAdmin.withPassword("some-password");
myBuilderAdmin.withSuperAdmin(Boolean.TRUE);
myBuilderAdmin.withTenantId("tenantId");
myBuilderAdmin.withUserName(userName);
//que viene aqui exactamente?
Map<String, String> someMetadata = new HashMap<String, String>();
someMetadata.put("some-key","some-value");
myBuilderAdmin.withMetadata(someMetadata);
AdminUser myAdminUser = myBuilderAdmin.build();
repository.save(myAdminUser);
Optional<AdminUser> loadedUserName = repository.findByUsername(userName);
assertNotNull(loadedUserName);
// assertThat(repository.findOne(homer.id).isPresent(), is(true));
assertEquals("something went wrong!",userName,loadedUserName.get().getUsername());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("Done testFindByUsername!");
}
}
AdminUserRepository looks like:
import java.util.Optional;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import unicon.matthews.admin.AdminUser;
#Repository
public interface AdminUserRepository extends CrudRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}
CassandraConfiguration looks like:
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
#Configuration
#EnableAutoConfiguration
class CassandraConfiguration {
#Configuration
#EnableCassandraRepositories
static class CassandraConfig extends AbstractCassandraConfiguration {
#Override
public String getKeyspaceName() {
return "example";
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.RECREATE;
}
}
}
I understand that spring is trying to instantiate this AdminUserRepository class which is created using CrudRepository from spring-data project. It is supposed that if i mark this interface with #Repository, spring will instantiate the class within the spring context in order that another bean will be capable to autowire it within it, so, why spring is not able to instantiate the dependency?
AdminUserRepository interface is located within src/main/java and AdminUserRepositoryTests is located within src/test/java.
this is my actual pom.xml, please help.
Marking a Spring data repository with #Repository actually doesn't do anything. If you wan't to enable a CrudRepository you need to annotate your configuration with #EnableJpaRepositories. However, since you are using Cassandra I think it's more likely you want to be using a CassandraRepository ?
public interface AdminUserRepository extends CassandraRepository<AdminUser, String> {
#Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);
}

No qualifying bean of type [java.lang.Class] found for dependency [java.lang.Class<org.springframework.data.repository.Repository<?, ?>>]

I have started working with Spring framework. Here I am working with Spring Data - Cassandra Repository modular application. I could able to test a spring-data-cassandra application individually, whereas when I try to use as a moudle in a project and scan the packages of components from other module like...
<context:component-scan base-package="example.dao,example.domain" />
I am getting an error
No qualifying bean of type [example.domain.EventRepository] found for dependency [example.domain.EventRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I can share you the code, if required.
The way I have done for another modules works fine.
I am not getting where is the problem.
Please find the code below for DAO CLASS.
#Service
#Transactional
public class EventDao {
#Autowired
private EventRepository eventRepository;
/*public EventDao(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}*/
private final static Logger logger = LoggerFactory.getLogger(EventDao.class);
public Event saveMember(Event member) {
eventRepository.save(member);
return member;
}
}
My Repository interface.
package example.domain;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
public interface EventRepository extends CassandraRepository<Event> {
#Query("select * from event where type = ?0 and bucket=?1")
Iterable<Event> findByTypeAndBucket(String type, String bucket);
}
My Cassandra configuration class.
package example;
#Configuration
#PropertySource(value = { "classpath:cassandra.properties" })
#EnableCassandraRepositories(basePackages = { "example" })
public class CassandraConfiguration extends AbstractCassandraConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(CassandraConfiguration.class);
#Autowired
private Environment environment;
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
return cluster;
}
#Override
protected String getKeyspaceName() {
return environment.getProperty("cassandra.keyspace");
}
#Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
}
UPDATE
I could able to create individual spring-data-cassandra and spring-data-neo4j modules seperately with other service modules and its working fine in both the modules.
But I have another module with Neo4j spring-data-neo4j module in the same project, when I try to run both(neo4j+cassandra) the modules under the same project its creating the problem.
still waiting for the help! I have tried my best!
Thanks!

javax.validation.ValidationException: Call to TraversableResolver.isReachable() threw an exception

I am getting below Exception with my Application , For bean validation in Spring , I am using Spring4.0.2 version.
I am working with weblogic11g application server
javax.validation.ValidationException: Call to TraversableResolver.isReachable() threw an exception
at org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:773)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:331)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForRedefinedDefaultGroup(ValidatorImpl.java:278)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:260)
at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:213)
Truncated. see log file for complete stacktrace
Caused By: javax.persistence.PersistenceException: Failed to load provider from META-INF/services
at javax.persistence.spi.PersistenceProviderResolverHolder$DefaultPersistenceProviderResolver.getPersistenceProviders(PersistenceProviderResolverHolder.java:121)
at javax.persistence.Persistence$PersistenceUtilImpl.isLoaded(Persistence.java:278)
at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(JPATraversableResolver.java:33)
at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(DefaultTraversableResolver.java:112)
at org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:47)
Truncated. see log file for complete stacktrace
Caused By: java.lang.ClassCastException: org.apache.openjpa.persistence.PersistenceProviderImpl cannot be cast to javax.persistence.spi.PersistenceProvider
at javax.persistence.spi.PersistenceProviderResolverHolder$DefaultPersistenceProviderResolver.getPersistenceProviders(PersistenceProviderResolverHolder.java:110)
at javax.persistence.Persistence$PersistenceUtilImpl.isLoaded(Persistence.java:278)
at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(JPATraversableResolver.java:33)
at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(DefaultTraversableResolver.java:112)
at org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:47)
Truncated. see log file for complete stacktrace
this is my POJO class
import java.util.Date;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
public class TestVO extends BaseVO {
private static final long serialVersionUID = 1L;
#Length(max=18)
#NotNull
#NotEmpty
#Pattern(regexp = "[a-zA-Z0-9]*")
private String Id;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
}
This is My validator Class
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class DataValidator {
#Autowired(required = true)
private Validator validator;
public Set<ConstraintViolation<Object>> validate(Object tvo) {
return this.validator.validate(tvo);
}
}
this is my controller class where I am trying to validate my POJO
#Autowired
private DataValidator dValidator;
TestVO testVO = testBO.getTest(id);
Set<ConstraintViolation<Object>> violations = this.dValidator.validate(testVO);
I have updated the application-context.xml with the below validator
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
I have below Jar's in place in my WEB-INF/lib
hibernate-validator-4.0.1.GA.jar
validation-api-1.0.0.GA.jar
j2ee.jar
javax.persistence_1.0.0.0_1-0-2.jar
commons-logging-1.1.1.jar
Any Help can be greatly appreciated.
This problem usually happens from conflicts caused by loading classes of the same name, but from different classloaders. I would suggest you to check for any duplicated persistence jar-files (in your case javax.persistence_1.0.0.0_1-0-2.jar) and remove it(them)
If you're using certain configurations of Hibernate bytecode enhancement, you can also encounter this exception. See https://hibernate.atlassian.net/browse/HHH-11294

Resources