I need to catch response from SOAP webservice I'm calling.
I've implemented interceptor as described here to catch the incoming message:
client.getInInterceptors().add(new MyInterceptor());
the class is like the following:
public class MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
public MyInterceptor() {
super(Phase.POST_LOGICAL_ENDING);
}
#Override
public void handleMessage(final SoapMessage message) throws Fault {
// Do stuff
}
}
It is on POST_LOGICAL_ENDING phase, but the issue is that handleMessage () is not being called.
We have similar interceptor on outgoing message catching PRE_PROTOCOL_ENDING which works perfectly fine with the service.
What did I miss?
Should I use different phase?
I guess you have to add this interceptor to the out* -> getOutInterceptors()
Related
I am using OpenFeign client in Spring Boot without using Ribbon or Eureka. I created a custom error decoder which handles response errors as intended but connection refused errors seem to bypass my custom decoder.
P.S. When my remote service is up, I can make requests and receive responses.
I am new to Java and Spring and I am wondering if I need to wrap all my calls with try catch, or adding my custom error handler should be catching the error since it seems cleaner to handle all errors in one place
public class FeignErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultErrorDecoder = new Default();
#Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() <= 499) {
//handle with custom exception
}
if (response.status() >=500) {
//handle with custom exception
}
return defaultErrorDecoder.decode(methodKey, response);
}
}
#Configuration
public class FeignConfig {
//other beans here
#Bean
public ErrorDecoder feignErrorDecoder() {
return new FeignErrorDecoder();
}
}
I have implemented a REST endpoint in JavaEE that fires an asynchronous event to trigger a process each time the endpoint is used by a user.
This all works as intended and the process is triggered asynchronously, but results in a SEVERE level log: No valid EE environment for injection of TagsProcessor and I do not understand why.
Is this a bug in Payara? Or am I doing something wrong?
Here is an example implementation:
Rest endpoint where the event is fired on each login:
#Path("auth")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#RequestScoped
public class AuthenticationResource {
#POST
#Path("request-jwt")
#PermitAll
#Timed(name = "appV2RequestJwt", absolute = true)
public Response appRequestJwt(RefreshRequest refreshRequest) {
JwtResponse dto;
try {
dto = authenticationProcessor.appRequestJwt(refreshRequest);
//Fire asynchronous event
calculateTagsEvent.fireAsync(new CalculateTagsEvent(refreshRequest.getUsername()));
return Response.ok(dto).build();
} catch (Exception exception) {
LOGGER.log(Level.SEVERE, "Could not request jwt: {}", exception.getMessage());
dto = new JwtResponse(null, INTERNAL_SERVER_ERROR);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(dto).build();
}
}
}
Observer class:
#RequestScoped
public class TagsProcessor {
private static final Logger LOGGER = Logger.getLogger(TagsProcessor.class.getName());
#Inject
private BeanController beanController;
//Observe asynchronous event
public void manageCalculateTagsEvent(#ObservesAsync CalculateTagsEvent event) {
LOGGER.log(Level.WARNING, "Event observed");
beanController.create(new SomeBean());
}
}
This results in the logs:
[#|2022-08-17T06:39:39.461+0000|SEVERE|Payara 5.201||_ThreadID=473;_ThreadName=payara-executor-service-task;_TimeMillis=1660718379461;_LevelValue=1000;| No valid EE environment for injection of TagsProcessor|#]
[#|2022-08-17T06:39:39.473+0000|WARNING|Payara 5.201|TagsProcessor|_ThreadID=473;_ThreadName=payara-executor-service-task;_TimeMillis=1660718379473;_LevelValue=900;| Event observed|#]
So it's working as intended, but is giving me the warning about the injection...
As mentioned in my comment I did try various scopes but in the end it's supposed to be a #Stateless EJB that can be spawned from a pool without being attached to the client's state.
Camel has to call REST service for some integration, However, the REST service has one authentication api (POST api) which needs to be called first to get a token and then other subsequent api calls has to be invoked with the token embedded in header of HTTP requests.
Does Spring Restemplate or apache camel has some api to support the same?
Followed #gusto2 approach, Its pretty much working fine.
SO, I created two routes --> First one is a timer based like below, this generates the token, periodically refreshes it(since the route is timer based) and stores the token in a local variable for being reused by some other route.
#Component
public class RestTokenProducerRoute extends RouteBuilder {
private String refreshedToken;
#Override
public void configure() throws Exception {
restConfiguration().producerComponent("http4");
from("timer://test?period=1200000") //called every 20 mins
.process(
exchange -> exchange.getIn().setBody(
new UserKeyRequest("apiuser", "password")))
.marshal(userKeyRequestJacksonFormat) //convert it to JSON
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.to("http4://localhost:8085/Service/Token")
.unmarshal(userKeyResponseJacksonFormat)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
UserKeyResponse response= exchange.getIn().getBody(
UserKeyResponse.class); //get the response object
System.out.println(response + "========>>>>>>" +
response.getResult());
setRefreshedToken(response.getResult()); //store the token in some object
}
}).log("${body}");
}
public String getRefreshedToken() {
return refreshedToken;
}
public void setRefreshedToken(String refreshedToken) {
this.refreshedToken = refreshedToken;
}
}
And the second route can call subsequent apis which will use the token generated by the first route, it would be something like this. Have to add error handling scenarios, where token might not be valid or expired. But I guess that would be separate concern to solve.
#Component
public class RestTokenUserOnboardRoute extends RouteBuilder {
private JacksonDataFormat OtherDomainUserRequestJacksonFormat = new JacksonDataFormat(
OtherDomainUserRequest.class);
private JacksonDataFormat OtherDomainUserResponseJacksonFormat = new JacksonDataFormat(
OtherDomainUserResponse.class);
#Override
public void configure() throws Exception {
restConfiguration().producerComponent("http4");
//This route is subscribed to a Salesforce topic, which gets invoked when there is any new messages in the topic.
from("salesforce:CamelTestTopic?sObjectName=MyUser__c&sObjectClass="+MyUser__c.class.getName()))
.convertBodyTo(OtherDomainUserRequest.class)
.marshal(OtherDomainUserRequestJacksonFormat).log("${body}")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.log("The token being passed is ==> ${bean:tokenObj?method=getRefreshedToken}")
.setHeader("Authorization", simple("${bean:tokenObj?method=getRefreshedToken}"))
.to("http4://localhost:8085/Service/DomainUser")
.unmarshal(OtherDomainUserResponseJacksonFormat)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
OtherDomainUserResponse response = exchange.getIn().getBody(
OtherDomainUserResponse.class);
System.out.println(response + "==================>>>>>> " + response.getStatusCode());
}
}).log("${body}");
}
}
So, here the token is getting consumed from the tokenObj bean (instance of RestTokenProducerRoute which has method getRefreshedToken() defined. It returns the stored token.
Needless to say, you have set the bean in camelcontext registry as follows along with other settings (like component, route etc). In my case it was as follows.
#Autowired
public RestTokenUserOnboardRoute userOnboardRoute;
#Autowired
public RestTokenProducerRoute serviceTokenProducerRoute;
#Autowired
private RestTokenProducerRoute tokenObj;
#Override
protected CamelContext createCamelContext() throws Exception {
SimpleRegistry registry = new SimpleRegistry();
registry.put("tokenObj", tokenObj); //the tokenObj bean,which can be used anywhere in the camelcontext
SpringCamelContext camelContext = new SpringCamelContext();
camelContext.setRegistry(registry); //add the registry
camelContext.setApplicationContext(getApplicationContext());
camelContext.addComponent("salesforce", salesforceComponent());
camelContext.getTypeConverterRegistry().addTypeConverter(DomainUserRequest.class, MyUser__c.class, new MyTypeConverter());
camelContext.addRoutes(route()); //Some other route
camelContext.addRoutes(serviceTokenProducerRoute); //Token producer Route
camelContext.addRoutes(userOnboardRoute); //Subsequent API call route
camelContext.start();
return camelContext;
}
This solves my problem of setting token dynamically where token is getting produced as a result of execution of some other route.
I have a simple client using RESTEasy as follows:
public class Test {
public static void main(String[] args) {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost");
client.register(new MyMapper());
MyProxy proxy = target.proxy(MyProxy.class);
String r = proxy.getTest();
}
}
public interface MyProxy {
#GET
#Path("test")
String getTest();
}
#Provider
public class MyMapper implements ClientExceptionMapper<BadRequestException>{
#Override
public RuntimeException toException(BadRequestException arg0) {
// TODO Auto-generated method stub
System.out.println("mapped a bad request exception");
return null;
}
}
The server is configured to return a 400 - Bad Request on http://localhost/test along with a helpful message. A BadRequestException is being thrown by ClientProxy. Other than wrapping in try/catch, how can I make getTest() catch the exception and return the Response's helpful message as a string. I tried various ClientExceptionMapper implementations, but just can seem to get it right. The above code doesn't ever call toException. What am I missing here?
My current work-around is to use a ClientResponseFilter and then do a setStatus(200) and stuff the original status in the response entity. This way I avoid the exception throws.
ClientExceptionMapper in Resteasy is deprecated (see java docs)
The JAX-RS 2.0 client proxy framework in resteasy-client module does
not use
org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper.
Try with an ExceptionMapper like this:
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class MyMapper implements ExceptionMapper<ClientErrorException> {
#Override
public Response toResponse(ClientErrorException e) {
return Response.fromResponse(e.getResponse()).entity(e.getMessage()).build();
}
}
Regards,
I'd advise going through the Jax-RS client API unless there's a functionality you need using the RestEasy clients. (RestEasy ships with Jax-RS, so there's no library differences)
Client client = ClientFactory.newClient();
WebTarget target = client.target("http://localhost/test");
Response response = target.request().get();
if ( response.getStatusCode() != Response.Status.OK.getStatusCode() ) {
System.out.println( response.readEntity(String.class) );
return null;
}
String value = response.readEntity(String.class);
response.close();
The reason why your mapper does not work is because the client is not actually throwing the exception. The client is returning a valid result to the proxy, and the proxy is reading that, and throwing the exception, which happens after the mapper can intercept it.
Here is my fault interceptor:
public class OutFaultInterceptor extends AbstractPhaseInterceptor<Message> {
public OutFaultInterceptor() {
super(Phase.SEND);
}
#Override
public void handleMessage(Message message) throws Fault
{
Fault fault = (Fault)message.getContent(Exception.class);
Throwable ex = fault.getCause();
Response response = JAXRSUtils.convertFaultToResponse(ex, message);
message.setContent(Response.class, response);
}
}
Here is my relevant cxf-config:
<jaxrs:outFaultInterceptors>
<bean id="outfault" class="com.xxx.OutFaultInterceptor"/>
</jaxrs:outFaultInterceptors>
I can get into the handleMessage method no problem, but I'm not able to modify the message.
Currently what it returns is the default: ns1:XMLFault blah blah...
What I want to return is a Response object that has a proper HTTP response code and a json body (which I correctly have in my response variable above).
Thanks
If you're using JAX-RS, why not setup an exception mapper, and then use that mapper to handle the response.
A simple example:
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class MyExceptionMapper implements
ExceptionMapper<MyException> {
#Override
public Response toResponse(MyException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
Then you would need to register the provider in the jaxrs serve by adding:
<jaxrs:providers>
<bean class="com.blah.blah.blah.blah.MyExceptionMapper"/>
</jaxrs:providers>
in the server config in the context. With that you have full access to the exception, and can get whatever you want from it.