Java Reference

JsonTemplate

Introduction

The JsonTemplate class provides an easy way to issue REST HTTP and websocket calls, such at GET, POST, PUT, and DELETE. It is built on top of the Jetty HttpClient class.

Overview

You should be able to make all your websocket calls using this component. If additional functionality is required, you can use this object to grab Jetty’s HttpClient, which allows for full control.

Jetty

Jetty is a project from the Eclipse Foundation. It is an open source web server and servlet container. It is full-featured, standards-based, and has a small footprint. It supports HTTP/2, websockets, and other integrations.

See the Eclipse Foundation for more info.

DO NOT use any other HTTP client library

Always use the JsonTemplate component. If that doesn’t provide the desired functionality, grab its HttpClient object for more fine-grained control.

API Components

The purpose of the JsonTemplate object is to make REST and websocket calls.

JsonTemplate

The JsonTemplate is a KOS-provided system component that you inject into in your code using the @Autowired annotation. You then use it to send HTTP/REST GET/POST/PUT/DELETE messages to server endpoints.

REST and Websockets

REST (representational state transfer) is a software architectural style that describes a uniform interface between internet-based components. See Wikipedia.

WebSocket is a full-duplex communication channel over a single TCP connection. It enables interaction between a client and a web server. See Wikipedia.

JsonTemplate

The following code defines the JsonTemplate class. It has one constructor and four sets of methods for the most common HTTP request methods.

In all of these methods, the variables are:

url

URL of web endpoint, as a text string

uri

URI of web endpoint

body

the data placed in the request’s body, as JSON

clazz

class that holds the response data

envelope

true if the response is wrapped in the ResponseEnvelope class

API: JsonTemplate class
public class JsonTemplate {

    // Constructor:
    public JsonTemplate(HttpClient client, ObjectMapper mapper);

    // Getters:
    public HttpClient getClient();

    // GET methods:
    public <T> JsonResp<T> GET(String url, Class<T> clazz, boolean envelope);
    public <T> JsonResp<T> GET(   URI uri, Class<T> clazz, boolean envelope);

    // POST methods:
    public <T> JsonResp<T> POST(String url, Object body, Class<T> clazz, boolean envelope);
    public <T> JsonResp<T> POST(   URI uri, Object body, Class<T> clazz, boolean envelope);

    // PUT methods:
    public <T> JsonResp<T> PUT(String url, Object body, Class<T> clazz, boolean envelope);
    public <T> JsonResp<T> PUT(   URI uri, Object body, Class<T> clazz, boolean envelope);

    // DELETE methods:
    public <T> JsonResp<T> DELETE(String url, Object body, Class<T> clazz, boolean envelope);
    public <T> JsonResp<T> DELETE(   URI uri, Object body, Class<T> clazz, boolean envelope);

    // Generic send methods:
    public <T> JsonResp<T> send(Request request, Class<T> clazz, boolean envelope);
    public <T> JsonResp<T> send(HttpMethod method, String url, Object body, Class<T> clazz, boolean envelope);

    // Parsing method:
    public <T> JsonResp<T> fromJson(ContentResponse resp, Class<T> clazz, boolean envelope);
}
HTTP Request Methods

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. These include GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE and PATCH. These are sometimes referred to as "HTTP verbs".

See Mozilla.org for more information.

JsonResp

The following code defines the JsonResp (response) class.

API: JsonResp class
public class JsonResp<T> {

    // Constructors are private.

    // Getters:
    public int getStatus();
    public ContextResponse getResponse();
    public ResponseEnvelope<T> getEnvelope();
    public T getData();
    public Exception getException();

    // Methods:
    public void throwRequestExceptionOnError();
    public throwRequestExceptionOnError(int errStatus, String errMsg);
    public String getErrorMsg();
}

ResponseEnvelope

The ResponseEnvelope class is used by many KOS endpoints to wrap a response object in.

API: ResponseEnvelope class
public class ResponseEnvelope<T> {

    // Fields:
    private int status;               // the HTTP status code
    private ResponseVersion version;  // handler version used to provide context to the data
    private T data;                   // primary data from the handler
    private String error;             // optional error message

    // Getters and Setters for each of the data fields:
    // . . .
}

Example Code

This section demonstrates a few ways the JsonTemplate object can be used.

The examples use the UriBuilder.

POST with response

The following code snippet shows a hypothetical call to a web server in an attempt to log in a user.

Line 16 shows the call to the POST() method, passing in LoginCredentials as the request body, and TokenResponse as the response clazz.

Making a POST call and handling the response
// Request data:
public record LoginCredentials(String name, String password) {}

// Response data:
public record TokenResponse(String token) {}

public class MyClass {

    @Autowired
    private JsonTemplate jsonTemplate;

    public void login(String uname, String pwd) {

        String url = "http://server.com:5757/api/login";
        URI uri = new UriBuilder(url).toURI();
        LoginCredentials creds = new LoginCredentials(uname, pwd);
        JsonResp<TokenResponse> resp = jsonTemplate.POST(uri, creds, TokenResponse.class, true);

        if (resp.getData() != null) {
            String token = resp.getData().token();
            // . . .
        } else {
            String errorMsg = resp.getErrorMsg();
            // . . .
        }
    }
}

PUT with no response

The following code snippet shows a slight variation from the example above, as this one does not receive a response body from the web server.

Line 10 shows the call to the PUT() method, passing in null for both the request body and response clazz.

Making a PUT call when there’s no response
public class MyClass {

    @Autowired
    private JsonTemplate jsonTemplate;

    public void resetPassword(String userId) {

        String url = "https://server.com/api/reset-password/{userId}";
        URI uri = new UriBuilder(url).setVar("userId", userId).toURI();
        JsonResp<String> resp = jsonTemplate.PUT(uri, null, null, true);

        if (resp.getStatus() != 200) {
            // Success
        } else {
            // Failure
        }
    }
}

GET with no envelope

This example demonstrates how to retrieve a server’s response that does not wrap its data in the KOS envelope.

Almost no difference, except that you must pass in false to the envelope parameter on line number 10.

Making a GET call without an envelope
public class MyClass {

    @Autowired
    private JsonTemplate jsonTemplate;

    public void getFirstName(String userId) {

        String url = "https://server.com/api/first-name/{userId}";
        URI uri = new UriBuilder(url).setVar("userId", userId).toURI();
        JsonResp<String> resp = jsonTemplate.GET(uri, null, String.class, false);

        if (resp.getData() != null) {
            // Success
        } else {
            // Failure
        }
    }
}

Throw exception on error

As you may have noticed in the preceding examples, all calls to any of the jsonTemplate.GET/POST/PUT/DELETE() methods never throw an exception. Instead, you verify the operation was successful or not by either a) checking that the resp.getStatus() value is OK (200), and/or b) checking that the resp.getData() value is not null (when expecting a response).

If you want to throw an exception on any error, simply place a call to resp.throwRequestExceptionOnError() after the send call. If the HTTP status is not OK (200), or if any other error occurred, then a RequestException is thrown.

How to throw an exception when there’s a JsonTemplate error
public class MyClass {

    @Autowired
    private JsonTemplate jsonTemplate;

    public void getFirstName(String userId) {

        String url = "https://server.com/api/first-name/{userId}";
        URI uri = new UriBuilder(url).setVar("userId", userId).toURI();
        JsonResp<String> resp = jsonTemplate.GET(uri, null, String.class, false);
        resp.throwRequestExceptionOnError();
        // Successful request and response if we get here.
    }
}
Previous
Next
On this page
Java Development
Seamlessly transition from Legacy+ systems to Freestyle microdosing and advanced distributed dispense systems.
UI Development
Using KOS SDKs, integrating Consumer and Non-consumer facing UIs becomes seamless, giving you less hassle and more time to create.
Video Library
Meet some of our development team, as they lead you through the tools, features, and tips and tricks of various KOS tools.
Resources
Familiarize yourself with KOS terminology, our reference materials, and explore additional resources that complement your KOS journey.
Copyright © 2024 TCCC. All rights reserved.