Using Response Patterns

One issue with REST (and HTTP in general) is that the HTTP response code must be set as a header before the body of the request is sent. This can be problematic when REST calls invoke long-running processes, pipes the results through the connection, and then fails after an HTTP 200 has already been sent.

One common solution is to serialize some text at the end to indicate whether the long-running process succeeded (e.g. "FAILED" or "SUCCEEDED").

The {@link oajrc.RestClient} class has convenience methods for scanning the response without interfering with the other methods used for retrieving output.

The following example shows how the {@link oajrc.RestCall#successPattern(String)} method can be used to look for a SUCCESS message in the output:

Example:

// Throw a RestCallException if SUCCESS is not found in the output. restClient.doPost(URL) .successPattern("SUCCESS") .run();

The {@link oajrc.RestCall#failurePattern(String)} method does the opposite. It throws an exception if a failure message is detected.

Example:

// Throw a RestCallException if FAILURE or ERROR is found in the output. restClient.doPost(URL) .failurePattern("FAILURE|ERROR") .run();

These convenience methods are specialized methods that use the {@link oajrc.RestCall#responsePattern(ResponsePattern)} method which uses regular expression matching against the response body. This method can be used to search for arbitrary patterns in the response body.

The following example shows how to use a response pattern finder to find and capture patterns for "x=number" and "y=string" from a response body.

Example:

final List<Number> xList = new ArrayList<Number>(); final List<String> yList = new ArrayList<String>(); String responseText = restClient.doGet(URL) .responsePattern( new ResponsePattern("x=(\\d+)") { @Override public void onMatch(RestCall restCall, Matcher m) throws RestCallException { xList.add(Integer.parseInt(m.group(1))); } @Override public void onNoMatch(RestCall restCall) throws RestCallException { throw new RestCallException("No X's found!"); } } ) .responsePattern( new ResponsePattern("y=(\\S+)") { @Override public void onMatch(RestCall restCall, Matcher m) throws RestCallException { yList.add(m.group(1)); } @Override public void onNoMatch(RestCall restCall) throws RestCallException { throw new RestCallException("No Y's found!"); } } ) .getResponseAsString();

Using response patterns does not affect the functionality of any of the other methods used to retrieve the response such as {@link oajrc.RestCall#getResponseAsString()} or {@link oajrc.RestCall#getResponse(Class)}. HOWEVER, if you want to retrieve the entire text of the response from inside the match methods, use {@link oajrc.RestCall#getCapturedResponse()} since this method will not absorb the response for those other methods.