How to get request body in java jar in java callout policy

I need to get the request body passed in the JSON format in the java code. I need to validate the request in java code and perform some other checks. Anyone please

0 4 459
4 REPLIES 4

Here is some code that shows how you could examine the payload from within a Java callout.

 

import com.apigee.flow.execution.ExecutionContext;
import com.apigee.flow.execution.ExecutionResult;
import com.apigee.flow.execution.spi.Execution;
import com.apigee.flow.message.MessageContext;
import java.util.Map;

public class TestCallout implements Execution {
  private Map properties;

  public TestCallout(Map properties) {
    this.properties = properties;
  }

  public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt) {
    try {
      String content = (String) msgCtxt.getVariable("request.content");
      // content can be null in case of GET or HEAD or DELETE
      if (content != null) {
        // parse as JSON here?
      }
    } catch (Exception e) {
      ...
    }
    return ExecutionResult.SUCCESS;
  }
}

 

There are some limitations to what you can do for parsing JSON. The Apigee runtime does not permit reflection, and many common json parsing libraries use reflection. The result is, if you try to use FasterXML to parse JSON into a POJO, you will get a runtime error as Apigee refuses to allow the parsing. Likewise if you use Gson.

There are workarounds. See this repo for some background and hints.


BTW, if you are simply doing some validations, you might find it easier to do from within a JS callout. The code for that looks like this:

 

var c = context.getVariable('request.content');
var json = JSON.parse(c); 
// validate here.
// throw an exception if there is a validation error.

 

This seems much simpler than writing Java code to do validations. The performance will be fine. 

Thanks for replying, actually I want to do OAS validation generic for entire Proxies. I found a solution using java callout. Would you please correct its a good approach to validate each request payload using java callout or JS would be a better option for this thing.

Just making sure you are aware: Apigee has a built-in policy that performs OAS Validation

If for some reason you do not like that option, then, yes , it would be reasonable for you to write your own code in Java to do this validation, and package it as a Java callout. You will need to take care with the reflection and permissions, as I described above.