org.springframework.beans.factory.UnsatisfiedDependencyException on Cloud Rest Client with Netflix Ribbon - spring

I am getting
a org.springframework.beans.factory.UnsatisfiedDependencyException while running SpringClientSideRibbonApplication.java class. I think there is no error but I don't know why this exception comes. Please help me. I am using STS IDE.
MyConfiguration.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
public class MyConfiguration {
#Autowired
IClientConfig ribbonClientConfig;
#Bean
public IPing ribbonPing(IClientConfig config) {
return new PingUrl();
}
#Bean
public IRule ribbonRule() {
return new WeightedResponseTimeRule();
}
}
SpringClientSideRibbonApplication.java
package com.javasampleapproach.ribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
#SpringBootApplication
#RibbonClient(name = "helloworld", configuration =
MyConfiguration.class)
public class SpringClientSideRibbonApplication {
public static void main(String[] args)
{
SpringApplication.run(SpringClientSideRibbonApplication.class,
args);
}
}
WebController.java
package com.javasampleapproach.ribbon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#RestController
public class WebController {
#LoadBalanced
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
#Autowired
RestTemplate restTemplate;
#RequestMapping("/helloworld")
public String home() {
return
this.restTemplate.getForObject("http://helloworld/greeting",
String.class);
}
}
Error Msg
Error creating bean with name 'myConfiguration': Unsatisfied
dependency expressed through field 'ribbonClientConfig'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ribbonClientConfiguration': Invocation
of init method failed; nested exception is
java.lang.NoClassDefFoundError:
org/apache/commons/configuration/AbstractConfiguration
Application.yml
spring:
application:
name: Ribbon-Client
helloworld:
ribbon:
eureka:
enabled: false
listOfServers: localhost:8090,localhost:8091,localhost:8092
ServerListRefreshInterval: 15000
server:
port: 8080
Dependency
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.3.5.RELEASE </version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Their is no coding error. The problem was in my Maven dependency.My internet is slow so Maven download the corrupt jar file. I tried with Gradle. Now it's okey

Related

Injection of CommandGateway not work in Quarkus using AxonIq

I have a microservice in Quarkus which implementing CQRS/Event sourcing using AxonIq Framework. I Already made it using Spring boot and everythings it's ok. I would like to migrate it in Quarkus but I have error during maven compilation probably because the Ioc. When CDI try to create the service I think he can inject Axon CommandGateway and QueryGateway.
[ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:2.7.1.Final:build (default) on project domain: Failed to build quarkus application: io.quarkus.builder.BuildExce
ption: Build failure: Build failed due to errors
[ERROR] [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 2 deployment problems:
[ERROR] [1] Unsatisfied dependency for type org.axonframework.Commandhandling.CommandGateway and qualifiers [#Default]
[ERROR] - java member: com.omb.commands.MyAggregateCommandService().commandGateway
[ERROR] - declared on CLASS bean [types=[com.omb.commands.MyAggregateCommandService, java.lang.Object], qualifiers=[#Default, #Any], target=com.omb.commands.MyAggregateCommandService]
Configuration
package com.omb..configuration;
import com.omb..MyAggregate;
import com.omb..commands.MyAggregateCommandService;
import com.omb..mongo.MongoMyAggregateProjector;
import com.omb..queries.MyAggregateQueryService;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.axonframework.config.Configurer;
import org.axonframework.config.DefaultConfigurer;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.extensions.mongo.DefaultMongoTemplate;
import org.axonframework.extensions.mongo.eventsourcing.tokenstore.MongoTokenStore;
import org.axonframework.serialization.xml.XStreamSerializer;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
#ApplicationScoped
public class AxonConfiguration {
#Produces
public org.axonframework.config.Configuration getAxonConfiguration(MongoMyAggregateProjector MyAggregateProjector, MongoDatabase database, EventStorageEngine eventStorageEngine) {
XStreamSerializer serializer = XStreamSerializer.defaultSerializer();
Configurer configurer = DefaultConfigurer
.defaultConfiguration()
.configureAggregate(MyAggregate.class)
.eventProcessing(conf -> conf
.registerTokenStore(config -> MongoTokenStore.builder()
.mongoTemplate(
DefaultMongoTemplate.builder()
// optionally choose collection names here
.mongoDatabase(database)
.build())
.serializer(serializer)
.build()))
.registerEventHandler(conf -> MyAggregateProjector)
.registerQueryHandler(conf -> MyAggregateProjector)
.configureEmbeddedEventStore(conf -> eventStorageEngine);
return configurer.start();
}
#Produces
public MongoDatabase mongoDatabase(MongoClient client) {
return client.getDatabase("MyAggregate");
}
#Produces
#ApplicationScoped
public MyAggregateQueryService queryService(org.axonframework.config.Configuration configuration) {
return new MyAggregateQueryService(configuration.queryGateway());
}
#Produces
#ApplicationScoped
public MyAggregateCommandService commandService(org.axonframework.config.Configuration configuration) {
return new MyAggregateCommandService(configuration.commandGateway());
}
}
Service :
package com.omb..commands;
import com.omb..models.MyAggregateDTO;
import org.axonframework.commandhandling.gateway.CommandGateway;
import javax.enterprise.context.ApplicationScoped;
import java.util.concurrent.CompletableFuture;
#ApplicationScoped
public class MyAggregateCommandService {
CommandGateway commandGateway;
public MyAggregateCommandService(CommandGateway commandGateway) {
this.commandGateway = commandGateway;
}
public CompletableFuture<String> createMyAggregate(final MyAggregateDTO MyAggregate) {
return commandGateway.send(new CreateMyAggregateCommand(MyAggregate.id(), MyAggregate.name()));
}
public CompletableFuture<MyAggregateDTO> updateMyAggregate(final String MyAggregateId, final MyAggregateDTO MyAggregate) {
if(MyAggregate.id().equals(MyAggregateId)) {
return commandGateway.send(new UpdateMyAggregateCommand(MyAggregate.id(), MyAggregate.name()));
} else {
throw new IllegalArgumentException("Identifiers are not the same, does not update");
}
}
}
Controller :
package com.omb;
import com.omb..commands.MyAggregateCommandService;
import com.omb..models.MyAggregateDTO;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
#Path("/commands/MyAggregate")
public class MyAggregateCommandController {
private MyAggregateCommandService MyAggregateCommandService;
public MyAggregateCommandController(MyAggregateCommandService MyAggregateCommandService) {
this.MyAggregateCommandService = MyAggregateCommandService;
}
#POST
#Path("/create")
public CompletableFuture<String> createMyAggregate(#Valid MyAggregateCreateInput MyAggregate) {
MyAggregateDTO MyAggregateDTO = new MyAggregateDTO(UUID.randomUUID().toString(), MyAggregate.name());
return MyAggregateCommandService.createMyAggregate(MyAggregateDTO);
}
#PUT
#Path("/{MyAggregateId}")
public CompletableFuture<MyAggregateDTO> updateMyAggregate(#PathParam("MyAggregateId") String MyAggregateId, MyAggregateDTO MyAggregate) {
MyAggregateDTO MyAggregateDTO = new MyAggregateDTO(MyAggregate.id(), MyAggregate.name());
return MyAggregateCommandService.updateMyAggregate(MyAggregateId,MyAggregateDTO);
}
/* #ExceptionHandler(value = Exception.class)
public ResponseEntity<String> handle(Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}*/
}
dependency
<dependency>
<groupId>org.axonframework.extensions.mongo</groupId>
<artifactId>axon-mongo</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-test</artifactId>
<scope>test</scope>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-panache</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-configuration</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-modelling</artifactId>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-messaging</artifactId>
</dependency>
<!-- Quarkus -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-core</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-reactive-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
I had the same issue, one of the reasons can be that your bean is brought by a dependency and to fix it you need to add an empty beans.xml in main/resources/META-INF in this dependency in order for Quarkus to discover the beans as indicated by the documentation
Relevant extract:
The bean archive is synthesized from:
the application classes,
dependencies that contain a beans.xml descriptor (content is ignored),
dependencies that contain a Jandex index - META-INF/jandex.idx,
dependencies referenced by quarkus.index-dependency in application.properties,
and Quarkus integration code.

How to create a Spring boot application with Azure Event Hubs

when my application when running it hit the error
All classes in my application can see below
any aides for fix this error
only 3 class available in my project.
Failed to start bean 'outputBindingLifecycle'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventHubChannelProvisioner' defined in com.azure.spring.eventhub.stream.binder.config.EventHubBinderConfiguration: Unsatisfied dependency expressed through method 'eventHubChannelProvisioner' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.azure.spring.integration.eventhub.factory.EventHubConnectionStringProvider' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
how to fix this my main class
import com.azure.spring.integration.core.EventHubHeaders;
import com.azure.spring.integration.core.api.reactor.Checkpointer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import java.util.function.Consumer;
import static com.azure.spring.integration.core.AzureHeaders.CHECKPOINTER;
#SpringBootApplication
public class EventHubsCheckerApplication {
public static final Logger LOGGER = LoggerFactory.getLogger(EventHubsCheckerApplication.class);
public static void main(String[] args) {
SpringApplication.run(EventHubsCheckerApplication.class, args);
}
#Bean
public Consumer<Message<String>> consume() {
return message -> {
Checkpointer checkpointer = (Checkpointer) message.getHeaders().get(CHECKPOINTER);
LOGGER.info("New message received: '{}', partition key: {}, sequence number: {}, offset: {}, enqueued time: {}",
message.getPayload(),
message.getHeaders().get(EventHubHeaders.PARTITION_KEY),
message.getHeaders().get(EventHubHeaders.SEQUENCE_NUMBER),
message.getHeaders().get(EventHubHeaders.OFFSET),
message.getHeaders().get(EventHubHeaders.ENQUEUED_TIME)
);
checkpointer.success()
.doOnSuccess(success -> LOGGER.info("Message '{}' successfully checkpointed", message.getPayload()))
.doOnError(error -> LOGGER.error("Exception found", error))
.subscribe();
};
}
}
controller class
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Sinks;
#RestController
public class EventProducerController {
public static final Logger LOGGER = LoggerFactory.getLogger(EventProducerController.class);
#Autowired
private Sinks.Many<Message<String>> many;
#PostMapping("/messages")
public ResponseEntity<String> sendMessage(#RequestParam String message) {
LOGGER.info("Going to add message {} to sendMessage.", message);
many.emitNext(MessageBuilder.withPayload(message).build(), Sinks.EmitFailureHandler.FAIL_FAST);
return ResponseEntity.ok(message);
}
}
configuration class
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import java.util.function.Supplier;
#Configuration
public class EventProducerConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(EventProducerConfiguration.class);
#Bean
public Sinks.Many<Message<String>> many() {
return Sinks.many().unicast().onBackpressureBuffer();
}
#Bean
public Supplier<Flux<Message<String>>> supply(Sinks.Many<Message<String>> many) {
return () -> many.asFlux()
.doOnNext(m -> LOGGER.info("Manually sending message {}", m))
.doOnError(t -> LOGGER.error("Error encountered", t));
}
}
pom file
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.contoso</groupId>
<artifactId>event-hubs-cheker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>event-hubs-cheker</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>azure-spring-cloud-stream-binder-eventhubs</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
how to run with out any error i cant fix this help me for that please
how to fix this issue i try to fix this but i cant fix it
After following the instructions on the following web page: How to create a Spring Cloud Stream Binder application with Azure Event Hubs
I was able to have the project working. You can review my implementation at the following GitHub repository: https://github.com/esalomon/spring-event-hubs1

Using Feign builder requests doesn't send trace-id, span-id to child clients but using rest template is showing all headers on child clients

I'm making a sequential request using Feign Builder. There are no x-b3-traceid,x-b3-spanid .. in the title of the request. That's why the log my last client appears on the zipkin.
I use spring boot 2.4.2 , spring cloud 2020.0.0 , feign-core 10.10.1 , feign-okhttp 10.10.1. I have tried spring-cloud-openfeign and i achieved wanted result. But i don't want to use this lib. There are requests when using Feign Builder and Rest Template in here. I dont' see same log at zipkin.
My Client1 App. I am sending request http://localhost:8082/
import feign.Client;
import feign.Feign;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sample.feign2.Client2Feign;
import javax.servlet.http.HttpServletRequest;
#RestController
public class SampleController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Autowired
private RestTemplate restTemplate;
#Autowired
private Client client;
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
#Bean
public OkHttpClient okHttpClient(){
return new OkHttpClient();
}
#GetMapping("/hello/feignBuilder")
public String sayHelloFeignBuilder(HttpServletRequest httpServletRequest){
logger.info("Send to request client2");
Client2Feign client2Feign = Feign.builder()
.client(client)
.decoder(new Decoder.Default())
.encoder(new Encoder.Default())
.target(Client2Feign.class, "http://localhost:8082/");
return client2Feign.sayHelloFeignBuilder();
}
#GetMapping("/hello/say")
public String sayHelloFeignBuilder1(){
return "Hello";
}
#GetMapping("/hello/rest")
public String sayHelloRest(){
System.out.println(tracer.currentSpan());
logger.info("Inside rest 1");
String baseUrl = "http://localhost:8082/sayHelloRest";
String response = (String) restTemplate.exchange(baseUrl, HttpMethod.GET, null, String.class).getBody();
logger.info("The response received by client2 is " + response);
return response;
}
}
This is yml of my client1 app. I use same yml conf on other client apps which client2 and clint3. Only changes port and app name.
server:
port: 8081
spring:
application:
name: euraka-client1
zipkin:
enabled: true
service.name: euraka-client1
sender.type: web
base-url: http://localhost:9411
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka
instance:
preferIpAddress: true
This is my Feign at Client2 app.
import feign.RequestLine;
public interface Client2Feign {
#RequestLine("GET /sayHelloBuilder")
String sayHelloFeignBuilder();
}
Here impl of ClientFeign2.
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
public interface FeignBuilderController {
#GetMapping("/sayHelloBuilder")
String sayHelloBuilder(HttpServletRequest httpServletRequest);
#GetMapping("/sayHelloRest")
String sayHelloRest(HttpServletRequest httpServletRequest);
}
import feign.Client;
import feign.Feign;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sample.feign.Client3Feign;
import sample.feign2.Client2Feign;
import javax.servlet.http.HttpServletRequest;
#RestController
public class FeignBuilderControllerImpl implements FeignBuilderController{
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Autowired
private RestTemplate restTemplate;
#Autowired
private Client client;
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
#Bean
public OkHttpClient okHttpClient(){
return new OkHttpClient();
}
#Override
public String sayHelloBuilder(HttpServletRequest httpServletRequest) {
logger.info("Send to request client3");
Client3Feign client3Feign = Feign.builder()
.client(client)
.decoder(new Decoder.Default())
.encoder(new Encoder.Default())
.target(Client3Feign.class, "http://localhost:8083/");
return client3Feign.sayHelloFeignBuilder3();
}
#Override
public String sayHelloRest(HttpServletRequest httpServletRequest) {
logger.info("Inside rest 2");
String baseUrl = "http://localhost:8083/sayHelloRestClient3";
String response = (String) restTemplate.exchange(baseUrl, HttpMethod.GET, null, String.class).getBody();
logger.info("The response received by client3 is " + response);
return response;
}
This is my Feign at Client3 app.
import feign.RequestLine;
public interface Client3Feign {
#RequestLine("GET /sayHelloBuilderClient3")
String sayHelloFeignBuilder3();
}
Here impl of Client3 Feign.
import javax.servlet.http.HttpServletRequest;
public interface FeignController3 {
#GetMapping("/sayHelloBuilderClient3")
String sayHello3(HttpServletRequest httpServletRequest);
#GetMapping("/sayHelloRestClient3")
String sayHelloRest3(HttpServletRequest httpServletRequest);
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
#RestController
#RequestMapping
public class FeignController3Impl implements FeignController3 {
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Override
public String sayHello3(HttpServletRequest httpServletRequest) {
logger.info("Response returned from client3");
return "Hello from client3 using FeignClientBuilder";
}
#Override
public String sayHelloRest3(HttpServletRequest httpServletRequest) {
logger.info("Response returned from client3");
return "Hello from client3 using RestClient";
}
}
pom.xml from client3 and i use client3 at client2/pom and the same as client1.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>oguzhan.example</groupId>
<artifactId>client3</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<release>${java.version}</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
diff-feign-rest-image
feign-zipkin-img
feign-request-img
rstlet-rest-tmplte-img
rest-zipkin-img
The problem might be related to the fact that you're creating the Feign builder manually via Feign.builder() factory method. We're unable to instrument that call. You should create a bean (via SleuthFeignBuilder.builder) and inject that into your code.

Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration

we are using Freemarker for generating the HTML code for the emails our application is going to be sending.
Our usage and configuration is based off of https://github.com/hdineth/SpringBoot-freemaker-email-send
Particularly:
package com.example.techmagister.sendingemail.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import java.io.IOException;
#Configuration
public class FreemarkerConfig {
#Bean(name="emailConfigBean")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates/");
return bean;
}
}
However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using JUnit 5.
When I added the relevant dependencies
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
versions:
<junit.jupiter.version>5.3.1</junit.jupiter.version>
<mockito.version>2.23.0</mockito.version>
And made a test class:
package com.example.techmagister.sendingemail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
#ExtendWith({SpringExtension.class, MockitoExtension.class})
#Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() throws Exception {
try {
Template template = emailConfig.getTemplate("email.ftl");
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run that in debug mode, emailConfig is null.
Why is that?
Their test example https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java
works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.
In our actual code (which is large, multi module project), I have another error org.springframework.beans.factory.UnsatisfiedDependencyException
caused by:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.
You cannot autowire your emailConfigBean directly as a freemarker.template.Configuration
FreeMarkerConfigurationFactoryBean is a factorybean.
To get the Confuguration you need to call factorybean.getObject()
so instead of
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
just autowire your factorybean FreeMarkerConfigurationFactoryBean and load your template with emailConfig.getObject().getTemplate("email.ftl")
#Autowired
#Qualifier("emailConfigBean")
private FreeMarkerConfigurationFactoryBean emailConfig;
#Test
void testFreemarkerTemplate(){
Assertions.assertNotNull(emailConfig);
try {
Template template =
emailConfig
.getObject() // <-- get the configuration
.getTemplate("email.ftl"); // <-- load the template
Assertions.assertNotNull(template);
} catch (Exception e) {
e.printStackTrace();
}
working test on github
On the other hand...
In a Spring Boot application the Freemarker configuration can be simplified by using the spring-boot-starter-freemarker dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
This starter for building MVC web applications using FreeMarker views adds the necessary auto-configuration. All you need to do is placing your template files in the resources/templates folder.
Then you just can autowire the freemarkerConfig (or use constructor injection):
#Autowired
private Configuration freemarkerConfig;
There is a nice example here, in the attached github code. I was able to use it as a starting point to test my freeMarker code: https://cleantestcode.wordpress.com/2014/06/01/unit-testing-freemarker-templates/

Trying to use Oauth2 token with feign client and hystrix

I am trying to call "ServiceB" from "ServiceA", both of the services are resource server, I am trying to make this inter service call through "Feign Client and OAuth2 toke" which is working fine with the below bean implmentation in Configuration class:
#Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
#Override
public void apply(RequestTemplate requestTemplate) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
SecurityContextHolder.getContext().getAuthentication()
.getDetails();
requestTemplate.header("Authorization",
"bearer " + details.getTokenValue());
}
};
}
When I am trying to use Feign client with fallback i.e. Hystrix without OAuth token(i.e. when none of services are Resource Server) that is also working fine.
But while trying to use three of these (i.e. Feignclient, Hystrix and OAuth2)all together, it is not working. Every time it is going to fallback method though all the services are up and running.
Below are my code:
App.java
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import feign.RequestInterceptor;
import feign.RequestTemplate;
#SpringBootApplication
#RestController
#EnableFeignClients
#EnableEurekaClient
#EnableCircuitBreaker
public class App
{
/*#Autowired
#Qualifier("abc")
private GitHubClient gitHub;*/
#Autowired
private CallService callService;
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
#RequestMapping(value="/feign",method=RequestMethod.POST,consumes="application/json")
public String contributors1(#RequestBody JSONObject payLoad) {
String callservice2 = callService.callservice(payLoad);
return callservice2;
}
#Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
#Override
public void apply(RequestTemplate requestTemplate) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
SecurityContextHolder.getContext().getAuthentication()
.getDetails();
requestTemplate.header("Authorization",
"bearer " + details.getTokenValue());
}
};
}
}
Callervice.java
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class CallService {
#Autowired
#Qualifier("abc")
private GitHubClient gitHub;
public String callservice(JSONObject payLoad){
String forObject =gitHub.contributors(payLoad);
return forObject;
}
}
HystrixWrappedClient.java
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
#Component("abc")
public class HystrixWrappedClient implements GitHubClient{
#Autowired
#Qualifier("gitHubClient")
private GitHubClient gitHub;
#Override
#HystrixCommand(fallbackMethod="failure")
public String contributors(JSONObject payLoad) {
return gitHub.contributors(payLoad);
}
public String failure(JSONObject payLoad){
System.out.println(payLoad);
return "Failure";
}
}
GitHubClient.java
import org.json.simple.JSONObject;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#FeignClient("MockRestService")
interface GitHubClient {
#RequestMapping(method = RequestMethod.POST, value = "/test",consumes="application/json")
String contributors(#RequestBody JSONObject payLoad);
}
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>
<!-- For swagger documenation -->
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<!-- NEW -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>1.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Please suggest. Whenever trying to use Feignclient, OAuth2 and Hystrix all together it always going to Fallback method.
Did you shared Spring Security context with Hystrix in some way?
Since Spring Cloud Netflix 1.2.0 you can enable sharing of security context with Hystrix using i.e config param
hystrix.shareSecurityContext: true
u can look into this http://kodgemisi.com/2017/02/use-securitycontext-feign-requestinterceptor/
Hystrix execute in another/different thread, transfer your security context by HystrixRequestVariableDefault

Resources