Accessing a Spring Data REST API With Feign - spring-boot

I am trying to consume a Rest CRUD API with Feign Client.
I've added the HATEOAS dependency to the Client application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
And here is the Client Interface
#FeignClient(name="core-service")
#RibbonClient(name="core-service")
public interface VoteClient {
#RequestMapping(method = RequestMethod.GET, path = "/candidates")
Resources<Candidate> getCandidates();
#RequestMapping(method = RequestMethod.GET, path = "/candidates/{id}")
Resource<Candidate> getCandidate(#PathVariable("id") long id);
}
But Here I still have "Candidate cannot be resolved to a Type"
How can I do to read Candidate, which an Entity in the Rest Service, in the Rest Client ?

It's a Java compiler error. The client needs Candidate.java imported on the client. It can be fixed with "Fix Project Setup" on the IDE, or adding the library to the classpath and importing the relevant package.

Related

awspring SQS Configuration not working in Spring Boot Project

We are attempting to move away from spring cloud aws to the new io.awspring.cloud project. The documentation states:
The AmazonSQSAsync client is automatically created and passed to the template’s constructor based on the provided credentials.
I am attempting to run this locally. In my pom.xml I have added the dependency:
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-messaging</artifactId>
<version>${spring.cloud.aws}</version>
</dependency>
And I removed the code to create an AmazonSQSAsync client. As per the documentation, I still define a QueueMessagingTemplate
import io.awspring.cloud.messaging.core.QueueMessagingTemplate;
import com.amazonaws.services.sqs.AmazonSQSAsync;
#Bean
#Qualifier
public QueueMessagingTemplate queueMessagingTemplateFifoSupport(AmazonSQSAsync amazonSQSAsync,
ObjectMapper objectMapper) {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setSerializedPayloadClass(String.class);
converter.setObjectMapper(objectMapper);
QueueMessagingTemplate messagingTemplate = new QueueMessagingTemplate(amazonSQSAsync);
messagingTemplate.setMessageConverter(converter);
return messagingTemplate;
}
The package namespace was updated to use io.awspring. When running the app I get the error:
No qualifying bean of type 'com.amazonaws.services.sqs.AmazonSQSAsync' available
My belief is that Spring should supply this client automatically. Am I missing something?
In my application properties I have defined:
cloud.aws.credentials.access-key
cloud.aws.credentials.secret-key
cloud.aws.region.static
I was missing a dependency:
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-autoconfigure</artifactId>
<version>${spring.cloud.aws}</version>
</dependency>
which is necessary for automatic creation of default clients.
On a side note- best to avoid using this for now as you will be locked in to v1 of the Java AWS SDK until you can upgrade io.awspring to a version compatible with both a newer version of spring boot and aws

How to consume spring cloud config server Jdbc backend configs from Spring cloud Client server?

I went through lots of tutorials regarding this but could not get this done.
Here is my table structure for this.
Application Profile Label prop_key value
masking dev latest test-property message
I have a cloud config server which should integrate with JDBC backend. Here is my application.properties in config server
server.port=8082
spring.application.name=masking
management.endpoints.web.exposure.include=*
spring.datasource.url=jdbc:postgresql://localhost:8000/finos?currentSchema=xlabs
spring.datasource.username=mufgdev
spring.datasource.password=XXX
spring.profiles.active=XXX
spring.cloud.config.server.jdbc.sql=SELECT prop_key,value from xlabs.properties where application=? and profile=? and label=?
spring.cloud.config.server.jdbc.order=1
With this configs if I enter http://localhost:8082/masking/dev/latest response will show the results as I want.
I want to consume properties in client side with the following configs in bootstrap.properties
spring.application.name=masking
spring.cloud.config.uri=http://localhost:8082
spring.cloud.config.label=latest
spring.cloud.config.profile=dev
And in my client side
#RestController
#RefreshScope
public class TestController {
#Value("${test-property}")
private String aConf;
#GetMapping("/message")
String message() {
String name =aConf ;
return name;
}
}
This gives java.lang.IllegalArgumentException: Could not resolve placeholder 'test-property' in value "${test-property}"
Can anyone comment on this?
Thanks.
This issue comes with the latest Spring boot release, All the above code segments steps all okay, But by default Spring has disabled bootstrap. So you have to enable them by adding
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
No need add for older versions of the Spring boot projects.

Use Micrometer with OpenFeign in spring-boot application

The OpenApi documentation says that it supports micrometer. How does the integration works? I could not find anything except this little documentation.
I have a FeignClient in a spring boot application
#FeignClient(name = "SomeService", url = "xxx", configuration = FeignConfiguration.class)
public interface SomeService {
#GET
#Path("/something")
Something getSomething();
}
with the configuration
public class FeignConfiguration {
#Bean
public Capability capability() {
return new MicrometerCapability();
}
}
and the micrometer integration as a dependency
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-micrometer</artifactId>
<version>10.12</version>
</dependency>
The code makes a call but I could not find any new metrics via the actuator overview, expecting some general information about my HTTP requests. What part is missing?
Update
I added the support for this to spring-cloud-openfeign. After the next release (2020.0.2), if micrometer is set-up, the only thing you need to do is putting feign-micrometer onto your classpath.
Old answer
I'm not sure if you do but I recommend to use spring-cloud-openfeign which autoconfigures Feign components for you. Unfortunately, it seems it does not autoconfigure Capability (that's one reason why your solution does not work) so you need to do it manually, please see the docs how to do it.
I was able to make this work combining the examples in the OpenFeign and Spring Cloud OpenFeign docs:
#Import(FeignClientsConfiguration.class)
class FooController {
private final FooClient fooClient;
public FooController(Decoder decoder, Encoder encoder, Contract contract, MeterRegistry meterRegistry) {
this.fooClient = Feign.builder()
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(new MicrometerCapability(meterRegistry))
.target(FooClient.class, "https://PROD-SVC");
}
}
What I did:
Used spring-cloud-openfeign
Added feign-micrometer (see feign-bom)
Created the client in the way you can see above
Importing FeignClientsConfiguration and passing MeterRegistry to MicrometerCapability are vital
After these, and calling the client, I had new metrics:
feign.Client
feign.Feign
feign.codec.Decoder
feign.codec.Decoder.response_size

Issue in consuming Restful webserive using apache camel reslet framework

I have a Camel Project which runs in 8080 port to consume external restful web service which is a SpringBoot project which runs in port 8082, toproduce employee information based on the end point call. Here I'm trying to consume ResetFul webservice using Apache Camel Restlet. While consuming the webservice every alternative call is failing.
Restlet operation failed invoking http://localhost:8082/employeeController/getEmployeeDetails/12?wsdl with statusCode: 400 /n responseBody:<html><body><h1>400 Bad request</h1>Your browser sent an invalid request.</body></html>
This is the error i'm getting on every alternative call.
Restlet code to consume which is written inside Camel Context.
<to id="getEmployeeDetails" pattern="InOut" uri="restlet:http://localhost:8082/employeeManager/getEmployeeDetails/{employeeId}?restletMethod=GET"/>
SpringBoot code which produces webservice,
#Controller
#RequestMapping(value="employeeController")
public class EmployeeController{
#RequestMapping(value="/getEmployeeDetails/{employeeId}", method=RequestMethod.GET,produces=MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public String getEmployeeDetails(#PathVariable("employeeId") int employeeId) {
//getting the employee information from DB
}
}
The Camel Resetlet dependency added in pom.xml is
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-restlet</artifactId>
<version>2.24.1</version>
</dependency>>
Do i need add any other maven dependency in order to work for every endpoint call? Could you please help me here.
The easiest way to consume Restlet Resources is to use the Restlet HTTP Client:
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.httpclient</artifactId>
<version>2.4.0</version>
</dependency>
With a code similar to this:
Component c = new Component();
Client client = c.getClients().add(Protocol.HTTP);
client.getContext().getParameters().add ( "socketTimeout", "1000" );
Response resp = client.handle(new Request(Method.GET, "https://swapi.co/api/people/1/"));
System.out.println("Output: " + resp.getEntity().getText());

Metrics http_server_requests_seconds_count in spring boot application using cxf-spring-boot-starter-jaxrs contains uri as "UNKNOWN"

Metrics http_server_requests_seconds_count in Spring Boot application with version 2.0.8.Release exposed using spring actuator contains URI as:
"UNKNOWN".
Spring Boot application is using cxf-spring-boot-starter-jaxrs for exposing rest endpoints.
I have added micrometer-registry-prometheus dependency in my project.
http_server_requests_seconds_count{exception="None",method="POST",status="200",uri="UNKNOWN",} 2.0
I have tried adding micrometer-jersey2 dependency in my project.
Actual
http_server_requests_seconds_count{exception="None",method="POST",status="200",uri="UNKNOWN",} 2.0
Expected:
http_server_requests_seconds_count{exception="None",method="GET",status="200",uri="/sayHello",} 2.0
After the clarification in OP comments (CXF being another JAX-RS implementation): There's currently no support in Micrometer to handle CXF requests. It (Spring WebMvc) can't extract the optionally parameterized request url and in that case falls back to UNKNOWN. (Otherwise this could lead to a metrics explosion if your CXF endpoints provide some highly parameterizable URLs which get a lot of traffic.)
So you could have a look at the micrometer-jersey2 implementation and derive a micrometer-cxf implementation ;) (Or if not already the case (use the search) - open up an issue with the Micrometer or CXF project. I am mentioning the latter, because they might be interessted in taking care of that implementation.)
If you need cxf statistics for micrometer report, you can try
<dependency>
<groupId>io.github.kdprog</groupId>
<artifactId>cxf-micrometer-metrics</artifactId>
<version>1.0.0</version>
</dependency>
The following statistics will be reported
cxf_requests_processed_total - total number of cxf requests ,
cxf_requests_seconds_sum - total execution time of cxf requests,
cxf_requests_seconds_max - maximum execution time of cxf request,
cxf_requests_success_total - total number of successfully processed cxf requests,
cxf_requests_failed_total - total number of failed cxf requests
for each web service method of every client or server cxf endpoint.
For spring applications add the following bean to your application configuration.
#Bean
public FactoryBeanListener cxfMicrometerBean(final MeterRegistry registry) {
return new MicrometerFactoryBeanListener(registry);
}
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#actuator.metrics.supported
You can make custom tag provider to override it:
#Bean
WebMvcTagsProvider webMvcTagsProvider() {
return new DefaultWebMvcTagsProvider() {
#Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response,
Object handler, Throwable exception) {
return Tags.concat(
super.getTags(request, response, handler, exception),
Tags.of(Tag.of("uri",request.getRequestURI()))
);
}
};
}
More examples.
You can also collect cxf metrics for prometheus using io.github.ddk-prog:cxf-prometheus-metrics.
Add dependency to your pom.xml
<dependency>
<groupId>io.github.ddk-prog</groupId>
<artifactId>cxf-prometheus-metrics</artifactId>
<version>1.0.0</version>
</dependency>
and the following bean to your application configuration.
#Bean
public FactoryBeanListener cxfPrometheusFeatureBean(final CollectorRegistry registry) {
return new PrometheusFactoryBeanListener(registry);
}
You will get cxf_requests_total, cxf_requests_success, cxf_requests_failed, cxf_requests_seconds for each endpoint and operation in your spring boot actuator prometheus report.
For example,
cxf_requests_seconds{endpoint="server1",operation="server1Method",} 0.0157349
If you are using WebFlux on your project, you can make your custom tag provider by overriding:
#Bean
WebFluxTagsProvider webFluxTagsProvider() {
return new DefaultWebFluxTagsProvider() {
#Override
public Iterable<Tag> httpRequestTags(ServerWebExchange exchange, Throwable exception) {
return Tags.concat(super.httpRequestTags(exchange, exception), Tags.of(Tag.of("uri", exchange.getRequest().getPath().value())));
}
};
}
It works for me.

Resources