Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
Buy OSRS Gold

Sell OSRS Gold
Sign in to follow this  
orange451

JRest - Dependency-less REST call library

Recommended Posts

Posted (edited)

Hey all, 

For a project I'm working on in Tribot, I found I needed to make some rest calls to a back-end server. While in the enterprise world I'd normally use Spring or some other large library, they wont work in Tribot due to their heavy use of reflection and massive startup-times. I've written a pretty light-weight REST call library and wanted to share it here for anyone interested! This library is super tiny (1 package) and starts almost instantly, so it's very bot friendly. A lot of other restful libraries take a long time to turn on, which gets in the way of starting scripts.

 

Website: https://jrest.io/

Source: https://github.com/orange451/JRest

 

With it, you can either host your own rest-server endpoints, or make a call to any rest endpoint. I should note, that by Dependency-less, I mean that it doesn't need any other dependencies to function. However DTO/POJO serialization/deserialization requires Gson (in Tribot dependencies folder)

 

What could you benefit from using REST calls? What can you do with them?

  • Simplify your client/server communication protocols
  • Make global statistics for your scripts easier!
  • Communicate to Muels/other clients

 

Here's some examples:

Synchronous GET Request:

RequestEntity<String> request = new RequestEntity<>(HttpMethod.GET);
ResponseEntity<String> response = request.exchange("http://localhost/testAPI", String.class);
System.out.println(response.getBody());

 

Asynchronous GET Request:

RequestEntity<JsonObject> request = new RequestEntity<>(HttpMethod.GET);
request.exchangeAsync("http://localhost/testJson", JsonObject.class, (response)->{
	System.out.println(response.getBody());
});

 

REST Server:

public class TestServer extends RestServer {
	public TestServer() {
		
		/**
		 * Test Endpoint. Returns static String
		 */
		this.addEndpoint(HttpMethod.GET, "/testAPI", (request)->{
			return new ResponseEntity<String>(HttpStatus.OK, "Hello From Server!");
		});
		
		/**
		 * Test Post endpoint. Returns your posted data back to you.
		 */
		this.addEndpoint(HttpMethod.POST, "/testPost", MediaType.ALL, MediaType.ALL, (request)->{
			return new ResponseEntity<String>(HttpStatus.OK, request.getBody().toString());
		});
		
		/**
		 * Test JSON endpoint. Returns a JSON object.
		 */
		this.addEndpoint(HttpMethod.GET, "/testJson", MediaType.ALL, MediaType.APPLICATION_JSON, (request)->{
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("TestKey", "Hello World!");
			
			return new ResponseEntity<JsonObject>(HttpStatus.OK, jsonObject);
		});
	}
	
	@Override
	public int getPort() {
		return 80;
	}

	public static void main(String[] args) {
		new TestServer();
	}
}

 

Any feedback is welcome!

 

Some notes:

  • By default data is sent over the network as a String. The rest endpoint methods and exchange methods contain a generic T class type operator that lets you better control what type of data you are sending.
    • Strings, Lists, and Maps can be sent over the network out-of-the box.
    • If you use DaxWalker, you can use JSONObject and JSONArray as they extend Map and list (see above)
    • Custom DTO objects and JsonElement types can be sent over network using GSON Library (Comes with tribot)
  • This can be used to not only make REST calls, but also host REST Endpoints
    • It follows standard HTTP protocol, so your hosted REST Endpoints also work as a Web Server (NOT TESTED WITH HTTPS)
Edited by orange451
  • Like 2

Share this post


Link to post
Share on other sites
Posted (edited)

Small update. I added a way to specify what type of data is expected for a given REST Endpoint. Example:

Server:

/**
 * Test Post endpoint. Returns your posted data back to you.
 */
this.addEndpoint(HttpMethod.POST, "/GetEmployee", JsonObject.class, (request)->{
	JsonObject payload = request.getBody();
	int id = payload.get("id").getAsInt();
	
	String[] names = {
			"Frank",
			"Jeff",
			"Oliver",
			"Maxwell"
	};
	
	JsonObject response = new JsonObject();
	response.addProperty("id", id);
	response.addProperty("name", names[id-1]);
	
	return new ResponseEntity<JsonObject>(HttpStatus.OK, response);
});

 

Client:

JsonObject body = new JsonObject();
body.addProperty("id", 1);
RequestEntity<JsonObject> request = new RequestEntity<>(HttpMethod.POST, body);
request.exchangeAsync("http://localhost/GetEmployee", JsonObject.class, (response)->{
	JsonObject payload = response.getBody();
	System.out.println("Employee data: ");
	System.out.println("\tid: " + payload.get("id").getAsInt());
	System.out.println("\tname: " + payload.get("name"));
});

 

 

[EDIT]

Another update. Allows you to return DTO objects

public class TestDTO {

	public TestDTO() throws MalformedURLException {
		// Create payload
		JsonObject body = new JsonObject();
		body.addProperty("id", 1);
		
		// Create request object
		RequestEntity<JsonObject> request = new RequestEntity<>(HttpMethod.POST, body);
		
		// Send request to server
		request.exchangeAsync("http://localhost/GetEmployee", Employee.class, (response)->{
			Employee employee = response.getBody();
			System.out.println("Employee data: ");
			System.out.println("\tid: " + employee.getId());
			System.out.println("\tname: " + employee.getName());
		});
	}

	public static void main(String[] args) throws MalformedURLException, IOException {
		new TestDTO();
	}
}

/**
 * DTO used to represent employee information sent from server.
 */
class Employee {
	private int id;
	
	private String name;
	
	public Employee() {
		//
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() {
		return this.name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
}

 

Edited by orange451

Share this post


Link to post
Share on other sites

Another update. You can now specify to use HTML as a MediaType in Rest Endpoints.

 

Server:

/**
 * Test Endpoint. Returns static String
 */
this.addEndpoint(HttpMethod.GET, "/", MediaType.TEXT_HTML, (request)->{
	return new ResponseEntity<String>(HttpStatus.OK, "<h1>Index! Welcome to JREST!</h1>");
});

 

Client:

jrYyeFv.png

Share this post


Link to post
Share on other sites
Posted (edited)

Internally this uses sockets, so it's just as lightweight. What this does for you, is make a super convenient way to listen or send specific types of data that needs to be communicated from one place to another. Manually writing all that stuff with sockets leads to a very bloated/messy project. This helps you keep it clean, and also respects HTTP protocol, so you can easily interface this with many other applications on the internet!

 

Also, things like POJO serialization is super useful. An example would be, if you have a class that contains all of the skills for your player...

public class PlayerStats {
	private String playerName;
	private int attack;
	private int strength;
	private int detense;
  
	// Write getters & setters
  	// Required for deserialization
}

This class can be sent to your server via:

PlayerStats stats = new PlayerStats("orange451", 99, 64, 50);
new RequestEntity<>(HttpMethod.POST, playerStats).exchangeAsync("http://serverip/PostStats");

The server could then read your data via:

server.addEndpoint(HttpMethod.POST, "/PostStats", PlayerStats.class, (request)->{
	PlayerStats stats = request.getBody();
  	// Write some code to write these stats to a database here
  	return new ResponseEntity<>(HttpStatus.OK);
});

 

Much cleaner than manually doing all this!

Edited by orange451

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Our picks

    • Hello everyone,

      Last week we tried to roll out Auth0 Login, but we lost that battle. Now it's time to win the war!

      Important changes

      When logging into the client, you'll now have to enter your Auth0 account credentials instead of your forums credentials

      Note: 2FA is still handled through your forums account (for the time being)



      Changes for existing users

      You'll have to link your Auth0 account to your forums account here: https://tribot.org/forums/settings/login/?service=11


      Auth0 accounts have been created for most existing users. Please use your forums email address and password to login.



      Important notes

      Make sure to verify your email address upon creating a new Auth0 account


      When we mention your Auth0 account, we mean your account used for auth.tribot.org as displayed below
      • 69 replies
    • To better support the upcoming changes (TRiBot X, new repository), we're switching our login handler to Auth0. Instead of logging in with the standard form, you'll now be required to login through our Auth0 application.

      All existing accounts which have been used within approximately the past year have been imported into Auth0 using the same email and password combination which has been stored on the forums.

      What does this mean for users?

      Your account credentials are now even more securely stored


      You'll be able to login via Facebook, Google, and others in the future


      Is there anything users have to do differently now?

      Existing users: You'll have to login with the standard login, open your Account Settings, then link your Auth0 account


      New users: You'll be redirected to our Auth0 app (auth.tribot.org) where you'll be able to create an account


      Why was this change made?

      The new apps we are creating (such as the new repository) aren't able to use the forums to handle user logins


      To centralize all user accounts in one area


      To ensure that the client login doesn't go down when the forums are having problems


      To speed up our development


      Other considerations

      There's no documentation or official support for using Invision Community combined with Auth0, so there are still a few kinks we're working out


      We're in the works of creating an account management panel specifically for Auth0 accounts (ETA August)


      It's not possible to change email addresses for the time being (this will be resolved this August)


      Changing passwords is a weird process for the time being. To change your password, you'll have to use the "Don't remember your password" tool on the Auth0 login page
      • 11 replies
    • Over the past month, we've been working hard on TRiBot's new repository - a much needed update. This change has been deemed necessary for TRiBot X, and will allow us to really speed up development of all aspects of TRiBot.

      Today we are going to share what we've been working on!


      Now you must be wondering what kind of features the new repository will have.... well, you'll have to be patient for a little while longer. We're still figuring out various technical aspects so we can't provide answers to all possible questions. We're also focusing on development rather than writing about it so that everyone can get access to our latest developments at lightning speed. I will however answer a few users' questions.

      We're planning on a release of this early to mid August, giving users some goodies before TRiBot X's release.

      Thank you all for being patient. I hope everyone is excited as much as I am!
      • 17 replies
    • Over the past few months, I’ve been working diligently on a new project - TRiBot X. Everything has been written from the ground up, with all of the best practices of software engineering. Every aspect of TRiBot has been re-imagined to support three main goals: flexibility, useability, and reliability.
      • 50 replies
    • Come give us feedback on the next version of TRiBot!
      • 86 replies
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...