SkillAgentSearch skills...

Jsonrpc4j

JSON-RPC for Java

Install / Use

/learn @briandilley/Jsonrpc4j
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

JSON-RPC for Java

This project aims to provide the facility to easily implement JSON-RPC for the java programming language. jsonrpc4j uses the [Jackson][Jackson page] library to convert java objects to and from json objects (and other things related to JSON-RPC).

Download

Features Include:

  • Streaming server (InputStream \ OutputStream)
  • HTTP Server (HttpServletRequest \ HttpServletResponse)
  • Portlet Server (ResourceRequest \ ResourceResponse)
  • Socket Server (StreamServer)
  • Integration with the Spring Framework
  • Streaming client
  • HTTP client
  • Dynamic client proxies
  • Annotations support
  • Custom error resolving
  • Composite services

Maven

This project is built with Gradle. Be sure to check the build.gradle for the dependencies if you're not using gradle. If you're already using spring you should have most (if not all) of the dependencies already - outside of maybe the [Jackson Library][Jackson page]. Jsonrpc4j is available from the maven central repo. Add the following to your pom.xml if you're using maven:

In <dependencies>:

	<!-- jsonrpc4j -->
	<dependency>
		<groupId>com.github.briandilley.jsonrpc4j</groupId>
		<artifactId>jsonrpc4j</artifactId>
		<version>1.7</version>
	</dependency>

or with gradle:

    implementation('com.github.briandilley.jsonrpc4j:jsonrpc4j:1.7')

If you want to just download the projects output JAR and it's dependencies you can do it over at the [Maven repository][Maven repository].

JSON-RPC specification

The official source for the [JSON-RPC 2.0 specification][JSON RPC Spec]. The guys over at [json-rpc google group][Google Group] seem to be fairly active, so you can ask clarifying questions there.

Streaming server and client

Jsonrpc4j comes with a streaming server and client to support applications of all types (not just HTTP). The JsonRpcClient and JsonRpcServer have simple methods that take InputStreams and OutputStreams. Also in the library is a JsonRpcHttpClient which extends the JsonRpcClient to add HTTP support.

Spring Framework

jsonrpc4j provides support for exposing java services as JSON-RPC over HTTP without requiring any additional work on the part of the programmer. The following example explains how to use the JsonServiceExporter within the Spring Framework.

Create your service interface:

package com.mycompany;
public interface UserService {
    User createUser(String userName, String firstName, String password);
    User createUser(String userName, String password);
    User findUserByUserName(String userName);
    int getUserCount();
}

Implement it:

package com.mycompany;
public class UserServiceImpl
    implements UserService {

    public User createUser(String userName, String firstName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setFirstName(firstName);
        user.setPassword(password);
        database.saveUser(user);
        return user;
    }

    public User createUser(String userName, String password) {
        return this.createUser(userName, null, password);
    }

    public User findUserByUserName(String userName) {
        return database.findUserByUserName(userName);
    }

    public int getUserCount() {
        return database.getUserCount();
    }

}

Configure your service in Spring as you would do it for any other Beans, and then add a reference of your service Bean into JsonServiceExporter by specifying the service and serviceInterface properties:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean id="userService" class="com.mycompany.UserServiceImpl">
    </bean>

    <bean name="/UserService.json" class="com.googlecode.jsonrpc4j.spring.JsonServiceExporter">
        <property name="service" ref="userService"/>
        <property name="serviceInterface" value="com.mycompany.UserService"/>
    </bean>

</beans>

Your service is now available at the URL /UserService.json. Type conversion of JSON->Java and Java->JSON will happen for you automatically. This service can be accessed by any JSON-RPC capable client, including the JsonProxyFactoryBean, JsonRpcClient and JsonRpcHttpClient provided by this project:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean  class="com.googlecode.jsonrpc4j.spring.JsonProxyFactoryBean">
        <property name="serviceUrl" value="http://example.com/UserService.json"/>
        <property name="serviceInterface" value="com.mycompany.UserService"/>
    </bean>

<beans>

In the case that your JSON-RPC requires named based parameters rather than indexed parameters an annotation can be added to your service interface (this also works on the service implementation for the ServiceExporter):

package com.mycompany;
public interface UserService {
    User createUser(@JsonRpcParam(value="theUserName") String userName, @JsonRpcParam(value="thePassword") String password);
}

By default all error message responses contain the the message as returned by Exception.getmessage() with a code of 0. This is not always desirable. jsonrpc4j supports annotated based customization of these error messages and codes, for example:

package com.mycompany;
public interface UserService {
    @JsonRpcErrors({
        @JsonRpcError(exception=UserExistsException.class,
            code=-5678, message="User already exists", data="The Data"),
        @JsonRpcError(exception=Throwable.class,code=-187)
    })
    User createUser(@JsonRpcParam(value="theUserName") String userName, @JsonRpcParam(value="thePassword") String password);
}

The previous example will return the error code -5678 with the message User already exists if the service throws a UserExistsException. In the case of any other exception the code -187 is returned with the value of getMessage() as returned by the exception itself.

Auto Discovery With Annotations

Spring can also be configured to auto-discover services and clients with annotations.

To configure auto-discovery of annotated services first annotate the service interface:

@JsonRpcService("/path/to/MyService")
interface MyService {
... service methods ...
}

Next annotate the implementation of the service interface;

@AutoJsonRpcServiceImpl
class MyServiceImpl {
... service methods' implementations ...
}

and use the following configuration to allow spring to find the implementation that you would like to expose:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean class="com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter"/>

  <bean class="com.mycompany.MyServiceImpl" />

</beans>

Configuring a client is just as easy:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean class="com.googlecode.jsonrpc4j.spring.AutoJsonRpcClientProxyCreator">
    <property name="baseUrl" value="http://hostname/api/" />
    <property name="scanPackage" value="com.mycompany.services" />
  </bean>

</beans>

Where the baseUrl is added to the front of the path value provided by the JsonRpcService annotation and scanPackage tells spring which packages to scan for services.

Without the Spring Framework

jsonrpc4j can be used without the spring framework as well. In fact, the client and server both work in an Android environment.

Client

Here's an example of how to use the client to communicate with the JSON-RPC service described above:

JsonRpcHttpClient client = new JsonRpcHttpClient(
    new URL("http://example.com/UserService.json"));

User user = client.invoke("createUser", new Object[] { "bob", "the builder" }, User.class);

Or, the ProxyUtil class can be used in conjunction with the interface to create a dynamic proxy:

JsonRpcHttpClient client = new JsonRpcHttpClient(
    new URL("http://example.com/UserService.json"));

UserService userService = ProxyUtil.createClientProxy(
    getClass().getClassLoader(),
    UserService.class,
    client);

User user = userService.createUser("bob", "the builder");

server

The server can be used without spring as well:

// create it
JsonRpcServer server = new JsonRpcServer(userService, UserService.class);

After having created the server it's simply a matter of calling one of the handle(...) methods available. For example, here's a servlet using the very same UserService:

class UserServiceServlet
    extends HttpServlet {

    private UserService userService;
    private JsonRpcServer jsonRpcServer;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        jsonRpcServer.handle(req, resp);
    }

    public void init(ServletConfig config) {
        //this.userService = ...
        this.jsonRpcServer = new JsonRpcServer(this.userService, Us
View on GitHub
GitHub Stars1.1k
CategoryDevelopment
Updated2d ago
Forks448

Languages

Java

Security Score

90/100

Audited on Mar 27, 2026

No findings