Wednesday Mar 25, 2009

Consuming PHP Zend Rest API in Java

Share/Save/Bookmark<script type="text/javascript">a2a_linkname="Consuming PHP Zend Rest API in Java";a2a_linkurl="http://blogs.sun.com/divyen/entry/consuming_php_zend_rest_api";</script><script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script>

In my last Weblog entry, I described the steps on developing Rest API in PHP using Zend Framework.
Now we have Rest API ready to be consumed by the client. Let consume it using Java Client.

Before beginning the coding part, we need to download following library.

The Jakarta Commons HttpClient 3.1 Library
http://mirror.olnevhost.net/pub/apache/httpcomponents/commons-httpclient/binary/commons-httpclient-3.1.tar.gz

Apache Commons Logging Library
http://mirrors.kahuki.com/apache/commons/logging/binaries/commons-logging-1.1.1-bin.tar.gz

Apache Commons Codec Library
http://download.nextag.com/apache/commons/codec/binaries/commons-codec-1.3.tar.gz

First of all lets create the new NetBeans project. Select “java” from the project categories and “java Application” from the projects list. Click Next, name your project as “zend_rest_client” and finally click Finish button.

Snap-1
Snap-1
Snap-2
Snap-2

Right click on the Library and Select the Property. Add downloaded Library files using “Add Jar/Folder”.

Snap-3
Snap-3

Click “OK” and then replace the content of Main.Java file with the following code.

package zend_rest_client;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.\*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/\* @author divyen patel \*/

public class Main {

    public static void main(String[] args) throws IOException, SAXException {
        String str_REST_SERVER = "http://localhost";
        String str_Port = "80"; //Default Apache Port

        String str_rest_API_page = "weather_rest.php";
        String str_rest_method = "get_temperature";
        String str_rest_method_argument = "zipcode=95035";

        String str_rest_url = str_REST_SERVER + ":" + str_Port + "/" + str_rest_API_page + "?method=" + str_rest_method + "&" + str_rest_method_argument;
        System.out.println("Request URL:" + str_rest_url + "\\n");


        // Send GET request
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(str_rest_url);


        int statusCode = client.executeMethod(method);

        InputStream rstream = null;
        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
        String line;
        String xmlString = "";

        while ((line = br.readLine()) != null) {
            xmlString = xmlString + line;
        }

        System.out.println("Request Response:" + xmlString + "\\n");

        //Parsing XML Response

        DOMParser parser = new DOMParser();

        parser.parse(new InputSource(new StringReader(xmlString)));

        Document document = parser.getDocument();
        System.out.println("Parsing XML Response");
        if (document.getElementsByTagName("status").item(0).getTextContent().equals("passed")) {
            System.out.println("Status: Passed");
            System.out.println("zipcode:" + document.getElementsByTagName("zipcode").item(0).getTextContent());
            System.out.println("tempHigh:" + document.getElementsByTagName("tempHigh").item(0).getTextContent());
            System.out.println("templow:" + document.getElementsByTagName("templow").item(0).getTextContent());
        } else {
            System.out.println("Status: Failed");
        }
    }
}


Finally right click on the project and Build it. You may see some warnings stating “DOMParser is Sun proprietary API and may be removed in a future release”. You can ignore these warnings.

Run the project and see the output in the IDE
Snap-4
Snap-4

You can also test it in the terminal console, using "java -jar <location of the jar file>"
Snap-5
Snap-5

If you have any better solution for consuming REST API in Java, please share with me. I am egar to learn it.

Saturday Feb 28, 2009

Developing Rest APIs in PHP using the Zend Framework

Share/Save/Bookmark<script type="text/javascript">a2a_linkname="Developing Rest APIs in PHP using the Zend Framework";a2a_linkurl="http://blogs.sun.com/divyen/entry/developing_a_rest_apis_in";</script><script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script>

Developing Rest APIs in PHP using the Zend Framework is as quick as a wink.
Lets begin with the installation and environment setup. I assume you are running OpenSolaris.

Step-1: Installation and Configuration of AMP [Note: skip this if you have already setup and configured AMP]
bash# su - root
bash# pkg refresh
bash# pkg install amp
bash# /usr/sbin/svccfg import /var/svc/manifest/network/http-apache22.xml
bash# /usr/sbin/svcadm enable http:apache22
bash# /usr/sbin/svccfg import /var/svc/manifest/application/database/mysql.xml
bash# /usr/sbin/svcadm enable mysql:version_50


Step-2: Installation and Configuration of Zend Framework.
bash# cd /usr/php/lib
bash# wget http://framework.zend.com/releases/ZendFramework-1.7.5/ZendFramework-1.7.5.tar.gz
bash# tar -xzf ZendFramework-1.7.5.tar.gz


Edit php.ini file and set the include_path variable to include Zend framework library path.
bash# vi /etc/php/5.2/php.ini

Add “include_path”, if it does not exists. If it is already set, just add path to the zend library at the end. Make sure to use “:” path separator.

include_path = ".:/usr/php/lib/ZendFramework-1.7.5/library"

bash# svcadm restart svc:/network/http:apache22


Step-3: Create Sample Database for Weather REST API.
Lets create the sample database for weather REST API.
bash# /usr/mysql/5.0/bin/mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \\g.
Your MySQL connection id is 1
Server version: 5.0.67 Source distribution
Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.

mysql> create database weatherdb;
Query OK, 1 row affected (0.00 sec)

mysql>use weatherdb;
Database changed


create tbl_zip_temperature table using following query.
create table tbl_zip_temperature (zip_code char(5), day_highest_temp int, day_lowest_temp int, PRIMARY KEY (zip_code));

mysql> create table tbl_zip_temperature (
-> zip_code char(5),
-> day_highest_temp int,
-> day_lowest_temp int,
-> PRIMARY KEY (zip_code)
-> );
Query OK, 0 rows affected (0.00 sec)



Lets dump in some dummy records with following queries.

insert into tbl_zip_temperature values(95035,67,52);
insert into tbl_zip_temperature values(95112,70,54);
insert into tbl_zip_temperature values(95032,70,50);

mysql> insert into tbl_zip_temperature values(95035,67,52);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tbl_zip_temperature values(95112,70,54);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tbl_zip_temperature values(95032,70,50);
Query OK, 1 row affected (0.00 sec)



Step-4: Create Weather REST API using Zend Framework Library.
Here we are all set to begin the coding.
Lets create the weather_rest.php file under the document root (/var/apache2/2.2/htdocs) with following code.
 
<?php
include_once ('Zend/Rest/Server.php');

function get_temperature($zipcode) {
    //error_code=0 for Sucesss / error_code=1 for Failure
    $error_code = 0;

    $doc = new DOMDocument();
    $doc->formatOutput = true;

    // Creating Responce Element
    $root_element = $doc->createElement("response");
    $doc->appendChild($root_element);

    //Create MYSQL Connection
	
    $MYSQL_DB_IP='localhost';
    $MYSQL_DB_USER='root';
    $MYSQL_DB_PASS='';
    $MYSQL_DB_NAME='weatherdb';
	
    $conn = new mysqli($MYSQL_DB_IP, $MYSQL_DB_USER, $MYSQL_DB_PASS , $MYSQL_DB_NAME);
    $sql = "select day_highest_temp, day_lowest_temp from tbl_zip_temperature where zip_code='".$zipcode."';";
    $result = $conn->query($sql);
    
    if ($result === false) {
        $error_code = 1;
    }
    else {
        if ($conn->affected_rows > 0) {        
		$row = $result->fetch_assoc();	
                $zip_element = $doc->createElement("zipcode");
                $zip_element->appendChild($doc->createTextNode($zipcode));
                $temp_high_element = $doc->createElement("tempHigh");
                $temp_high_element->appendChild($doc->createTextNode($row["day_highest_temp"]));
                $temp_low_element = $doc->createElement("templow");
                $temp_low_element->appendChild($doc->createTextNode($row["day_lowest_temp"]));
                $root_element->appendChild($zip_element);
                $root_element->appendChild($temp_high_element);
                $root_element->appendChild($temp_low_element);
        }
        else {
            $error_code = 1;
        }
    }
    
   //Return status failed, if any error found.
    if ($error_code == 1) {
        $statusElement = $doc->createElement("status");
        $statusElement->appendChild($doc->createTextNode("failed"));
        $root_element->appendChild($statusElement);
    }
    // Return status passed, if no error found
    else if ($error_code == 0) {
        $statusElement = $doc->createElement("status");
        $statusElement->appendChild($doc->createTextNode("passed"));
        $root_element->appendChild($statusElement);
    }
    return simplexml_load_string($doc->saveXML());
}

$server = new Zend_Rest_Server();
$server->addFunction('get_temperature');
$server->handle();

?>


That's all, you are done with creating REST API. Lets open the firefox, to test this API.
Type in following URL in the address bar and hit enter.
http://localhost/weather_rest.php?method=get_temperature&zipcode=95035

Output of the REST API call with the status passed
Snapshot1:http://blogs.sun.com/divyen/resource/rest_api_php_01.png

if you hit http://localhost/weather_rest.php?method=get_temperature&zipcode=95055, you will get the output as given below. There is no record for this zip code in the database.

Output of the REST API call with the status failed
Snapshot1:http://blogs.sun.com/divyen/resource/rest_api_php_02.png

if you hit http://localhost/weather_rest.php?method=get_temperature, without any argument, you will get the output as given below.

Output of the REST API call without proper argument
Snapshot1:http://blogs.sun.com/divyen/resource/rest_api_php_03.png

You can also consume this RESTfull API in your Java Application. I will blog about it in my next post.

For Detailed explanation on “Zend_Rest_Server”, visit Zend Framework - Programmer Reference Guide

Don't forget to leave your feedback :)

Sunday Oct 26, 2008

Install and configure libssh2 and ssh2 PECL module with AMP on OpenSolaris

Detailed information on libssh2 and SSH2 PECL module is available on

libssh2 - http://www.libssh2.org/wiki/index.php/Main_Page
SSH2 PECL Module - http://pecl.php.net/package/ssh2
Installing AMP on OpenSolaris is quite easy. below are the steps [1-4] for AMP stack installation.

[ Step:1 ]

-bash-3.2# pkg refresh
-bash-3.2#

[ Step:2 ]        
                   
-bash-3.2# pkg install amp
DOWNLOAD                                    PKGS       FILES     XFER (MB)
Completed                                  13/13   1633/1633 331.59/331.59

PHASE                                        ACTIONS
Update Phase                                     2/2
Install Phase                              2111/2111
-bash-3.2#

[ Step:3 ]

-bash-3.2# /usr/sbin/svccfg import /var/svc/manifest/network/http-apache22.xml
-bash-3.2# /usr/sbin/svcadm enable http:apache22
-bash-3.2#

[ Step:4 ]

-bash-3.2# /usr/sbin/svccfg import /var/svc/manifest/application/database/mysql.xml
-bash-3.2# /usr/sbin/svcadm enable mysql:version_50
-bash-3.2#


before we begin downloading libssh2 from sourceforge. We need to have gcc compiler installed to compile and build libssh2 library.

[ Step:5 ]

-bash-3.2# pkg install gcc-dev
DOWNLOAD                                    PKGS       FILES     XFER (MB)
Completed                                  18/18   2797/2797 105.65/105.65

PHASE                                        ACTIONS
Install Phase                              3545/3545


[ Step:6 ]

Download and extract libssh2 distribution.

-bash-3.2# cd /usr/src
-bash-3.2# wget http://voxel.dl.sourceforge.net/sourceforge/libssh2/libssh2-0.18.tar.gz
-bash-3.2# gunzip libssh2-0.18.tar.gz
-bash-3.2# tar xvf libssh2-0.18.tar

[ Step:7 ]

build and install libssh2

-bash-3.2# cd libssh2-0.18
-bash-3.2# ./configure
-bash-3.2# make all install

Next we need to link libssh2 and PHP with the SSH2 PECL module.

[ Step:8 ]

-bash-3.2# cd /usr/src
-bash-3.2# wget http://pecl.php.net/get/ssh2-0.10.tgz
-bash-3.2# gunzip ssh2-0.10.tgz
-bash-3.2# tar xvf ssh2-0.10.tar

-bash-3.2# cd ssh2-0.10

[ Step:9 ]

edit ssh2.c and change following if condition

#if LIBSSH2_APINO < 200412301450

to

#if LIBSSH2_VERSION_NUM < 0x001000

Save the file and execute phpize to prepare the build environment for the ssh2 PHP extension.

[ Step:10 ]

-bash-3.2# pwd
/usr/src/ssh2-0.10
-bash-3.2# /usr/php5/bin/phpize
Configuring for:
PHP Api Version:         20041225
Zend Module Api No:      20060613
Zend Extension Api No:   220060519


[ Step:11 ]

-bash-3.2# pwd
/usr/src/ssh2-0.10

-bash-3.2# ./configure --with-ssh2 --with-php-config=/usr/php5/bin/php-config
-bash-3.2# make
-bash-3.2# make install
Installing shared extensions:     /usr/php5/5.2.4/modules/

[ Step:12 ]

ssh2.so module is now installed. We can modify the php.ini file and make sure the module gets loaded by php.

-bash-3.2# vi /etc/php5/5.2.4/php.ini
add
extension=ssh2.so
under Dynamic Extensions section

restart the apache to and load the SSH2 php extension.

-bash-3.2# svcadm restart svc:/network/http:apache22
About

Divyen Patel

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today