Java Guide

Contents

  1. Download and import
  2. Attributes of a response
  3. Using pre-defined responses
  4. Encoding responses to JSON format
  5. More pre-defined responses
  6. Including data in responses
  7. Adding lists
  8. Creating custom responses
  9. Decoding JSON text into Response objects

Download/import

You can automatically import Responz in your project using Maven or Gradle:

Maven:

<dependency>
  <groupId>com.raylabz</groupId>
  <artifactId>responz</artifactId>
  <version>1.0.2</version>
</dependency>

Gradle:

implementation 'com.raylabz:responz:1.0.2'

Alternatively, you can download Responz as a .jar library:

Download .jar
Attributes of a response

All responses contain four attributes, inherited from a base class called Response. These are:

  • status - is either "OK" or "ERROR" and is used to indicate the result of the request.
  • title - contains a title that very briefly describes the result of the request.
  • message - contains a message to the client describing the result in more detail.
  • timestamp - timestamp that indicates the time the request was processed.
  • data - (Optional) contains data returned related to the client's request. The data object will be omitted from any serialized JSON if it is not defined.

Using pre-defined responses

The library offers two existing responses that extend the Response base class by implicitly specifying the status. These are the SuccessResponse, which indicates that the user's request has been executed successfully (status = ok) and ErrorResponse, which indicates that an error occurred when trying the execute the request (status = error). The following example shows how to instantiate a simple response, a Success response and an Error response.

//A generic response:
Response response = new Response(ResponseStatus.OK, "My title", "My message");

//A SuccessResponse:
SuccessResponse successResponse = new SuccessResponse("Success", "This is a successful message.");

//An ErrorResponse:
ErrorResponse errorResponse = new ErrorResponse("Error", "This is an error message.");

Encoding responses to JSON format

You can encode a Response object into a JSON string using the toJSON() method:

//Create response:
SuccessResponse successResponse = new SuccessResponse("Success", "This is a successful message.");

//Encode a response to a JSON string:
String responseJSON = successResponse.toJSON();

This should produce the following JSON text:

{"status":"OK","title":"Success","message":"This is a successful message.","timestamp":"1551571200000"}
More pre-defined responses

There are some additional Response classes you can use. These are based on common responses that can be found in a large variety of projects.

  • InvalidParameterResponse - Commonly used when an invalid parameter is submitted in the request. For example, an integer was expected, but a string was found.
  • MissingParameterResponse - Commonly used when a parameter was expected but not provided.
  • SecurityResponse - Commonly used when a user makes a request that requires authentication/authorization and is denied access.
  • UnknownFailureResponse - Commonly used when something has gone wrong on the server side. This is usually used in conjunction with exceptions or other fault-dealing mechanisms.

For more information about pre-defined responses, check out the Documentation.

InvalidParameterResponse invalidParameterResponse = new InvalidParameterResponse("myParam", "An integer, found string.");

MissingParameterResponse missingParameterResponse = new MissingParameterResponse("myParam");

SecurityResponse securityResponse = new SecurityResponse();

UnknownFailureResponse unknownFailureResponse = new UnknownFailureResponse("A failure has occurred, please contact the administrator.");

Including data in responses

Each response has a data member of type JsonObject which allows insertion of an arbitrary number of other objects. This member is initially null and will therefore not be printed in any encoded JSON text.

Creating data objects:

You can directly add raw data (Strings, Characters, Numbers and Booleans) using the addProperty() method:

//Create a data object:
JsonObject data = new JsonObject();

//You can enter key-value pairs for Strings, Characters, Numbers and Booleans using the addProperty method:
data.addProperty("property1", 2);
data.addProperty("property2", "hello");
data.addProperty("property3", true);
data.addProperty("property4", 3.5);

You can also add your custom objects by converting them using GSON's toJsonTree() method:

//Example custom class:
class Person {

    private String firstname;
    private String lastname;
    private int age;

    public Person(String firstname, String lastname, int age) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

//Create a new object of the custom class:
Person person = new Person("John", "Doe", 50);

//Create an instance of Gson:
final Gson gson = new Gson();

//Use the toJsonTree method to convert the object to a JsonElement and add it to the response:
data.add("person", gson.toJsonTree(person));

You can then insert data into a response by providing it in the constructor:

Response response = new Response(ResponseStatus.OK, "My title", "My message", data);

Alternatively, you can use the setData() method after a response is initialized:

response.setData(data);

Adding lists

You can also add lists using the listToJsonArray() method in JsonUtil:

//Create an array list of numbers:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);

//Create the data object:
JsonObject data = new JsonObject();

//Convert the list using the listToJsonArray() method in JsonUtil and add it to the data object:
data.add("numbers", JsonUtil.listToJsonArray(numbers));

Creating custom responses

You can create your own custom response by extending the Response, SuccessResponse or ErrorResponse classes:

public class NumbersFrom1To10Response extends Response {

    public NumbersFrom1To10Response() {
        super(ResponseStatus.OK, "Numbers fetched", "The numbers from 1-10 have been fetched.");
        JsonObject data = new JsonObject();
        ArrayList<Integer> numbers = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            numbers.add(i);
        }
        data.add("numbers", JsonUtil.listToJsonArray(numbers));
        setData(data);
    }

}

Decoding JSON text into Response objects

You can decode JSON formatted text into a Response object using GSON's fromJson() method:

final Gson gson = new Gson();
final Response decodedResponse = gson.fromJson(jsonText, Response.class);

You can then get the values of statuses, titles, messages and raw and custom data properties using:

//Print the status, title and message:
ResponseStatus responseStatus = decodedResponse.getStatus();
String title = decodedResponse.getTitle();
String message = decodedResponse.getMessage();

//Get the value of raw values from the data object:
int property1 = decodedResponse.getData().get("property1").getAsInt();
String property2 = decodedResponse.getData().get("property2").getAsString();

//Get the value of custom objects from the data object:
Person person = gson.fromJson(decodedResponse.getData().get("person"), Person.class);

For more information on the Responz library, please visit the documentation.