#Inject Twitter bean an connectionRepository issue - java

I'm developing an application which will get data from Twitter.
First I created an application.properties that contains the consumer ID and secret. Second I created a controller and injected Twitter and ConnectionRepository. I did everything as explained in the Spring Getting Started Guide
But I'm getting the error below.
#RestController
#RequestMapping("/api")
public class MarketDataResource {
private Twitter twitter;
private ConnectionRepository connectionRepository;
#Inject
public MarketDataResource(Twitter twitter, ConnectionRepository connectionRepository) {
this.twitter = twitter;
this.connectionRepository = connectionRepository;
}
#GetMapping("/market/data")
public String searchTweet (Model model) {
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
model.addAttribute(twitter.userOperations().getUserProfile());
CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
model.addAttribute("friends", friends);
return "hello";
}
}`
Error stack:
Parameter 0 of constructor in
fr.softeam.group.stockpicking.web.rest.data.MarketDataResource
required a bean of type
'org.springframework.social.twitter.api.Twitter' that could not be
found. Action: Consider defining a bean of type
'org.springframework.social.twitter.api.Twitter' in your
configuration.

Related

Vaadin hilla property call does not exist

I was trying to create a vaadin hilla application, trying to save a person's details. Created endpoint and the person object as well, but in generated files, the error is showing as below.
[TypeScript] Property 'call' does not exist on type 'PersonDetails'.
The application is running, pages also came up but with error.
#Endpoint
#AnonymousAllowed
public class PersonEndpoint {
private InterPersonService personService;
#Autowired
public PersonEndpoint(InterPersonService personService) {
this.personService = personService;
}
#Nonnull
public String savePerson(PersonDetails person) {
return this.personService.savePerson(person);
}
}
Vaadin hilla application to save a person's details. Expected to set the value from the textbox to the generated object and the data will be available in the endpoint save method.

How to prevent Thymeleaf Template Engine read path URL Get Mapping as a template engine name in Spring Boot

I have a controller get mapping which read path variable to return object from repository, and return template engine name using Thymeleaf to show it, and it works well in localhost with postman and browser:
#Controller
public class InvoiceFormController {
#Autowired
InvoiceDetailRepository invoiceDetailRepository;
#Autowired
InvoiceService invoiceService;
#GetMapping("/supermarket/invoice/{id}")
public String getInvoiceView(#PathVariable("id") UUID id, Model model) {
InvoiceDetail invoiceDetail = invoiceDetailRepository.getInvoiceDetailById(id);
if(invoiceDetail == null) {
return invoiceService.showError(model);
}
return invoiceService.showDetail(invoiceDetail, model);
}
}
this is the service:
#Service
public class InvoiceService {
public Spring showDetail(InvoiceDetail invoiceDetail, Model model) {
model.addAttribute("invoiceDetail", invoiceDetail);
return "invoicePage";
}
public Spring showError(Model model) {
model.addAttribute("error", "not found");
return "errorPage";
}
}
But, when I creating the unit test, it always became error, because the path url get mapping always read by Spring Boot as template engine name:
ERROR org.thymeleaf.TemplateEngine -[THYMELEAF][main] Exception processing template "supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067": Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers
the unit test is looks like this:
#WebMvcTest(InvoiceFormController.class)
class InvoiceFormControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
InvoiceDetailRepository invoiceDetailRepository;
#MockBean
InvoiceService invoiceService;
#Mock
Model model;
#Test
void testViewSuccess() throws Exception {
InvoiceDetail invoiceDetail = InvoiceDetail.builder().id(UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068").build();
UUID id = UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068");
Mockito.when(invoiceDetailRepository.getInvoiceDetailById(id))
.thenReturn(invoiceDetail);
Mockito.when(invoiceService.showDetail(invoiceDetail, model))
.thenReturn("invoicePage");
mockMvc.perform(MockMvcRequestBuilders.get("/supermarket/invoice/"+"d5afd278-db7c-4482-b992-c7440b522068"))
.andExpect(MockMvcResultMatchers.status().isOk());
.andExpect(MockMvcResultMatchers.view().name("invoicePage"));
}

Unable to refresh existing singleton bean in Spring boot application

I have a configuration defined in my spring boot applocation as follows:
#Configuration
public class RuleEngineConfiguration {
private final DatabaseRuleLoader databaseRuleLoader;
public RuleEngineConfiguration(
DatabaseRuleLoader databaseRuleLoader) {
this.databaseRuleLoader = databaseRuleLoader;
}
#Bean
public RuleEngineManager ruleEngine() {
return RuleEngineManagerFactory.getRuleEngineManager(this.databaseRuleLoader);
}
Now I would like to refresh RuleEngineManager bean in my spring boot application on creating/update of a row in a given table in DB with refresh function as defined below:
public void refresh() {
databaseRuleLoader.refresh(); <---THIS RELOADS ROWS FROM DB
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext
.getAutowireCapableBeanFactory();
RuleEngineManager ruleEngineManager = RuleEngineManagerFactory
.getRuleEngineManager(databaseRuleLoader);
registry.removeBeanDefinition("ruleEngine");
((SingletonBeanRegistry) registry).registerSingleton("ruleEngine", ruleEngineManager);
}
And in my application, where I need RuleEngineManager bean, I am getting the bean as follows:
((RuleEngineManager) applicationContext.getBean("ruleEngine"))
Even though the refresh function is getting executed every time, I am creating/updating any rows in DB, but, I am not seeing any changes. It seems the existing RuleEnginemanager bean is getting injected as a dependency. I am not able to figure out what I am missing here.
Could anyone please help here? Thanks.
What I was suggesting is to use a factory (design pattern)... for example in this way:
// you already have this class
public class RuleEngineManagerFactory{
private DatabaseRuleLoader databaseRuleLoader;
private RuleEngineManager ruleEngineManager;
public RuleEngineManagerFactory(DatabaseRuleLoader databaseRuleLoader) {
this.databaseRuleLoader = databaseRuleLoader;
}
public RuleEngineManager getRuleEngineManager(){
if(this.ruleEngineManager == null){
ruleEngineManager = new RuleEngineManager(this.databaseRuleLoader);
}
return this.ruleEngineManager;
}
public void refresh(){
ruleEngineManager = new RuleEngineManager(this.databaseRuleLoader);
}
}
In this way, you will inject RuleEngineManagerFactory wherever you need, and you can refresh the RuleEngineManager... so you will have to have a singleton for the factory of the manager, and not for the manager itself

Micronaut #Refreshable not working as expected

I'm trying to set up a micronaut service with a Consul configuration. When the service starts it successfully initializes the property of the bean with the value provided from the key-value store. However it doesn't reload when the value changes, even if the refresh is triggered manually.
Here's the bean:
#Refreshable
public class ConfigBean {
#Property(name = "welcome-message")
private String message = "doe!";
#PostConstruct
public void init() {
String text = this + "Scattered Clouds " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yy HH:mm.ss.SSS"));
System.out.println(text + "\r\n" + this.message);
}
}
And here is the simple controller endpoint:
#Controller("/p")
public class Controller {
#Inject
ApplicationContext applicationContext;
#Inject
private ConfigBean config;
#Get("/r")
#Produces(MediaType.TEXT_PLAIN)
public String refresh() {
applicationContext.publishEvent(new RefreshEvent());
return "Hello World";
}
#Get("/m")
#Produces(MediaType.TEXT_PLAIN)
public String message() {
return config.getMessage();
}
}
With this code what happens is
value is successfully resolved from config store and shown when navigating to localhost:8080/p/m
when getting localhost:8080/p/r for manual refresh interestingly enough the init() method of the config bean is called but the value in the message attribute is not updated
What is needed to re-trigger the update of the bean? Is there maybe an implicit call that can be used to purge a config-cache so it is fetched again?
The documentation is a bit sparse about this (Version 2.2.0 was used), thanks in advance!

Convert legacy code to Spring dependency injection

The legacy code snippet is shown as below. What I want to do is to convert this code to Spring. But the problem is Spring managed the dependency on it's own. My question is how to inject the serviceId provided by constructor?
public class MyService{
public Attribute getAttribute(){
int serviceId =1;
new ServiceDao(serviceId).getAttribute();
}
}
class ServiceDao{
private int serviceId;
ServiceDao(int serviceId){
this.serviceId = serviceId;
}
public Attribute getAttribute(){
//to get attribute
}
}
Basically you are trying to create new objects each time you call
new ServiceDao(serviceId).getAttribute();
This is purely against dependency injection. As your logic is based on the service ID you can create a service class as follows
#Service
class ServiceDao{
ServiceDao(){
}
public Attribute getAttribute(int serviceId){
//to get attribute
//return attribute based on service Id,
//if(serviceId==1)
//{ return new Attribute("Red");}
}
}
Your Myservice can be something like this
#Service
public class MyService{
#Autowired
ServiceDao dao;
public Attribute getAttribute(){
int serviceId =1;
return dao.getAttribute(1);
}
}

Categories