Java Backend Server

Configure Project

  1. First install the library from maven and add it to your project.
<dependency>
   <groupId>co.dapi</groupId>
   <artifactId>dapi-java</artifactId>
   <version>1.0.0</version>
</dependency>
  1. Import Dapi's library in your code.
import co.dapi.*;
import co.dapi.types.*;
import co.dapi.response.*;
  1. Create a Dapi app with your App Secret
class MainTestClass {
    private DapiApp myApp;

    public MainTestClass() {
        var myAppConfig = new Config("YOUR_APP_SECRET");
        myApp = new DapiApp(myAppConfig);
    }
}

Configure SDK Server

  1. Follow the steps in Configure Project first in order to obtain and import the library.

  2. Our code will basically update the request to add your app's appSecret to it, and forward the request to Dapi, then return the result.

Spring Boot example

The following example uses Spring Boot. For set-up instructions follow the documentation here.

You need to replace the placeholder in this code snippet (YOUR_APP_SECRET) with your app's appSecret.

package co.dapi.examples.springBoot;

import co.dapi.Config;
import co.dapi.DapiApp;
import com.google.gson.Gson;
import okhttp3.Response;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;

@SpringBootApplication
@RestController
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    // Build the JSON decoder/encoder to be used
    private static final Gson jsonAgent = (new Gson()).newBuilder().disableHtmlEscaping().create();

    // The DapiApp instance that will be used by your server
    private DapiApp dapiApp;

    @PostConstruct
    public void init() {
        // Replace YOUR_APP_SECRET with the appSecret of your Dapi app
        dapiApp = new DapiApp(new Config("YOUR_APPSECRET"));
    }

    @RequestMapping(
            value = "/handleSDKRequest",
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public String handleSDKRequest(@RequestBody String reqBodyJSON, @RequestHeader HashMap<String, String> reqHeadersMap) throws IOException {
        // Modify the request body before passing it to DapiApp
        try {
            // decode the JSON body into a HashMap, to be able to modify it
            HashMap reqBodyMap = jsonAgent.fromJson(reqBodyJSON, HashMap.class);

            // handle having an empty string as the request body(if it's allowed)
            if (reqBodyMap == null) {
                // create a new HasMap to use it as the request body
                reqBodyMap = new HashMap<>();
            }

            // modify the request body, or add new fields to it
            reqBodyMap.put("myCustomID", "CUSTOM_ID");

            // convert the updated request body back to a JSON string
            reqBodyJSON = jsonAgent.toJson(reqBodyMap);
        } catch (Exception e) {
            // add proper exception handling
            e.printStackTrace();
        }

        // Possibly, modify the header before passing it
        reqHeadersMap.put("X-My-Custom-Header", "CUSTOM_HEADER");

        // Forward the request body and headers to Dapi
        Response resp = dapiApp.handleSDKRequest(reqBodyJSON, reqHeadersMap);

        // Handle the response and return its body...
        // this will be returned only if the response body is null
        String respBodyJSON = "{\"error\": \"response.body is null\"}";

        // access the response body only if it's not null
        okhttp3.ResponseBody respBody = resp.body();
        if (respBody != null) respBodyJSON = respBody.string();

        return respBodyJSON;
    }
}

WildFly example

The following example uses WildFly. For set-up instructions follow the documentation here.

You need to replace the placeholder in the DapiService.java file (YOUR_APP_SECRET) with your app's appSecret.

package co.dapi.examples.wildfly;

import okhttp3.Response;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.stream.Collectors;

@WebServlet("/HandleSDKRequests")
public class DapiServlet extends HttpServlet {

    @Inject
    DapiService dapiService;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("Post/HandleSDKRequests called");

        // Read the body of the request
        String reqBody = req.getReader().lines().collect(Collectors.joining());

        // Read the headers of the request, and prepare them to be passed to Dapi
        HashMap<String, String> reqHeaders = new HashMap<>();
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            reqHeaders.put(headerName, headerValue);
        }

        // Call Dapi with the got request body and headers, and handle any exception that may occur
        try {
            Response dapiResp = dapiService.handleSDKRequest(reqBody, reqHeaders);

            // Try to read the body of the response got from Dapi
            String dapiRespBody = dapiResp.body().string();

            // Set the Content-Type of the response and write the response
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(dapiRespBody);
            writer.close();
        } catch (IOException e) {
            // Proper exception handling should be implemented in real-world handler
            resp.setContentType("text/plain");
            PrintWriter writer = resp.getWriter();
            writer.println("An exception happened");
            writer.println(e.getMessage());
            writer.close();
        }

    }
}
package co.dapi.examples.wildfly;

import co.dapi.Config;
import co.dapi.DapiApp;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;

public class DapiService {

    private final String appSecret = "YOUR_APP_SECRET";
    // Replace 'YOUR_APP_SECRET' with the appSecret of you dapi app
    private final DapiApp dapiApp = new DapiApp(new Config(appSecret));

    Response handleSDKRequest(String reqBodyJSON, HashMap<String, String> headersMap) throws IOException {
        return dapiApp.handleSDKRequest(reqBodyJSON, headersMap);
    }

}