DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Techniques You Should Know as a Kafka Streams Developer
  • Java REST API Frameworks
  • 4 Spring Annotations Every Java Developer Should Know
  • How To Compare DOCX Documents in Java

Trending

  • When Not To Use Apache Kafka (Lightboard Video)
  • Strategies for Building Self-Healing Software Systems
  • Knowledge Graph Enlightenment, AI, and RAG
  • Automate Message Queue Deployment on JBoss EAP
  1. DZone
  2. Coding
  3. Frameworks
  4. Introducing Kilo

Introducing Kilo

Meet Kilo (formerly HTTP-RPC), a lightweight Java framework for producing and consuming RESTful and REST-like web services.

By 
Greg Brown user avatar
Greg Brown
·
May. 15, 24 · Tutorial
Like (2)
Save
Tweet
Share
2.3K Views

Join the DZone community and get the full member experience.

Join For Free

Kilo 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:

Java
 
@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:

Java
 
@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 ItemDetailas a body argument:

Java
 
@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: string
  • Number/numeric primitive: number
  • Boolean/boolean: boolean
  • java.util.Date: number representing epoch time in milliseconds
  • Iterable: array
  • java.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:

Java
 
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:

Java
 
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:

Java
 
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:

Java
 
// 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
Java
 
// 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:

Java
 
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:

Java
 
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:

Java
 
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.

REST Java (programming language) Open source Framework

Published at DZone with permission of Greg Brown, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Techniques You Should Know as a Kafka Streams Developer
  • Java REST API Frameworks
  • 4 Spring Annotations Every Java Developer Should Know
  • How To Compare DOCX Documents in Java

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: