How to handle timeout exception in quarkus? - exception

I am trying to connect to a third-party API from quarkus controller . I have a controller using the method of service. The try catch block is not working.I have all the required dependency and i followed quarkus doc
Here is the code
Controller
package com.ncr.invoice;
// all imports over here
#Path("/api")
#RequestScoped
public class InvoiceController {
// all variable and injection
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/invoice")
#Timeout(250)
#PermitAll
public Response getInvoice(AuthTokenRequestModel atrm){
SoupResponseInvoiceDetail srid = null;
try{
srid = service.getInvoice(
atrm.getMcn(),"transactionId", atrm.getInvoiceNumber()
);
LOG.info("try block end");
}
catch(InterruptedException e)
{
LOG.info("Over here");
return Response.status(401).build();
}
return Response.ok(srid).build();
}
return Response.status(401).build();
}
// all getter setter
}
service
package com.ncr.invoice;
//all imports
#Path("/")
#RegisterRestClient(configKey="invoice-api")
#ClientHeaderParam(name = "Authorization", value = "{basicAuth}")
public interface InvoiceService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/")
public SoupResponseInvoiceDetail getInvoice(#QueryParam("id") String id,#QueryParam("txn_id") String txnId, #QueryParam("invoice") String invoice) throws InterruptedException;
default String basicAuth() {
String uName = ConfigProvider.getConfig().getValue("auth.username", String.class);
String pwd = ConfigProvider.getConfig().getValue("auth.pwd", String.class);
String creds = uName + ":" + pwd;
return "Basic " + Base64.getEncoder().encodeToString(creds.getBytes());
}
}
Error that i am getting
2021-01-07 13:07:42,286 INFO [com.ncr.inv.InvoiceController] (executor-thread-189) try block end
2021-01-07 13:07:42,555 ERROR [io.und.req.io] (executor-thread-189) Exception handling request 58a6d4b3-76c1-4a8b-b4a0-1e241219fb4d-4 to /api/invoice: org.jboss.resteasy.spi.UnhandledException: org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException: Timeout[com.ncr.invoice.InvoiceController#getInvoice] timed out
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:218)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:519)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
.........................................

To me it look like you need to need to do something like this:
#Provider
public class TimeoutExceptionMapper implements ExceptionMapper {
private static final Logger LOGGER = LoggerFactory.getLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
#Override
public Response toResponse(TimeoutException exception) {
LOGGER.warn(exception.getMessage());
return getResponse();
}
public static Response getResponse() {
ErrorResponse response = new ErrorResponse();
response.setDescription("Operation timet out, try again later");
return status(Response.Status.GATEWAY_TIMEOUT).entity(response).build();
}
}

Related

How to marshal to JSON/XML when an exception occurs with Camel rest-dsl

I have a REST-dsl camel route with binding: json_xml
with .type() and outType(). It works perfectly when no exception occurs. That is json input gives json output. Xml input gives xml output.
However, when I get an IllegalArgumentException I always return XML. I create a ErrorResponse POJO when the exception occurs. The CONTENT_TYPE is set to "application/json" for json. How do I return a POJO and let camel marhal to JSON/XML when an Exception occurs(given ResBindingMode.json_xml)?
onException(IllegalArgumentException.class)
.log(LoggingLevel.ERROR, LOGGER, "error")
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setHeader(Exchange.CONTENT_TYPE, exchangeProperty(Exchange.CONTENT_TYPE))
.bean(errorResponseTranslator);
restConfiguration().component("restlet").port(port).skipBindingOnErrorCode(true)
.bindingMode(RestBindingMode.json_xml);
rest("/whatever/api/v1/request")
.post().type(RequestDto.class).outType(ResponseDto.class)
.route()
.setProperty(Exchange.CONTENT_TYPE, header(Exchange.CONTENT_TYPE))
...process
ErrorDto:
#XmlRootElement(name = "errorResponse")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class ErrorResponseDto {
private String errorCode;
private String message;
#XmlElement(name = "message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#XmlElement(name = "errorCode")
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
You need to set the content type explicit to XML then
.setHeader(Exchange.CONTENT_TYPE, exchangeProperty(Exchange.CONTENT_TYPE))
Should be
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
The error occurs because the outType not dynamic. It seems like its a camel bug. That is: the outType must be an XMLROOT that contains OK and ERROR dto. It is possible to quickfix this if you use a XMLroot that takes an any element with lax=true(here you can add the ErrorDto or okResponseDto). But it does add an unwanted element. For now we have to implement a custom contentNegotiator.
This is when using skipBindingOnError is set to false.

Add java List in JsonObject return value

I want to add a list in the json return value. Here is my code -
#RequestMapping(value = "/servicearea", produces="application/json")
#ResponseBody
public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
{
List<ServiceArea> serviceLists = locationService.getAllServiceArea();
JsonObject result = Json.createObjectBuilder()
.add("message", "test")
.add("serviceLists", serviceLists)
.build();
return result.toString();
}
'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.
Thanks in advance.
Just create a pojo like this
class ReturnPojo {
private String message;
private List<ServiceArea> serviceLists;
//getters and setters
}
And from your controller you can do
ReturnPojo returnPojo = new ReturnPojo;
returnPojo.setMessage("test");
returnPojo.setServiceLists(serviceLists);
return returnPojo;
Change the method signature to return ReturnPojo
Below solution is only useful if you are using Rest API and Spring.
create class ServiceListPojo:
public class ServiceListPOJO{
List<ServiceArea> serviceLists;
public void setServiceLists(List<ServiceArea> serviceLists){
this.serviceLists = serviceLists;
}
}
Annotate your controller with #RestController
#RestController
public class SomeController{
#RequestMapping(value = "/servicearea")
public ServiceListPOJO ServiceArea()
{
List<ServiceArea> serviceLists = locationService.getAllServiceArea();
ServiceListPOJO slp = new ServiceListPOJO();
slp.setServciceLists(serviceLists);
return slp;
}
}

Spring RESTful Date format

A rest controller in jdk8 like this
#Transactional
#RequestMapping(value="/A", method = RequestMethod.POST)
public ABean aInsert(final java.sql.Date when, final long company) {
A bean = new A();
bean.setWhen(when);
bean.setCompany(entityManager.find(Company.class, company));
entityManager.persist(bean);
return new ABean(bean.getId(), bean.getVersion(), bean.getWhen(), bean.getCompany().getId());
}
is called with form post-data
when=1459987200000&company=1
but can not be called and returns a 400 - bad request
(description The request sent by the client was syntactically incorrect.).
My question is:
What is the default input string format of the java.sql.date?
when=2016-04-21&company=10 Works, so its
yyyy-mm-dd
For every other format register a custom Converter like this:
#Autowired
private final ConfigurableConversionService conversionService=null;
#PostConstruct
public void registerConverter() {
conversionService.addConverter(new Converter<String, Long>() {
#Override
public Long convert(String source) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm");
return df.parse(source).getTime();
} catch (ParseException e) {
return Long.parseLong(source);
}
}
});
}

sending arraylist from a rest service

I am new to webservices and also REST. I am trying to send a message as a post request to a rest service using rest java client.I am trying to get response of previous requests also(everything in json format). So, am storing the message objects into an arraylist and sending the list as a reponse. But I am not able to get the previous messages. Please tell me if am doing anything wrong.
This is my message model class.
public class Messages {
private String id;
private String message;
public Messages() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
the following is my webservice to receive a message object and return a json array.
#Path("/json/messages")
public class JSONMessages {
public List<Messages> list = new ArrayList<Messages>();
List<Messages> getAllMessages(Messages m){
list.add(m);
return list;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response MessageListInJSON(Messages msg) {
System.out.println("message saved");
if(!(msg.getId().equals("1"))){
String output ="Invalid User";
return Response.ok(output).build();
}
else{
return Response.ok(getAllMessages(msg)).build();
}
}
}
Finally, the following is my client side code
public class ClientPost {
public static void main(String[] args) {
try {
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource("http://localhost:8050/lab.rest.webservices/rest/json/messages/post");
//for(int i=0;i<5;i++){
String input = "{\"id\":\"1\", \"message\":\"hey there!\"}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.entity(input).post(ClientResponse.class);
if (response.getStatus() !=200 ) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output+"\n");
}
catch (Exception e) {
e.printStackTrace();
}
} }
Now, what I am expecting to see is the message I sent along with the previous responses stored in the array list(which were sent by running the client multiple times manually for now) but always am ending up with only the current message.
output:
Output from Server ....
[{"id":"1","message":"hey there!"}]
To be precise, what I want as output when i run my client several times(or put the try block in loop) is as follows which i am unable to get.
Output from Server ....
[{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"}] .
Resources in JAXRS aren't singletons. That means that for each request, the class JSONMessages is instantiated. So you lose the content of the attribute list. Changing it to static could fix your problem.
There is an annotation Singleton to change this behavior. In this case the resource will be managed as singleton and not in request scope. Here is a sample:
#Singleton
#Path("/json/messages")
public class JSONMessages {
(...)
}
Otherwise, be careful of concurrent accesses on your list. See this question for more details: java concurrent Array List access.
Hope it helps you,
Thierry

Ehcache hangs in test

I am in the process of rewriting a bottle neck in the code of the project I am on, and in doing so I am creating a top level item that contains a self populating Ehcache. I am attempting to write a test to make sure that the basic call chain is established, but when the test executes it hands when retrieving the item from the cache.
Here are the Setup and the test, for reference mocking is being done with Mockito:
#Before
public void SetUp()
{
testCache = new Cache(getTestCacheConfiguration());
recordingFactory = new EntryCreationRecordingCache();
service = new Service<Request, Response>(testCache, recordingFactory);
}
#Test
public void retrievesResultsFromSuppliedCache()
{
ResultType resultType = mock(ResultType.class);
Response expectedResponse = mock(Response.class);
addToExpectedResults(resultType, expectedResponse);
Request request = mock(Request.class);
when(request.getResultType()).thenReturn(resultType);
assertThat(service.getResponse(request), sameInstance(expectedResponse));
assertTrue(recordingFactory.requestList.contains(request));
}
private void addToExpectedResults(ResultType resultType,
Response response) {
recordingFactory.responseMap.put(resultType, response);
}
private CacheConfiguration getTestCacheConfiguration() {
CacheConfiguration cacheConfiguration = new CacheConfiguration("TEST_CACHE", 10);
cacheConfiguration.setLoggingEnabled(false);
return cacheConfiguration;
}
private class EntryCreationRecordingCache extends ResponseFactory{
public final Map<ResultType, Response> responseMap = new ConcurrentHashMap<ResultType, Response>();
public final List<Request> requestList = new ArrayList<Request>();
#Override
protected Map<ResultType, Response> generateResponse(Request request) {
requestList.add(request);
return responseMap;
}
}
Here is the ServiceClass
public class Service<K extends Request, V extends Response> {
private Ehcache cache;
public Service(Ehcache cache, ResponseFactory factory) {
this.cache = new SelfPopulatingCache(cache, factory);
}
#SuppressWarnings("unchecked")
public V getResponse(K request)
{
ResultType resultType = request.getResultType();
Element cacheEntry = cache.get(request);
V response = null;
if(cacheEntry != null){
Map<ResultType, Response> resultTypeMap = (Map<ResultType, Response>) cacheEntry.getValue();
try{
response = (V) resultTypeMap.get(resultType);
}catch(NullPointerException e){
throw new RuntimeException("Result type not found for Result Type: " + resultType);
}catch(ClassCastException e){
throw new RuntimeException("Incorrect Response Type for Result Type: " + resultType);
}
}
return response;
}
}
And here is the ResponseFactory:
public abstract class ResponseFactory implements CacheEntryFactory{
#Override
public final Object createEntry(Object request) throws Exception {
return generateResponse((Request)request);
}
protected abstract Map<ResultType,Response> generateResponse(Request request);
}
After wrestling with it for a while, I discovered that the cache wasn't being initialized. Creating a CacheManager and adding the cache to it resolved the problem.
I also had a problem with EHCache hanging, although only in a hello-world example. Adding this to the end fixed it (the application ends normally).
CacheManager.getInstance().removeAllCaches();
https://stackoverflow.com/a/20731502/2736496