# HTTP-RPC
**Repository Path**: Urey.Ming/HTTP-RPC
## Basic Information
- **Project Name**: HTTP-RPC
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2018-10-24
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: rpc
## README
[](https://github.com/gk-brown/HTTP-RPC/releases)
[](http://repo1.maven.org/maven2/org/httprpc/httprpc/)
# Introduction
HTTP-RPC is an open-source framework for implementing and interacting with RESTful and REST-like web services in Java. It is extremely lightweight and requires only a Java runtime environment and a servlet container. The entire framework is distributed as a single JAR file that is less than 70KB in size, making it an ideal choice for applications where a minimal footprint is desired.
This guide introduces the HTTP-RPC framework and provides an overview of its key features.
# Feedback
Feedback is welcome and encouraged. Please feel free to [contact me](mailto:gk_brown@icloud.com?subject=HTTP-RPC) with any questions, comments, or suggestions. Also, if you like using HTTP-RPC, please consider [starring](https://github.com/gk-brown/HTTP-RPC/stargazers) it!
# Contents
* [Getting HTTP-RPC](#getting-http-rpc)
* [HTTP-RPC Classes](#http-rpc-classes)
* [WebService](#webservice)
* [Method Arguments](#method-arguments)
* [Return Values](#return-values)
* [Exceptions](#exceptions)
* [Request and Repsonse Properties](#request-and-repsonse-properties)
* [Path Variables](#path-variables)
* [Documentation](#documentation)
* [JSONEncoder and JSONDecoder](#jsonencoder-and-jsondecoder)
* [CSVEncoder and CSVDecoder](#csvencoder-and-csvdecoder)
* [BeanAdapter](#beanadapter)
* [ResultSetAdapter and Parameters](#resultsetadapter-and-parameters)
* [WebServiceProxy](#webserviceproxy)
* [Additional Information](#additional-information)
# Getting HTTP-RPC
The HTTP-RPC JAR file can be downloaded [here](https://github.com/gk-brown/HTTP-RPC/releases). It is also available via Maven:
```xml
org.httprpchttprpc...
```
HTTP-RPC requires Java 8 or later and a servlet container supporting Java Servlet specification 3.1 or later.
# HTTP-RPC Classes
HTTP-RPC provides the following classes for creating and consuming REST services:
* `org.httprpc`
* `RequestMethod` - annotation that associates an HTTP verb with a service method
* `RequestParameter` - annotation that associates a custom request parameter name with a method argument
* `ResourcePath` - annotation that associates a resource path with a service method
* `Response` - annotation that associates a custom response description with a service method
* `WebService` - abstract base class for web services
* `WebServiceException` - exception thrown when a service operation returns an error
* `WebServiceProxy` - class for invoking remote web services
* `org.httprpc.io`
* `CSVDecoder` - class that reads an iterable sequence of values from CSV
* `CSVEncoder` - class that writes an iterable sequence of values to CSV
* `JSONDecoder` - class that reads an object hierarchy from JSON
* `JSONEncoder` - class that writes an object hierarchy to JSON
* `org.httprpc.beans`
* `BeanAdapter` - class that presents the properties of a Java bean object as a map and vice versa
* `Key` - annotation that associates a custom key with a bean property
* `org.httprpc.sql`
* `Parameters` - class for applying named parameters values to prepared statements
* `ResultSetAdapter` - class that presents the contents of a JDBC result set as an iterable sequence of maps or typed row values
These classes are explained in more detail in the following sections.
## WebService
`WebService` is an abstract base class for REST services. It extends the similarly abstract `HttpServlet` class provided by the servlet API.
Service operations are defined by adding public methods to a concrete service implementation. Methods are invoked by submitting an HTTP request for a path associated with a servlet instance. Arguments are provided either via the query string or in the request body, like an HTML form. `WebService` converts the request parameters to the expected argument types, invokes the method, and writes the return value to the output stream as [JSON](http://json.org).
The `RequestMethod` annotation is used to associate a service method with an HTTP verb such as `GET` or `POST`. The optional `ResourcePath` annotation can be used to associate the method with a specific path relative to the servlet. If unspecified, the method is associated with the servlet itself. If no matching handler method is found for a given request, the default handler (e.g. `doGet()`) is called.
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, the following service class implements some simple addition operations:
```java
@WebServlet(urlPatterns={"/math/*"})
public class MathService extends WebService {
@RequestMethod("GET")
@ResourcePath("sum")
public double getSum(double a, double b) {
return a + b;
}
@RequestMethod("GET")
@ResourcePath("sum")
public double getSum(List values) {
double total = 0;
for (double value : values) {
total += value;
}
return total;
}
}
```
The following request would cause the first method to be invoked:
```
GET /math/sum?a=2&b=4
```
This request would invoke the second method:
```
GET /math/sum?values=1&values=2&values=3
```
In either case, the service would return the value 6 in response.
### Method Arguments
Method arguments may be any of the following types:
* `String`
* `Byte`/`byte`
* `Short`/`short`
* `Integer`/`int`
* `Long`/`long`
* `Float`/`float`
* `Double`/`double`
* `Boolean`/`boolean`
* `java.util.Date` (from a long value representing epoch time in milliseconds)
* `java.util.time.LocalDate` ("yyyy-mm-dd")
* `java.util.time.LocalTime` ("hh:mm")
* `java.util.time.LocalDateTime` ("yyyy-mm-ddThh:mm")
* `java.util.List`
* `java.net.URL`
Missing or `null` values are automatically converted to `0` or `false` for primitive types.
`List` arguments represent multi-value parameters. List values are automatically converted to their declared types (e.g. `List`).
`URL` and `List` arguments represent file uploads. They may be used only with `POST` requests submitted using the multi-part form data encoding. For example:
```java
@WebServlet(urlPatterns={"/upload/*"})
@MultipartConfig
public class FileUploadService extends WebService {
@RequestMethod("POST")
public void upload(URL file) throws IOException {
...
}
@RequestMethod("POST")
public void upload(List files) throws IOException {
...
}
}
```
#### Custom Parameter Names
In general, service classes should be compiled with the `-parameters` flag so the names of their method parameters are available at runtime. However, the `RequestParameter` annotation can be used to customize the name of the parameter associated with a particular argument. For example, the following service might allow a caller to look up the name of the city associated with a particular zip code:
```java
@WebServlet(urlPatterns={"/lookup/*"})
public class LookupService extends WebService {
@RequestMethod("GET")
@ResourcePath("city")
public String getCity(@RequestParameter("zip_code") String zipCode) {
...
}
}
```
This request would invoke the `getCity()` method, passing "02101" as the `zipCode` argument:
```
GET /lookup/city?zip_code=02101
```
### Return Values
Return values are converted to their JSON equivalents as follows:
* `CharSequence`: string
* `Number`: number
* `Boolean`: true/false
* `Enum`: ordinal value
* `java.util.Date`: long value representing epoch time in milliseconds
* `java.util.time.LocalDate`: "yyyy-mm-dd"
* `java.util.time.LocalTime`: "hh:mm"
* `java.util.time.LocalDateTime`: "yyyy-mm-ddThh:mm"
* `Iterable`: array
* `java.util.Map`: object
For example, this method returns a `Map` instance containing three values:
```java
@RequestMethod("GET")
@ResourcePath("map")
public Map getMap() {
HashMap map = new HashMap<>();
map.put("text", "Lorem ipsum");
map.put("number", 123);
map.put("flag", true);
return map;
}
```
The service would produce the following in response:
```json
{
"text": "Lorem ipsum",
"number": 123,
"flag": true
}
```
Methods may also return `void` or `Void` to indicate that they do not produce a value.
If the return value is not an instance of any of the aforementioned types, it is automatically wrapped in an instance of `BeanAdapter` and serialized as a `Map`. `BeanAdapter` is discussed in more detail [later](#beanadapter).
#### Custom Result Encodings
Although return values are encoded as JSON by default, subclasses can override the `encodeResult()` method of the `WebService` class to provide a custom result encoding. See the method documentation for more information.
### Exceptions
If any exception is thrown by a service method, an HTTP 500 response will be returned. If the response has not yet been committed, the exception message will be returned as plain text in the response body. This allows a service to provide the caller with insight into the cause of the failure. For example:
```java
@RequestMethod("GET")
@ResourcePath("error")
public void generateError() throws Exception {
throw new Exception("This is an error message.");
}
```
### Request and Repsonse Properties
`WebService` provides the following methods to allow a service method to access the request and response objects associated with the current operation:
protected HttpServletRequest getRequest() { ... }
protected HttpServletResponse getResponse() { ... }
For example, a service might use the request to get the name of the current user, or use the response to return a custom header.
The response object can also be used to produce a custom result. If a service method commits the response by writing to the output stream, the return value (if any) will be ignored by `WebService`. This allows a service to return content that cannot be easily represented as JSON, such as image data or other response formats such as XML.
### Path Variables
Path variables may be specified by a "?" character in the resource path. For example:
```java
@RequestMethod("GET")
@ResourcePath("contacts/?/addresses/?")
public List