Solr Spring boot application failed to run, giving bean error - java

Getting an error while running , a solr spring boot application, it says
"Parameter 0 of constructor in Controller required a bean of type Repository that could not be found."
"Consider defining a bean of type Repository in your configuration."
Here is my enitiy
#SolrDocument(collection = "content_core")
public class ContentDoc {
#Id
#Indexed
private String id;
#Indexed(name = "display_title", type = "string")
private String displayTitle;
}
Here is my solr config file
#EnableSolrRepositories(basePackages = "com.baeldung.repository.ContentDocRepository.spring.data.solr.repository", namedQueriesLocation = "classpath:solr-named-queries.properties")
#ComponentScan
public class SolrConfig {
#Bean
public SolrClient solrClient() {
return new HttpSolrClient.Builder("http://localhost:8983/solr").build();
}
#Bean
public SolrTemplate solrTemplate(SolrClient client) throws Exception {
return new SolrTemplate(client);
}
}
Here is my controller
#RequestMapping("/api/v1/content")
#AllArgsConstructor
#Slf4j
public class ContentDocController {
private final ContentDocRepository contentDocRepository;
#GetMapping("/searchfaq")
public Map<String, Object> searchFaq(#RequestParam("sectionId") Long sectionId,
#RequestParam("seachTerm") String searchTerm) {
// ContentDoc contentDoc = new ContentDoc();
// contentDoc.setContentId((long)1);
// contentDoc.setDisplayTitle("virat");
// contentDocRepository.save(contentDoc);
return null;
}
}
Here is my repository
#Qualifier("contentDocRepository")
public interface ContentDocRepository extends SolrCrudRepository<ContentDoc, String> {
public List<ContentDoc> findByName(String displayTitle);
}
this is the error that I am getting ->
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-10-20 18:22:47.836 ERROR 2760 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
*********
APPLICATION FAILED TO START
*********
Description:
Parameter 0 of constructor in com.aa.aa.controller.ContentController required a bean of type 'com.aa.aa.repository.ContentDocRepository' that could not be found.
Action:
Consider defining a bean of type 'com.aa.aa.repository.ContentDocRepository' in your configuration.
I am trying to create an an api which searches data from DB , and using solr to index the db data.
I am following this page -> https://www.baeldung.com/spring-data-solr

Related

How create unit test in Spring REST in POST Cotroller

I have a Spring Boot Controller with POST. Method works fine. I tested it by POSTMAN and from postgresql I recieved JSON. But I need test it.
#RestController
#RequestMapping("/api")
public class FamilyController {
private final FamilyService familyService;
public FamilyController(FamilyService familyService) {
this.familyService = familyService;
}
#GetMapping("/getFamily/{familyId}")
public List<FamilyMember> getFamily(#PathVariable Integer familyId) {
return familyService.searchFamilyMember(familyId);
}
}
I created test:
#ExtendWith(SpringExtension.class)
#WebMvcTest(FamilyController.class)
class FamilyControllerTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private FamilyService service;
#Captor
private ArgumentCaptor<Family> argumentCaptor;
#Test
void createFamily() throws Exception {
Family family = new Family();
family.setId(1);
family.setFamilyName("Kowal");
family.setNrOfInfants(2);
family.setNrOfChildren(2);
family.setNrOfAdults(1);
Mockito.when(service.saveAndFlush(argumentCaptor.capture())).thenReturn(1);
mockMvc.perform(post("/api/createFamily")
.contentType(MediaType.APPLICATION_JSON)
.contentType(objectMapper.writeValueAsString(family)))
.andExpect(status().isCreated());
// .andExpect(header().exists("Location"))
// .andExpect(header().string("Location", "http://localhost/api/getFamily/1"));
assertThat(argumentCaptor.getValue().getFamilyName(), is("Kowal"));
}
when I run a test, I received error like below:
WARN 15404 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException:
Invalid mime type "{"id":1,"familyName":"Kowal","nrOfInfants":2,"nrOfChildren":2,"nrOfAdults":1,"familyMembers":[]};charset=UTF-8":
does not contain '/']
What am I doing wrong?
The problem is this line:
.contentType(objectMapper.writeValueAsString(family)))
Right now you are sending the object in the content-type header, that's why you get the error message.
Change it to:
.content(objectMapper.writeValueAsString(family)))

Parameter 0 of constructor in RestAuditFilterConfiguration required a single bean, but 2 were found:

I have the following Spring Service:
Interface copied from external jar:
public interface Masker {
String maskContent(String contentType, String content);
Map<String, List<String>> maskHeaders(Map<String, List<String>> headers);
}
Implementation:
#Service
public class MaskerImpl implements Masker {
private final List<String> maskers;
private final String headerMasker;
public MaskerImpl(List<String> maskers, String headerMasker) {
Collections.sort(maskers, AnnotationAwareOrderComparator.INSTANCE);
this.maskers = maskers;
this.headerMasker = headerMasker;
}
#Override
public String maskContent(String contentType, String content, String messageType) {
return content;
}
#Override
public Map<String, List<String>> maskHeaders(Map<String, List<String>> headers) {
return null;
}
}
Config:
#EnableConfigurationProperties(MaskerProperties.class)
public class MaskerConfiguration {
#Bean
Masker externalMasker(List<String> maskers, String headerMasker) {
return new MaskerImpl(maskers, headerMasker);
}
}
Small code example: https://github.com/rcbandit111/hateos_poc/tree/main/src/main/java/com/hateos/test/impl
But when I start the code I get error:
01:23:38.682 [main] DEBUG Reporter[report:37] - Application failed to start due to an exception
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.test.Masker' available: expected single matching bean but found 2: maskerImpl,externalMasker
Parameter 0 of constructor in com.test.RestAuditFilterConfiguration required a single bean, but 2 were found:
- maskerImpl: defined in URL [jar:file:/C:/Users/....../MaskerImpl.class]
- externalMasker: defined by method 'externalMasker' in com......MaskerConfiguration
Do you know how I can fix this issue?
Because you have defined 2 Masker bean, when you deploy your application, the Spring IoC container is confused which bean you are trying to autowire.
You can simply use #Qualifier into your class to specify your bean, like this:
#Component
public class YourClass {
#Autowired
#Qualifier("externalMasker")
private Masker externalMasker;
// or
#Autowired
#Qualifier("maskerImpl")
private Masker maskerImpl;
}

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"));
}

NullPointerException using Spring Boot JPA when trying to save to database

I am planning to play around with some trading data, and made a request to retrieve some markets data that I wish to store in mysql.
Since yesterday I have been stuck on a NullPointerException in my code. On StackOverflow I often see the error to be of trying to instantiate the Service for example, or forgotten annotations.
For me it seems to be going wrong whenever I try to use the Autowired Service. I invoke the method (that makes the data request in the Controller) from the main method for now. This does mean I have to instantiate in order to get there. This is probably where it goes wrong. I might be missing the concept of how to deal with this properly or how to save my data to the DAO. Hope someone can steer me in the right direction.
See the code below:
#SpringBootApplication
public class DesktopAutoTradingApplication {
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(DesktopAutoTradingApplication.class, args);
MarketsBinanceController marketsBinanceController = new MarketsBinanceController();
marketsBinanceController.saveListOfMarketsBinance();
}
#Controller
public class MarketsBinanceController{
#Autowired
RequestServices requestService;
public void saveListOfMarketsBinance() throws JsonProcessingException {
String resourceURL;
RestTemplate restTemplate = new RestTemplate();
ObjectMapper mapper = new ObjectMapper();
ResponseEntity<String> response;
MarketsBinance marketsBinance;
resourceURL = "https://api.cryptowat.ch/markets/binance";
response = restTemplate.getForEntity(resourceURL, String.class);
JsonNode root = mapper.readTree(response.getBody());
JsonNode result = root.get("result");
System.out.println(result);
List<MarketsBinance> markets = new ArrayList<>();
for(JsonNode item : result){
marketsBinance = new MarketsBinance();
MarketsBinanceDto marketsBinanceDto;
marketsBinanceDto = mapper.treeToValue(item,MarketsBinanceDto.class);
marketsBinance.setId(marketsBinanceDto.getId());
marketsBinance.setExchange(marketsBinanceDto.getExchange());
marketsBinance.setPair(marketsBinanceDto.getPair());
marketsBinance.setActive(marketsBinanceDto.getActive());
marketsBinance.setRoute(marketsBinanceDto.getRoute());
markets.add(marketsBinance);
requestService.saveMarketsBinance(markets);
}
}
}
#Service
#Transactional
public class RequestServices {
#Autowired
private MarketsBinanceDAO marketsBinanceDAO;
public void saveMarketsBinance(List<MarketsBinance> markets){
marketsBinanceDAO.saveAll(markets);
}
}
#Component
public interface MarketsBinanceDAO extends CrudRepository<MarketsBinance, Long> {
}
#Entity
public class MarketsBinance {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long tableId;
private Long id;
private String exchange;
private String pair;
private Boolean active;
private String route;
//getters and setters
public class MarketsBinanceDto {
private Long id;
private String exchange;
private String pair;
private Boolean active;
private String route;
//getters and setters
Exception in thread "main" java.lang.NullPointerException
at Controller.MarketsBinanceController.saveListOfMarketsBinance(MarketsBinanceController.java:46)
at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:16)
Below you find the error message received upon running the program adding the proposed solution in the first answer.
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'Controller.MarketsBinanceController' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:352)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:343)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127)
at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:15)
2020-09-07 12:24:03.545 INFO 22756 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-07 12:24:03.553 INFO 22756 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
You should use bean of type MarketsBinanceController that Spring created and configured instead of MarketsBinanceController marketsBinanceController = new MarketsBinanceController();.
To get this bean in main method you should get ApplicationContext. ApplicationContext you can get as returned object from SpringApplication.run(DesktopAutoTradingApplication.class, args);.
Complete code example:
ConfigurableApplicationContext context = SpringApplication.run(DesktopAutoTradingApplication.class, args);
MarketsBinanceController marketsBinanceController = context.getBean(MarketsBinanceController.class);
marketsBinanceController.saveListOfMarketsBinance();

#Inject Twitter bean an connectionRepository issue

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.

Categories