Search code examples
javaofbiz

How does one get the DispatchContext in Ofbiz from a Java program


I've spent the last few hours trying to find the answer in the "Apache Ofbiz Cookbook" and "Apache Ofbiz Development: The Beginner's Tutorial" how to get the DispatchContext in Ofbiz from a Java method. Ruth Hoffman's Cookbook doesn't include this code she just says "prepare any context parameters" p.43. I can understand how you get the DispatchContext when you register a service or an event but how does one do it from Java? Thanks.

I'm trying to populate Ofbiz entities/tables that I've defined in Ofbiz from the server end of a REST web service in Tomcat.

    GenericDelegator delegator = ctx.getDelegator();
    GenericValue myTable = delegator.makeValue("MyTable");
    myTable.set("name", myTableAsJson.getString("name"));


    try {
        delegator.store(offering);
    } catch(Exception e) {

    }

Solution

  • In Java method/event, dispatach context can be fetched using the following code snippet:

    GenericDispatcher dispatcher = (GenericDispatcher) request.getAttribute("dispatcher");
    DispatchContext dctx =  dispatcher.getDispatchContext();
    

    In Java method/event, any service can be invoked using the following code snippet:

    GenericDispatcher dispatcher = (GenericDispatcher) request.getAttribute("dispatcher");
    dispatcher.runSync("SERVICE_NAME", context);
    

    where context is map of required IN/IN-OUT parameters to service.

    To invoke service from Java method/event, there is no need to paas dispatch context. Only the service name and context is required.