No instance(s) of type variable(s) T exist so that Flux<T> confirms to Mono<? extend R) - spring-boot

I am implementing Spring webflux demo application and have written my demo application as like that
package com.abcplusd.application;
import com.abcplusd.domain.Event;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import java.util.Collections;
import java.util.Date;
import java.util.stream.Stream;
#SpringBootApplication
public class ReactiveClientApplication {
#Bean WebClient webClient() {
return WebClient.create("http://localhost:8080");
}
#Bean CommandLineRunner demo(WebClient webClient) {
return args -> {
webClient.get()
.uri("/events")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class))
.subscribe(System.out::println);
};
}
public static void main(String[] args) {
new SpringApplicationBuilder(ReactiveClientApplication.class)
.properties(Collections.singletonMap("server.port", "8081"))
.run(args);
}
}
It shows the following error
Error:(29, 41) java: incompatible types: no instance(s) of type variable(s) T exist so that reactor.core.publisher.Flux<T> conforms to reactor.core.publisher.Mono<? extends R>
The above error is at this line:
.flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class)))
Event Class
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
#Data
#AllArgsConstructor
public class Event {
private long id;
private Date when;
}
Can anybody help me to solve the error?

It works me after i have done these changes in my code
.flatMap(clientResponse -> clientResponse.bodyToFlux(Event.class)))
to
.flatMapMany(clientResponse -> clientResponse.bodyToFlux(Event.class))
and
#NoArgsConstructor annotation in Event.Class
as follows:
import java.util.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Event {
private long id;
private Date when;
}

flatMapMany instead of flatMap works.
However when you add property spring.main.web_environment=false to application.properties file, webClient simply doesn't work.

Related

Spring can't find repository bean

I'm using spring boot with spring data jdbc and I got trouble with run my app
I have StudentService class:
package ru.turnip.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.turnip.model.Student;
import ru.turnip.repository.StudentRepository;
import ru.turnip.utils.student.BusyStudents;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
#Service
public class StudentService {
private final BusyStudents busyStudents;
private final StudentRepository studentRepository;
public StudentService(BusyStudents busyStudents, StudentRepository studentRepository) {
this.busyStudents = busyStudents;
this.studentRepository = studentRepository;
}
...
}
And StudentRepository interface:
package ru.turnip.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ru.turnip.model.Student;
import java.util.UUID;
#Repository
public interface StudentRepository extends CrudRepository<Student, UUID> { }
So, when I try to run app, I get an eror, and I can't figure out where the problem is.
That my config class:
package ru.turnip;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.relational.core.mapping.event.BeforeSaveEvent;
import org.springframework.scheduling.annotation.EnableScheduling;
import ru.turnip.model.Student;
import java.time.Clock;
import java.util.UUID;
#ComponentScan
#Configuration
#EnableScheduling
public class ApplicationConfig {
#Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
#Bean
public ApplicationListener<BeforeSaveEvent> idGenerator() {
return event -> {
var entity = event.getEntity();
if (entity instanceof Student) {
((Student) entity).setId(UUID.randomUUID());
}
};
}
}
And project structure:
I tried to explicitly set package to be scanned, and also moved the repository to the package with the config. Also I tried to annotate with #Autowired field and constructor in StudentService

Encountered error "Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration"

I am getting the below error while starting spring boot application.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'java.util.concurrent.atomic.AtomicReference' in your configuration.
Below is the code .
package de.summer.sampleapplayerv1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication(scanBasePackages = {"de.summer.sampleapplayerv1"})
#EnableConfigurationProperties
#EnableJpaRepositories (basePackages ="de.summer.sampleapplayerv1.repository")
#EnableTransactionManagement
public class Sampleapplayerv1Application {
public static void main(String[] args) {
SpringApplication.run(Sampleapplayerv1Application.class, args);
}
}
package de.summer.sampleapplayerv1.service;
import de.summer.sampleapplayerv1.domain.QueueAndPublish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
#Slf4j
#Service
public class QueueAndPublishServiceImpl implements QueueAndPublishService{
private final AtomicReference<List<QueueAndPublish>> currentJob;
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
#Override
public QueueAndPublish getJobStatus(UUID jobId) {
return (QueueAndPublish) currentJob.get().stream()
.filter(j -> j.getJobId()==jobId)
.collect(Collectors.toList());
}
#Override
public List<QueueAndPublish> getAllJobStatus() {
return currentJob.get();
}
#Override
public QueueAndPublish getCategoryDataProcess() {
List<QueueAndPublish> processList=new ArrayList<QueueAndPublish>();
QueueAndPublish process=QueueAndPublish.builder()
.jobId(UUID.randomUUID())
.jobName("Name for Job")
.jobStatus("Not Yet Started")
.build();
Thread t1=new Thread(process.getJobId().toString()){
#Override
public void run(){
log.info("How are you doing");
process.setJobStatus("Completed");
}
};
t1.start();
processList.add(process);
currentJob.set(processList);
return process;
}
#Override
public QueueAndPublish getCatgeoryDataProcessStatus() {
return null;
}
}
package de.summer.sampleapplayerv1.domain;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.UUID;
#Getter
#Setter
#Builder
#Entity
public class QueueAndPublish implements Serializable {
#Id
private UUID jobId;
private String jobName;
private String jobStatus;
}
If I remove the constructor, spring boot application is starting up without any errors. If included , start up is failing with unsatisfied dependency errors.
Can someone please help on what is wrong with config?
You expect Spring to create an instance of class QueueAndPublishServiceImpl for the implementation of QueueAndPublishService. This instance needs a constructor parameter of type AtomicReference<List<QueueAndPublish>> injected.
But you obviously do not define any Spring bean (Bean, Component, Service, ...) of that type.
Edit:
public QueueAndPublishServiceImpl(
#Qualifier("currentJob") AtomicReference<List<QueueAndPublish>> currentJob
){
this.currentJob=currentJob;
}
Here you define a constructor parameter to have a AtomicReference<List<QueueAndPublish>>, and even specify it with a #Qualifier. So you need to provide a Spring bean of this class with this qualifier, otherwise Spring cannot inject it into the constructor call.
Consider defining a bean of type 'java.util.concurrent.atomic.AtomicReference' in your configuration.
Means "something like" adding this to your Sampleapplayerv1Application:
#Bean("currentJob") AtomicReference<List<QueueAndPublish>> currentJob() {
// or a list implementation of your choice.
return new AtomicReference<>(new java.util.ArrayList<>());
}

Is it a good idea to declare an injector and pass it as a state parameter when integrating typed Akka Actor with Spring

I could not find a neat way to integrate Spring with typed Actors.
Instead of using extensions I had declared an injector service
import akka.actor.typed.ActorSystem;
import com.akka.demo.a010.ASimpleSpringService;
import com.akka.demo.a010.AkkaSimpleBehaviour;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
#Data
public class ActorInjector {
#Autowired
private ASimpleSpringService aSimpleSpringService;
#Autowired
private ActorInjector _self;
public ActorSystem<AkkaSimpleBehaviour.Command> createAkkaSimpleBehaviour(String actorName) {
return ActorSystem.create(AkkaSimpleBehaviour.create(_self), actorName);
}
}
This service autowires itself and pass that reference to a simple actor.
My Actor definition is as follows.
import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import com.akka.demo.a010.config.ActorInjector;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Slf4j
public class AkkaSimpleBehaviour extends AbstractBehavior<AkkaSimpleBehaviour.Command> {
private final List<String> messages = new ArrayList<>();
private ActorRef<List<String>> sender;
private ActorInjector actorInjector;
public interface Command extends Serializable {
}
#AllArgsConstructor
public static class TellMeSomething implements Command {
private static final long serialVersionUID = -7796709831949054890L;
#Getter
private final String message;
}
#AllArgsConstructor
public static class CollectTheResults implements Command {
private static final long serialVersionUID = 1643210899551075153L;
#Getter
private final ActorRef<List<String>> sender;
}
private AkkaSimpleBehaviour(ActorContext<Command> context, ActorInjector actorInjector) {
super(context);
this.actorInjector = actorInjector;
}
public static Behavior<Command> create(ActorInjector actorInjector) {
return Behaviors.setup(ctx -> new AkkaSimpleBehaviour(ctx,actorInjector));
}
#Override
public Receive<Command> createReceive() {
return newReceiveBuilder().onMessage(TellMeSomething.class, message -> {
messages.add(message.getMessage());
actorInjector.getASimpleSpringService().logSomething("*-*-*-*-*-*-*-*-*-*");
return Behaviors.same();
}).onMessage(CollectTheResults.class, message -> {
this.sender = message.getSender();
if (messages.size() == 4) {
this.sender.tell(messages);
}
return Behaviors.same();
}).build();
}
}
After passing the injector service I can get my autowired dependencies from that service like :
actorInjector.getASimpleSpringService().logSomething("*-*-*-*-*-*-*-*-*-*");
My ASimpleService is just a dummy service which logs an output.
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
#Service
#Slf4j
public class ASimpleSpringService {
public void logSomething(String message){
log.info(message);
}
}
Then in a simple RestController I am using the system as follows:
import akka.actor.typed.ActorSystem;
import akka.actor.typed.javadsl.AskPattern;
import com.akka.demo.a010.config.ActorInjector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
#RestController
#Slf4j
public class MyRestController {
#Autowired
private ActorInjector actorInjector;
#GetMapping("/hello-akka")
public void greetings() {
ActorSystem<AkkaSimpleBehaviour.Command> exampleActor = actorInjector.createAkkaSimpleBehaviour("anActor");
exampleActor.tell(new AkkaSimpleBehaviour.TellMeSomething("hello"));
exampleActor.tell(new AkkaSimpleBehaviour.TellMeSomething("Who are you"));
exampleActor.tell(new AkkaSimpleBehaviour.TellMeSomething("create a child"));
exampleActor.tell(new AkkaSimpleBehaviour.TellMeSomething("Here is some message"));
CompletionStage<List<String>> result = AskPattern.ask(exampleActor, AkkaSimpleBehaviour.CollectTheResults::new, Duration.ofSeconds(10), exampleActor.scheduler());
result.whenComplete((reply, failure) -> {
if(reply != null){
log.info("The system responds in time");
} else {
log.error("The system does not respond in time");
exampleActor.terminate();
throw new RuntimeException("The system does not respond in time");
}
exampleActor.terminate();
});
try{
List<String> messages = result.toCompletableFuture().get();
messages.forEach(log::info);
} catch (InterruptedException | ExecutionException e){
e.printStackTrace();
}
}
}
My question is : I am planning to put all of my services into my ActorInjector service and these services will be injected into my actors. I am not familiar with Akka states and its side-effects however I know that it may be a bad idea to store all of these singleton services as actor states. Is it a good idea to store these services as an actor parameter ? What kind of side effects can I experience by doing this way? Can you point me the way?

Spring Boot #ComponentScan finds candidate component class but does not inject #Configuration beans

I have #SpringBootApplication with #ComponentScan({"myPackage"}) and in myPackage I have a class annotated with #Configuration or #Component. When I start the spring boot app the logs show:
DEBUG [main] org.sprin.conte.annot.ClassPathScanningCandidateComponentProvider 437 scanCandidateComponents: Identified candidate component class: file [C:\Web\project\bin\main\myPackage\Config.class]
but then nothing injects the class or its beans into the app...
It looks related to this
CODE
package app;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.gemfire.config.annotation.EnableLogging;
import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories;
#SpringBootApplication
#ComponentScan({"myPackage"})
#EntityScan({"myPackage"})
#EnableGemfireRepositories("region")
#EnableLogging(logLevel="info", logFile="geodeApi.log")
public class Web {
private static final Logger log = LogManager.getLogger(Web.class);
public static void main(String[] args) {
log.info("In Main");
SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Web.class, args);
log.info("Out Main");
}
}
In myPackage.Client
package myPackage;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableClusterDefinedRegions;
import org.springframework.data.gemfire.config.annotation.EnablePdx;
import org.springframework.data.gemfire.config.annotation.EnablePool;
import org.springframework.data.gemfire.config.annotation.EnablePool.Locator;
import org.springframework.data.gemfire.config.annotation.EnableStatistics;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
#ClientCacheApplication(name = "Web", logLevel = "debug")
#EnablePool(name = "webPool", subscriptionEnabled = true)
#EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
#EnablePdx
#EnableStatistics
#EnableGemFireHttpSession(poolName = "webPool")
#EnableGemfireCaching
// #EnableWebFlux
public class Client {
private static final Logger log = LogManager.getLogger(Client.class);
#Resource
private Region<String, String> myAdmin;
#PreDestroy
public void onDestroy() throws Exception {
log.info("onDestroy");
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Shutdown");
log.traceExit();
}
#Bean
ApplicationRunner StartedUp(){
log.traceEntry("StartedUp");
return args -> {
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Started");
log.traceExit();
};
}
// Required to resolve property placeholders in Spring #Value annotations.
#Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
log.traceEntry("propertyPlaceholderConfigurer");
return new PropertySourcesPlaceholderConfigurer();
}
}
In myPackage.Config
package myPackage;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
#Configuration
public class Config {
private static final Logger log = LogManager.getLogger(Config.class);
#Bean("myRegion")
public Region<String, Object> myRegion(GemFireCache cache) {
log.traceEntry();
Region<String, Object> r = cache.getRegion("myRegion");
r.setUserAttribute(ClientRegionShortcut.CACHING_PROXY);
return r;
}
}
In Config class while defining the bean you are using Region<String, Object> as return type. Where as in the your Client class you define Region<String, String>. Here it is clearly a type mismatch and hence bean will not load.

#EnableScheduling not being recognized and creating Executor service and running scheduled jobs

Trying to modify an application to have a #Component that has a scheduled task to fire every n seconds. It seems like the executor service is never getting started to recognized there are #Components that have a #Scheduled annotation. Any ideas?
Ensured the packages are correct and should be in the componentscan base package.
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* This is the Spring Boot class for the Data Consistency Model (DCM)
*/
#EnableScheduling
#SpringBootApplication
#EnableConfigurationProperties({KafkaConfig.class, SparkConfig.class, JedisConfig.class, PrometheusConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Component Class:
package com.test;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
#Component
#EnableScheduling
#EnableAsync
public class PrometheusGatewayMetricsPusher {
private static final Logger LOGGER = LogManager.getLogger(PrometheusGatewayMetricsPusher.class);
#Value("${spring.application.name}")
private String appName;
#Autowired
PushGateway pushGateway;
#Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void push() {
try {
pushGateway.push(CollectorRegistry.defaultRegistry, appName);
} catch (IOException e) {
LOGGER.log(Level.ERROR, "Error pushing to gateway. " + e.getMessage());
}
}
}
Config Class:
package com.test;
import io.prometheus.client.exporter.PushGateway;
import io.prometheus.client.hotspot.DefaultExports;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
#Getter
#Setter
#Configuration
public class MetricsConfig {
#Value("prometheus.config.gateway")
private String pushGatewayURL;
#PostConstruct
public void defaultExports() {
DefaultExports.initialize();
}
#Bean
public PushGateway pushGateway() {
return new PushGateway("localhost:9091");
}
}
I would expect the executor service to be started and initialized in the Application Context with a Thread Pool of 1. Then it would execute the #Scheduled method every second after an initial delay of 1 second. If I breakpoint in the #Component class it isn't being initialized at all.

Resources