News

A Java REST Client with Unirest

Posted: 2016-12-03 23:06:04. | By: John Flickinger

Intro

Given that I am a web person and that I recently learned how to build a REST API in NodeJS, I started getting curious about how sending HTTP requests would work in other languages and in particular Java. I found that the process is not nearly as awesome as it is in other languages. Fortunately, I found an awesome library called Unirest. Unirest does exactly what I wanted, but since it is fairly new there isn't much documentation on using it. After some trial and error, I found out how to do what I wanted. In particular, I found out how to make it interact with my Node REST server.

Setup

First things first, how do you install it? Well if you are using a Maven project, you must simply add it to the pom.xml as a dependency.

<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>

After adding it to your pom.xml you must then import it with Maven. In IntelliJ this can be done by right-clicking on the pom.xml file in the Project Explorer -> hovering over Maven -> and selecting reimport. Unirest is now ready to be used.

Making the requests

It's time to start interacting with the backend. but in-order to do so we first need to import it in Java.

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import org.json.JSONObject;

Now we need some data to send. For demonstration purposes, I will be creating a new device using a POST request. Let's create a JSON Object with the fields that need to be populated.

//The Data you want to send in JSON format
JSONObject deviceObj = new JSONObject()
.put("Device_Type_ID", 1)
.put("Device_Name", "name")
.put("Communication_Protocol_ID", 1)
.put("Icon_ID", 1)
.put("Location_ID", 1);

Now that the data is ready, it is time to make the request. This is super simple with UniRest. All that is needed is to create a response object where we can store the result after the HTTP request is complete. In this case, I will send a POST request to insert a device into the database. The information will be contained in the body of the HTTP request. In Unirest the JSONObject can simply be passed as an argument into the body method.

//The request you are sending to the server
HttpResponse<JsonNode> jsonResponse = Unirest.post("https://meshversion2-johnnyvf24.c9users.io/devices")
.header("Content-Type", "application/json")
.body(deviceObj)
.asJson();

After the request is made the HTTP status code can be checked to make sure everything went alright. 

//The device was inserted successfully
if(jsonResponse.getStatus() == 200) {
//Request was successful
} else if(jsonResponse.getStatus() == 400) {
//Something went wrong, tell the user there was an error
}

And in case further confirmation is required we will make a GET request to the same URL to see all the devices that are in the database.

//GET ALL the devices in the database
HttpResponse<JsonNode> response = Unirest.get("https://meshversion2-johnnyvf24.c9users.io/devices")
.header("Content-Type", "application/json")
.header("accept", "application/json")
.asJson();

//Print out all the devices returned, a big string of JSON
System.out.println(response.getBody());

//Put the devices into a JSON Object
JSONObject res = new JSONObject(response.getBody());

//Print out the response in a nicer format
System.out.println(res.toString(2));

The results are below:

[{"Communication_Protocol_ID":1,"Location_ID":2,"Device_Name":"toaster","Device_ID":2,"Device_Type_ID":1,"Icon_ID":2},{"Communication_Protocol_ID":1,"Location_ID":1,"Device_Name":"thermostat","Device_ID":3,"Device_Type_ID":1,"Icon_ID":1},{"Communication_Protocol_ID":1,"Location_ID":2,"Device_Name":"microwave","Device_ID":4,"Device_Type_ID":1,"Icon_ID":2},{"Communication_Protocol_ID":2,"Location_ID":1,"Device_Name":"Test","Device_ID":5,"Device_Type_ID":1,"Icon_ID":1},{"Communication_Protocol_ID":1,"Location_ID":1,"Device_Name":"Device12","Device_ID":6,"Device_Type_ID":1,"Icon_ID":1},{"Communication_Protocol_ID":1,"Location_ID":1,"Device_Name":"name","Device_ID":7,"Device_Type_ID":1,"Icon_ID":1},{"Communication_Protocol_ID":1,"Location_ID":1,"Device_Name":"name","Device_ID":8,"Device_Type_ID":1,"Icon_ID":1}]
{"array": [
  {
    "Communication_Protocol_ID": 1,
    "Location_ID": 2,
    "Device_Name": "toaster",
    "Device_ID": 2,
    "Device_Type_ID": 1,
    "Icon_ID": 2
  },
  {
    "Communication_Protocol_ID": 1,
    "Location_ID": 1,
    "Device_Name": "thermostat",
    "Device_ID": 3,
    "Device_Type_ID": 1,
    "Icon_ID": 1
  }

News/Blog section of the website is nearing completion

Posted: 2016-06-24 19:19:13. | By: John Flickinger



Welcome

Hello all and welcome to my first post! I am excited to give you guys some insight into what I have been doing for the last week. Feel free to completely ignore this post if this is not your "cup of tea". 


A slow beginning

Two months ago I was asked by the MESH developer team to make a blog where we could post some updates; I silently hated the idea. I mean, why should I spend countless hours making something that would simply distract me from the actual project, but worse than that was the idea that it might never be used. (You might think it far fetched for me to make such assumptions, but I still had a sour taste from a previous experience. In my prior employment, I received countless requests to make a polling/voting system and after I made it, it was barely even used.  Needless to say, I wasn't thrilled.) So then why did I change my mind?

Two weeks ago my boss approached me to start revamping the project website (this website) and after discussing some design aspects, my boss mentioned he wanted the website to have a way to post news updates. After some thinking I realized that the goal of a developer blog is very similar to a "news" section and although I had initially disliked the idea I started thinking one, I started thinking about it from technical standpoint. I mean what exactly would be required to do it? 

Unbeknownst to me, I was trapped in my own curiosity. 


How to start?

Needless to say, I started working on it. Obviously I couldn't simply write the blogs as static webpages, that was crude and more importantly it required that I be in "stand-by mode" to post new blog/news updates. Nope that was not acceptable. Then perhaps I should go the WordPress route? That peaked my interest a bit, but ultimately I decided against it. I won't explain why, but these guys share a similar opinion to my own. So then what should I do? 

I decided to do it myself. Not only would this be funner than trying to learn an established CMS system, but it would also be educational as this would be the first time I created such a system. 


Getting it done

Darn! Things were worst than I thought. I had designed the current version of the website off a bootstrap 3 template. I was creating everything through non-organized PHP scripts and that was getting repetitive. Oh how I longed for my Model-View-Controller workflow. So, I scrapped everything. I removed all my ill-written PHP scripts and started converting my project to a Codeigniter project. (If you are a Web Developer who still uses PHP and don't already have a MVC framework, I recommend you give Codeigniter an opportunity.) 

After converting the project to Codeigniter, I realized I had another problem, inorder for it to be a self-posting system I would need to add user-accounts, what a drag.... 

For the billionth time I made another log-in system. However, this one was a little bit different because it was designed only for administrators. (So don't ask for further details, you won't get any more info). 

After taking the initial layout from the bootstrap 3 template, I tore away all the html that I wouldn't need. I try to live by the KISS principle because I tend to over complicate every project I have ever worked on. After finishing the layout, I decided there was one thing I really wanted that I was not willing to compromise on. That was a tagging system. 

In summary this is the information that was required to make this work (Once I make a commenting system you'll be able to give me feedback.)

The database


CREATE TABLE `user` (
  `uid` int(11) NOT NULL,
  `email` varchar(255) NOT NULL,
  `fname` varchar(100) DEFAULT NULL,
  `lname` varchar(100) DEFAULT NULL,
  `access_level` int(11) NOT NULL,
  `password` varchar(60)
); 
ALTER TABLE `user`
  ADD PRIMARY KEY (`uid`);
CREATE TABLE `post_tags` (
  `post_tag_id` int(11) NOT NULL,
  `tid` int(11) NOT NULL,
  `pid` int(11) NOT NULL
);
ALTER TABLE `post_tags`
  ADD PRIMARY KEY (`post_tag_id`);
CREATE TABLE `post` (
  `post_id` int(11) NOT NULL,
  `uid` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` longtext NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `last_updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
);
ALTER TABLE `post`
  ADD PRIMARY KEY (`post_id`);
CREATE TABLE `tags` (
  `tid` int(11) NOT NULL,
  `name` varchar(120) NOT NULL,
  `uid` int(11) NOT NULL
)
ALTER TABLE `tags`
  ADD PRIMARY KEY (`tid`);

I know everything is far from perfect. (I mean I even ignored foreign keys).


The editor

The next step was actually being able to insert the required information into the database. The way I did this was simple, create a form which submits the data. However there was one small problem. How would I get all the fancy text we wanted? I decided to use a JS library called NicEdit. Not only was it simple to implement but it came with a sufficient amount of tools to use (Such as an image upload feature). NicEdit does just fine.

After uploading information and sanitizing it (against xss attacks etc...) , then it is stored into the database. There is one last part I want to mention, the tags. 

Tags

Implementing the tagging part was actually alot easier than I though it would be. All it involved was searching to see if a tag was already inserted and if not creating a new tag. There may be better ways to do this, but this worked for me. Finally a made a filter to search posts based on their tags. It works, but it needs alot of work. Feel free to send me some feedback, under CONTACT if you have any questions.

About

This is a project conducted within the iCREDITS smart grid research center at New Mexico State University. It is funded by the National Science Foundation. Although we are still in the early stages of development, we have high hopes that the project will be successful!

Get Involved

Are you interested in Home Automation? Want to learn more about the Internet of Things? Or are you looking for some practical experience with real systems? We are always looking for enthusiastic contributors. Find out how!

Contact

Science Hall, Room #134
New Mexico State University
Las Cruces, NM 88001