Posts Tagged ‘JSON’

Are you working with multiple devices like iPhone, Android and Web then take a look at this post that explains you how to develop a RESTful API in PHP.  Representational state transfer (REST) is a software system for distributing the data to different kind of applications. The web service system produce status code response in JSON or XML format.
Create a RESTful Services API in PHP.


Download Script

Database
Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.

CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API Class: api.php
Contains simple PHP code, here you have to modify database configuration details like database name, username and password.

<?php
require_once(“Rest.inc.php”);class API extends REST
{
public $data = “”;
const DB_SERVER = “localhost”;
const DB_USER = “Database_Username”;
const DB_PASSWORD = “Database_Password”;
const DB = “Database_Name”;private $db = NULL;

public function __construct()
{
parent::__construct();// Init parent contructor
$this->dbConnect();// Initiate Database connection
}

//Database connection
private function dbConnect()
{
$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

//Public method for access api.
//This method dynmically call the method based on the query string
public function processApi()
{
$func = strtolower(trim(str_replace(“/”,””,$_REQUEST[‘rquest’])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response(”,404);
// If the method not exist with in this class, response would be “Page not found”.
}

private function login()
{
…………..
}

private function users()
{
…………..
}

private function deleteUser()
{
………….
}

//Encode array into JSON
private function json($data)
{
if(is_array($data)){
return json_encode($data);
}
}
}

// Initiiate Library
$api = new API;
$api->processApi();
?>

Login POST
Displaying users records from the users table Rest API URL http://localhost/rest/login/. This Restful API login status works with status codes if status code 200 login success else status code 204 shows fail message. For more status code information check Rest.inc.php in download script.

private function login()
{
// Cross validation if the request method is POST else it will return “Not Acceptable” status
if($this->get_request_method() != “POST”)
{
$this->response(”,406);
}$email = $this->_request[’email’];
$password = $this->_request[‘pwd’];// Input validations
if(!empty($email) and !empty($password))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_email = ‘$email’ AND user_password = ‘”.md5($password).”‘ LIMIT 1″, $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everythig is good send header as “OK” and user details
$this->response($this->json($result), 200);
}
$this->response(”, 204); // If no records “No Content” status
}
}

// If invalid inputs “Bad Request” status message and reason
$error = array(‘status’ => “Failed”, “msg” => “Invalid Email address or Password”);
$this->response($this->json($error), 400);
}

Users GET
Displaying users records from the users table Rest API URL http://localhost/rest/users/

private function users()
{
// Cross validation if the request method is GET else it will return “Not Acceptable” status
if($this->get_request_method() != “GET”)
{
$this->response(”,406);
}
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1”, $this->db);
if(mysql_num_rows($sql) > 0)
{
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
{
$result[] = $rlt;
}
// If success everythig is good send header as “OK” and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response(”,204); // If no records “No Content” status
}

DeleteUser
Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/

private function deleteUser()
{if($this->get_request_method() != “DELETE”){
$this->response(”,406);
}
$id = (int)$this->_request[‘id’];
if($id > 0)
{
mysql_query(“DELETE FROM users WHERE user_id = $id”);
$success = array(‘status’ => “Success”, “msg” => “Successfully one record deleted.”);
$this->response($this->json($success),200);
}
else
{
$this->response(”,204); // If no records “No Content” status
}
}

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

.htaccess code
Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

 

Bull Wrestling Bear Markets: Testosterone-driven

With the release of version 2.0 Facelet templating became a core part of the JSF specification. Using <ui:composition> and <ui:decorate> tags it becomes pretty easy to build up complicated pages whilst still keeping your mark-up clean. Templates are particularly useful when creating HTML forms but, unfortunately, do tend to cause repetition in your xhtml files, breaking the DRY (Don’t Repeat Yourself) principal of good software design. As part of a project to provide deeper integration between JSF and Spring I have developed a couple of new components that aim to make templating easier. Before diving into the new components, lets look at how a typical form might be built up using standard JSF templates.

Often the initial starting point with form templates is to add some boiler plate surround to each input. Often you need extra <div> or tags for your css to use. Here is a typical example:

01 <!-- /WEB-INF/pages/entername.xhtml -->
02 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
03   <h:inputText id="firstName" label="First Name" value="#{bean.firstName}"/>
04   <ui:param name="label" value="First Name"/>
05   <ui:param name="for" value="firstName"/>
06 </ui:decorate>
07 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
08   <h:inputText id="lastName" label="Last Name" value="#{bean.lastName}"/>
09   <ui:param name="label" value="Last Name"/>
10   <ui:param name="for" value="lastName"/>
11 </ui:decorate>
12 <!-- Many additional form elements -->
1 <!-- /WEB-INF/layout/form.xhtml -->
2 <ui:composition>
3   <div class="formElement">
4     <span class="formLabel">
5       <h:outputLabel for="#{for}" label="#{label}">
6     </span>
7     <ui:insert/>
8   </div>
9 </ui:composition>

Here we can see that each item on the form is contained within a <div> and form labels are wrapped in an additional <span>. There is already some repetition in the mark-up, with the “for” parameter mirroring the component ID. I have also given each <h:inputText> element a label attribute
for better validation error messages, this is repeated in the “label”. Things start getting worse if we want to mark required fields with an asterisk:

01 <!-- /WEB-INF/pages/entername.xhtml -->
02 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
03   <h:inputText id="firstName" label="First Name" value="#{bean.firstName}" required="false"/>
04   <ui:param name="label" value="First Name"/>
05   <ui:param name="for" value="firstName"/>
06   <ui:param name="showAsterisk" value="false"/>
07 </ui:decorate>
08 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
09   <h:inputText id="lastName" label="Last Name" value="#{bean.lastName}" required="true"/>
10   <ui:param name="label" value="Last Name"/>
11   <ui:param name="for" value="lastName"/>
12   <ui:param name="showAsterisk" value="true"/>
13 </ui:decorate>
14 <!-- Many additional form elements -->
1 <!-- /WEB-INF/layout/form.xhtml -->
2 <ui:composition>
3   <div class="formElement">
4     <span class="formLabel">
5       <h:outputLabel for="#{for}" label="#{label}#{showAsterisk ? ' *' : ''}">
6     </span>
7     <ui:insert/>
8   </div>
9 </ui:composition>

It’s pretty frustrating that we need to pass <ui:param> items that duplicate attributes already specified on the <h:inputText>. It is easy to see how, even for relatively small forms, we are going to end up with a lot of duplication in our mark-up. What we need is a way to get information about the inserted component inside the template, even though we don’t know what type of component it will be. What we need is <s:componentInfo>.

The <s:componentInfo> component exposes a variable containing information about the inserted component. This information includes the label, the component clientID and if the component is required. By inspecting the inserted item we can remove a lot of duplication:

1 <!-- /WEB-INF/pages/entername.xhtml -->
2 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
3   <h:inputText id="firstName" label="First Name" value="#{bean.firstName}" required="false"/>
4 </ui:decorate>
5 <ui:decoreate template="/WEB-INF/layout/form.xhtml">
6   <h:inputText id="lastName" label="Last Name" value="#{bean.lastName}" required="true"/>
7 </ui:decorate>
8 <!-- Many additional form elements -->
01 <!-- /WEB-INF/layout/form.xhtml -->
02 <ui:composition>
03   <s:componentInfo var="info">
04     <div class="formElement">
05       <span class="#{info.valid ? 'formLabel' : 'formErrorLabel'}">
06         <h:outputLabel for="#{info.for}" label="#{info.label}#{info.required ? ' *' : ''}">
07       </span>
08       <ui:insert/>
09     </div>
10   </s:componentInfo>
11 </ui:composition>

Something else that we can now do is tell if the inserted component has failed validation. Notice that the example above will pick the “formErrorLabel” CSS class for components that are not valid.

One interesting feature of having the new <s:componentInfo> component is that all the <ui:decorate> tags become identical. We have removed all the repetition inside the tag, but the tag itself is still repeated many times. Here we have one more trick that can help by introducing a new <s:decorateAll> tag. Using <s:decorateAll> allows use to apply a template once for every child component. Here is the updated form mark-up:

1 <!-- /WEB-INF/pages/entername.xhtml -->
2 <s:decoreateAll template="/WEB-INF/layout/form.xhtml">
3   <h:inputText id="firstName" label="First Name" value="#{bean.firstName}" required="false"/>
4   <h:inputText id="lastName" label="Last Name" value="#{bean.lastName}" required="true"/>
5   <!-- Many additional form elements -->
6 </s:decorateAll>
01 <!-- /WEB-INF/layout/form.xhtml -->
02 <ui:composition>
03   <s:componentInfo var="info">
04     <div class="formElement">
05       <span class="#{info.valid ? 'formLabel' : 'formErrorLabel'}">
06         <h:outputLabel for="#{info.for}" label="#{info.label}#{info.required ? ' *' : ''}">
07       </span>
08       <ui:insert/>
09     </div>
10   </s:componentInfo>
11 </ui:composition>

If you want to look at the source code for these components check out the org.springframework.springfaces.template.ui package on springfaces GitHub project.

Diagram of Unicast Streaming

Since Gson version 1.6, two new classes – JsonReader and JsonWriter, are introduce to provide streaming processing on JSON data. Read this Gson streaming documentation to understand what are the benefits of using it.

Here we show you two full examples of using following Gson streaming APIs to read and write JSON data.

  1. JsonWriter – Streaming write to JSON.
  2. JsonReader – Streaming read from JSON.

Gson streaming processing is fast, but difficult to code, because you need to handle each and every detail of processing JSON data.

1. JsonWriter

In this example, you use “JsonWriter” to write JSON data into a file name “file.json“. See comments for self-expalantory.

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.stream.JsonWriter;

public class GsonStreamExample {
   public static void main(String[] args) {

     JsonWriter writer;
     try {
	writer = new JsonWriter(new FileWriter("c:\\user.json"));

	writer.beginObject(); // {
	writer.name("name").value("mkyong"); // "name" : "mkyong"
	writer.name("age").value(29); // "age" : 29

	writer.name("messages"); // "messages" : 
	writer.beginArray(); // [
	writer.value("msg 1"); // "msg 1"
	writer.value("msg 2"); // "msg 2"
	writer.value("msg 3"); // "msg 3"
	writer.endArray(); // ]

	writer.endObject(); // }
	writer.close();

	System.out.println("Done");

     } catch (IOException e) {
	e.printStackTrace();
     }

   }

}

As result, following new file named “file.json” is created :

{
	"name":"mkyong",
	"age":29,
	"messages":["msg 1","msg 2","msg 3"]
}

2. JsonReader

Example to use “JsonReader” to parse or read above file “file.json”.

Token
In streaming mode, every JSON “data” is consider as an individual token. When you use JsonReaderto process it, each tokens will be processed sequential.For example,

{
	"url":"www.mkyong.com"
}

Token 1 = “{”
Token 2 = “url”
Token 3 = “www.mkyong.com”
Token 4 = “}”

As result, you need to keep calling “next****” method to move to next token manually.

See full example.

package com.mkyong.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.stream.JsonReader;

public class GsonStreamExample {
   public static void main(String[] args) {

     try {
	JsonReader reader = new JsonReader(new FileReader("c:\\user.json"));

	reader.beginObject();

	while (reader.hasNext()) {

	  String name = reader.nextName();

	  if (name.equals("name")) {

		System.out.println(reader.nextString());

	  } else if (name.equals("age")) {

		System.out.println(reader.nextInt());

	  } else if (name.equals("message")) {

		// read array
		reader.beginArray();

		while (reader.hasNext()) {
			System.out.println(reader.nextString());
		}

		reader.endArray();

	  } else {
		reader.skipValue(); //avoid some unhandle events
	  }
        }

	reader.endObject();
	reader.close();

     } catch (FileNotFoundException e) {
	e.printStackTrace();
     } catch (IOException e) {
	e.printStackTrace();
     }

   }

}

Output

mkyong
29
msg 1
msg 2
msg 3

JSON Card -- Front

JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a very good alternative solution.

In this series of Java JSON tutorials, we focus on three popular third party Java libraries to process JSON data, which are Jackson, Google Gson and JSON.simple

 

JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).

Note
To convert object to / from JSON, you should consider Jackson or Gson.

In this tutorial, we show you how to use JSON.simple to read and write JSON data from / to a file.

1. JSON.simple Dependency

JSON.simple is available at Maven central repository, just declares following dependency in your pom.xml file.

  <dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
  </dependency>

2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonSimpleExample {
     public static void main(String[] args) {

	JSONObject obj = new JSONObject();
	obj.put("name", "mkyong.com");
	obj.put("age", new Integer(100));

	JSONArray list = new JSONArray();
	list.add("msg 1");
	list.add("msg 2");
	list.add("msg 3");

	obj.put("messages", list);

	try {

		FileWriter file = new FileWriter("c:\\test.json");
		file.write(obj.toJSONString());
		file.flush();
		file.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

	System.out.print(obj);

     }

}

Output – See content of file named “test.json“.

{
	"age":100,
	"name":"mkyong.com",
	"messages":["msg 1","msg 2","msg 3"]
}

3. Read JSON from file

Use JSONParser to read above generated JSON file “test.json“, and display each of the values.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample {
     public static void main(String[] args) {

	JSONParser parser = new JSONParser();

	try {

		Object obj = parser.parse(new FileReader("c:\\test.json"));

		JSONObject jsonObject = (JSONObject) obj;

		String name = (String) jsonObject.get("name");
		System.out.println(name);

		long age = (Long) jsonObject.get("age");
		System.out.println(age);

		// loop array
		JSONArray msg = (JSONArray) jsonObject.get("messages");
		Iterator iterator = msg.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ParseException e) {
		e.printStackTrace();
	}

     }

}

Output

mkyong.com
100
msg 1
msg 2
msg 3