Introducing Kilo
Meet Kilo (formerly HTTP-RPC), a lightweight Java framework for producing and consuming RESTful and REST-like web services.
Join the DZone community and get the full member experience.
Join For FreeKilo is an open-source framework for creating and consuming RESTful and REST-like web services in Java. It is extremely lightweight and requires only a Java runtime environment and a servlet container. The project’s name comes from the nautical K or Kilo flag, which means “I wish to communicate with you”.
Kilo was formerly known as “HTTP-RPC”, and was created as an alternative to other frameworks that have a larger footprint and steeper learning curve. The name was changed recently to better reflect the project’s current focus and intent.
This article provides an overview of two core Kilo classes, WebService
and WebServiceProxy
.
WebService
WebService
is an abstract base class for web services. It extends the similarly abstract HttpServlet
class and provides a thin, REST-oriented layer on top of the standard servlet API.
For example, the following service implements some simple mathematical operations:
@WebServlet(urlPatterns = {"/math/*"}, loadOnStartup = 1)
@Description("Math example service.")
public class MathService extends WebService {
@RequestMethod("GET")
@ResourcePath("sum")
@Description("Calculates the sum of two numbers.")
public double getSum(
@Description("The first number.") double a,
@Description("The second number.") double b
) {
return a + b;
}
@RequestMethod("GET")
@ResourcePath("sum")
@Description("Calculates the sum of a list of numbers.")
public double getSum(
@Description("The numbers to add.") List<Double> values
) {
double total = 0;
for (double value : values) {
total += value;
}
return total;
}
}
The RequestMethod
annotation associates an HTTP verb such as GET
or POST
with a service method, or “handler”. The optional ResourcePath
annotation associates a handler with a specific path, or “endpoint”, relative to the servlet. If unspecified, the handler is associated with the servlet itself. The optional Description
annotation is used in the automatically generated documentation for the service.
Arguments may be provided via the query string, resource path, or request body. They may also be submitted as form data. WebService
converts the values to the expected types, invokes the method, and writes the return value (if any) to the output stream as JSON.
Multiple methods may be associated with the same verb and path. WebService
selects the best method to execute based on the provided argument values. For example, this request would invoke the first method:
GET /math/sum?a=2&b=4
While this would invoke the second:
GET /math/sum?values=1&values=2&values=3
In either case, the service would return the value 6 in response.
Path Variables
Path variables (or “keys”) are specified by a “?” character in a handler’s resource path. For example, the itemID
argument in the method below is provided by a path variable:
@RequestMethod("GET")
@ResourcePath("items/?")
@Description("Returns detailed information about a specific item.")
public ItemDetail getItem(
@Description("The item ID.") Integer itemID
) throws SQLException { ... }
Path parameters must precede query parameters in the method signature. Values are mapped to method arguments in declaration order.
Body Content
Body content may be declared as the final parameter in a POST
or PUT
handler. For example, this method accepts an item ID as a path variable and an instance of ItemDetail
as a body argument:
@RequestMethod("PUT")
@ResourcePath("items/?")
@Description("Updates an item.")
public void updateItem(
@Description("The item ID.") Integer itemID,
@Description("The updated item.") ItemDetail item
) throws SQLException { ... }
Return Values
Return values are converted to JSON as follows:
String
: stringNumber
/numeric primitive: numberBoolean
/boolean
: booleanjava.util.Date
: number representing epoch time in millisecondsIterable
: arrayjava.util.Map
: object
Additionally, instances of the following types are automatically converted to their string representations:
Character
/char
Enum
java.time.TemporalAccessor
java.time.TemporalAmount
java.util.UUID
java.net.URL
All other values are assumed to be beans and are serialized as objects.
WebServiceProxy
The WebServiceProxy
class is used to submit API requests to a server. It provides the following two constructors:
public WebServiceProxy(String method, URL url) { ... }
public WebServiceProxy(String method, URL baseURL, String path, Object... arguments) throws MalformedURLException { ... }
The first version accepts a string representing the HTTP method to execute and the URL of the requested resource. The second accepts the HTTP method, a base URL, and a relative path (as a format string, to which the optional trailing arguments are applied).
Request arguments are specified via a map passed to the setArguments()
method. Any value may be used as an argument and will generally be encoded using its string representation. However, Date
instances are automatically converted to a long value representing epoch time in milliseconds. Additionally, Collection
or array instances represent multi-value parameters and behave similarly to <select multiple>
tags in HTML. Body content can be provided via the setBody()
method.
Service operations are invoked via one of the following methods:
public Object invoke() throws IOException { ... }
public <T> T invoke(Function<Object, ? extends T> transform) throws IOException { ... }
public <T> T invoke(ResponseHandler<T> responseHandler) throws IOException { ... }
The first version deserializes a successful JSON response (if any). The second applies a transform to the deserialized response. The third version allows a caller to provide a custom response handler:
public interface ResponseHandler<T> {
T decodeResponse(InputStream inputStream, String contentType) throws IOException;
}
The following code demonstrates how WebServiceProxy
might be used to access the operations of the simple math service discussed earlier:
// GET /math/sum?a=2&b=4
var webServiceProxy = new WebServiceProxy("GET", new URL("http://localhost:8080/kilo-test/math/sum"));
webServiceProxy.setArguments(mapOf(
entry("a", 4),
entry("b", 2)
));
System.out.println(webServiceProxy.invoke()); // 6.0
// GET /math/sum?values=1&values=2&values=3
var webServiceProxy = new WebServiceProxy("GET", new URL("http://localhost:8080/kilo-test/math/sum"));
webServiceProxy.setArguments(mapOf(
entry("values", listOf(1, 2, 3))
));
System.out.println(webServiceProxy.invoke()); // 6.0
POST
, PUT
, and DELETE
operations are also supported.
Typed Invocation
WebServiceProxy
additionally provides the following methods to facilitate convenient, type-safe access to web APIs:
public static <T> T of(Class<T> type, URL baseURL) { ... }
public static <T> T of(Class<T> type, URL baseURL, Consumer<WebServiceProxy> initializer) { ... }
Both versions return an implementation of a given interface that submits requests to the provided URL. An optional initializer accepted by the second version will be called prior to each service invocation; for example, to apply common request headers.
The RequestMethod
and ResourcePath
annotations are used as described earlier. Proxy methods must include a throws clause that declares IOException
, so that callers can handle unexpected failures. For example:
public interface MathServiceProxy {
@RequestMethod("GET")
@ResourcePath("sum")
double getSum(double a, double b) throws IOException;
@RequestMethod("GET")
@ResourcePath("sum")
double getSum(List<Double> values) throws IOException;
}
Example usage is shown below:
var mathServiceProxy = WebServiceProxy.of(MathServiceProxy.class, new URL("http://localhost:8080/kilo-test/math/"));
System.out.println(mathServiceProxy.getSum(4, 2)); // 6.0
System.out.println(mathServiceProxy.getSum(listOf(1.0, 2.0, 3.0))); // 6.0
Additional Information
This article introduced the Kilo framework and provided a brief overview of two Kilo classes, WebService
and WebServiceProxy
. For more information, see the project README.
Published at DZone with permission of Greg Brown, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments