Friday, July 29, 2011

Using Drupal menu system callback mapping to retrieve JSON or XML data

In my previous post I talked about Drupal menu system callback mapping. Today I'm going to show you how Drupal menu system callback mapping can be used to retrive JSON or XML data.

The way to accomplish the task is to register a path for a menu item with an optional argument. If you pass that optional argument along with the request URL callback function will return JSON data else it will return XML data. In that way callback function will serve both data formats.

Following is a coding example of above mentioned scenario.

<?php
//hook_perm implementation
function example_perm() {
    return array(
        'access city'
    );
}

//hook_menu implementation
function example_menu() {
    $items = array();
 
    //menu item 
    $items['full_city_list'] = array(
        'title' => t('City List JSON'
        ), 'page callback' => 'full_city_list', 'page arguments' => array(
            1
        ), 'access arguments' => array(
            'access city'
        ), 'type' => MENU_CALLBACK);   

    return $items;
}

function full_city_list() {
 $jsonParam=arg(1);//optional argument
 $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");
 
 if(strcmp($jsonParam, "json") == 0){
    $response = array();
    
    while ($city_data = db_fetch_object($result)) {
        $response[$city_data->name]['city_name'] = $city_data->name;
        $response[$city_data->name]['tid'] = $city_data->tid;
    }

    if (!empty($response)) {
        //encodes city data as json  
        $jsonstrCityList = json_encode($response);
        echo $jsonstrCityList;
    } else {
        return false;
    }
 }elseif(strcmp($jsonParam, "") == 0){
 //sending city data as xml
 $dom = new DOMDocument("1.0");
    $root_elm = $dom->createElement("markers");
    $root = $dom->appendChild($root_elm);    

    while ($city_data = db_fetch_object($result)) {

        $marker_elm = $dom->createElement("marker");
        $marker_node = $root->appendChild($marker_elm);

        $marker_node->setAttribute("name", $city_data->name);
        $marker_node->setAttribute("tid", $city_data->tid);
    }
    header("Content-type: text/xml");
    echo $dom->saveXML();
 }
}
?>



output for http://example.com/full_city_list/json
{"Agalawatta":{"city_name":"Agalawatta","tid":"156"},"Ahungalla":{"city_name":"Ahungalla","tid":"214"},"Akurana":{"city_name":"Akurana","tid":"164"},"Akuressa":{"city_name":"Akuressa","tid":"162"},"Aluthgama":{"city_name":"Aluthgama","tid":"120"},"Ambalangoda":{"city_name":"Ambalangoda","tid":"125"},"Ampara":{"city_name":"Ampara","tid":"211"},"Anuradhapura":{"city_name":"Anuradhapura","tid":"46"},"Arugambay":{"city_name":"Arugambay","tid":"114"},"Avissawella":{"city_name":"Avissawella","tid":"212"},"Badulla":{"city_name":"Badulla","tid":"108"},"Balangoda":{"city_name":"Balangoda","tid":"149"},"Balapitiya":{"city_name":"Balapitiya","tid":"486"},"Bandarawela":{"city_name":"Bandarawela","tid":"197"}}


output for http://example.com/full_city_list
<markers>
<marker name="Agalawatta" tid="156"/>
<marker name="Ahungalla" tid="214"/>
<marker name="Akurana" tid="164"/>
<marker name="Akuressa" tid="162"/>
<marker name="Aluthgama" tid="120"/>
<marker name="Ambalangoda" tid="125"/>
<marker name="Ampara" tid="211"/>
<marker name="Anuradhapura" tid="46"/>
<marker name="Arugambay" tid="114"/>
<marker name="Avissawella" tid="212"/>
<marker name="Badulla" tid="108"/>
<marker name="Balangoda" tid="149"/>
<marker name="Balapitiya" tid="486"/>
<marker name="Bandarawela" tid="197"/>
</markers>

Wednesday, July 20, 2011

Drupal menu system callback mapping

How does drupal menu system callback mapping happen?

When a user makes a request to drupal through a browser, using the request URL drupal menu system decides which callback function to invoke.

what is a callback function?

Callback function in this case is a php function which gets called when a user trying to access a path that has already been registered in a menu item.

In the given example-1 if a browser makes a request using the URL "http://example.com/hello", menu system will look for a menu item which contains that path and invokes the relevant callback function in this case, "hello()".

example-1

<?php

//hook_perm implementation  
function example_perm() {
    return array(
        'access hello'
    );
}

//hook_menu implementation  
function example_menu() {
    $items = array();
    //menu item   
    $items['hello'] = array(
    'title' =--> t('hello'
    ), 'page callback' => 'hello', 'page arguments' => array(
    0
    ), 'access arguments' => array(
    'access hello'
    ), 'type' => MENU_CALLBACK);

    return $items;
}

//callback function  
function hello() {
    echo "hello!";
}
?>  

Output for example-1
hello!

example-2

This example shows how to get city data in json or xml using a request URL.

<?php

//hook_perm implementation
function example_perm() {
    return array(
        'access hello'
    );
}

//hook_menu implementation
function example_menu() {
    $items = array();
    //menu item 
    $items['hello'] = array(
        'title' => t('hello'
        ), 'page callback' => 'hello', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    $items['full_city_list_json'] = array(
        'title' => t('City List JSON'
        ), 'page callback' => 'full_city_list_json', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    $items['full_city_list_xml'] = array(
        'title' => t('City List XML'
        ), 'page callback' => 'full_city_list_xml', 'page arguments' => array(
            0
        ), 'access arguments' => array(
            'access hello'
        ), 'type' => MENU_CALLBACK);

    return $items;
}

function hello() {
    echo "hello!";
}

function full_city_list_json() {
    $response = array();
    $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");
    while ($city_data = db_fetch_object($result)) {
        $response[$city_data->name]['city_name'] = $city_data->name;
        $response[$city_data->name]['tid'] = $city_data->tid;
    }

    if (!empty($response)) {
        //encodes city data as json  
        $jsonstrCityList = json_encode($response);
        echo $jsonstrCityList;
    } else {
        return false;
    }
}

function full_city_list_xml() {
//sending city data as xml
    $dom = new DOMDocument("1.0");
    $root_elm = $dom->createElement("markers");
    $root = $dom->appendChild($root_elm);

    $result = db_query("SELECT  tid,name FROM term_data  WHERE  vid=2 order by name ASC");

    while ($city_data = db_fetch_object($result)) {

        $marker_elm = $dom->createElement("marker");
        $marker_node = $root->appendChild($marker_elm);

        $marker_node->setAttribute("name", $city_data->name);
        $marker_node->setAttribute("tid", $city_data->tid);
    }
    header("Content-type: text/xml");
    echo $dom->saveXML();
}

?>

Outputs for example-2

for http://example.com/full_city_list_json

{"Agalawatta":{"city_name":"Agalawatta","tid":"156"},"Ahungalla":{"city_name":"Ahungalla","tid":"214"},"Akurana":{"city_name":"Akurana","tid":"164"},"Akuressa":{"city_name":"Akuressa","tid":"162"},"Aluthgama":{"city_name":"Aluthgama","tid":"120"},"Ambalangoda":{"city_name":"Ambalangoda","tid":"125"},"Ampara":{"city_name":"Ampara","tid":"211"},"Anuradhapura":{"city_name":"Anuradhapura","tid":"46"},"Arugambay":{"city_name":"Arugambay","tid":"114"},"Avissawella":{"city_name":"Avissawella","tid":"212"},"Badulla":{"city_name":"Badulla","tid":"108"},"Balangoda":{"city_name":"Balangoda","tid":"149"},"Balapitiya":{"city_name":"Balapitiya","tid":"486"},"Bandarawela":{"city_name":"Bandarawela","tid":"197"}}

for http://example.com/full_city_list_xml

<markers>
<marker name="Agalawatta" tid="156"/>
<marker name="Ahungalla" tid="214"/>
<marker name="Akurana" tid="164"/>
<marker name="Akuressa" tid="162"/>
<marker name="Aluthgama" tid="120"/>
<marker name="Ambalangoda" tid="125"/>
<marker name="Ampara" tid="211"/>
<marker name="Anuradhapura" tid="46"/>
<marker name="Arugambay" tid="114"/>
<marker name="Avissawella" tid="212"/>
<marker name="Badulla" tid="108"/>
<marker name="Balangoda" tid="149"/>
<marker name="Balapitiya" tid="486"/>
<marker name="Bandarawela" tid="197"/>
</markers>


As in example-2 after you grabbed the city data in json or in xml you can parse them and use in any of your applications.

Wednesday, July 6, 2011

Parsing JSON (comes as a response to a web request) using java

JSON (JavaScript Object Notation) as in definition is a light weight data exchange format, a fat free alternative to XML. In today's post I will show you how to parse JSON (comes as a response to a web request) using java.

First download json-lib and add it to your classpath. You'll also have to add following libraries to your classpath

  1. commons-lang.jar
  2. commons-beanutils.jar
  3. commons-collections.jar
  4. commons-logging.jar
  5. ezmorph.jar

What you need next is a request url and it's response should be JSON data. You will see mine in the example code I've provided, if you know how to use firebug the task will be much more simpler. In your browser run that request you'll get the JSON data which I parse, it's lengthy that's why I didn't add it in here. If you get untidy JSON data, format it using jasonlint.

Now let's move on to the example code, it's not hard to understand, simply go through it. Refer comments for clarifications.

java code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

public class JsonParse { 

 public static void main(String[] args) {
  String jsonString = "";

  String city = "London";
  String country = "United+Kingdom";

  //This is the request url  
  String requestUrl = "http://www.bing.com/travel/hotel/hotelReferenceData.do?q="
    + city
    + "%2C+"
    + country
    + "+leave+07%2F08%2F2011+return+07%2F10%2F2011+adults%3A2+rooms%3A1&distanceFrom=22&HotelPriceRange=1%2C2%2C3%2C4&pageOffset=0&pageCount=240&cim=2011-07-08&com=2011-07-10&a=2&c=0&r=1&sortBy=PopularityDesc";
  try {
   URL url = new URL(requestUrl.toString());
   BufferedReader in = new BufferedReader(new InputStreamReader(
     url.openStream()));
   String inputLine;

   while ((inputLine = in.readLine()) != null) {
    //JSON data get stored as a string
    jsonString = inputLine;

   }
   in.close();
   //the way to parse JSON array
   JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonString);
   //getting another JSON string to parse
   String parse1 = json.getString(0);
   
   //the way to parse JSON object
   JSONObject json2 = (JSONObject) JSONSerializer.toJSON(parse1);
   //getting a json array inside JSON object
   JSONArray array1 = json2.getJSONArray("hotels");

   for (int i = 0; i < array1.size(); i++) {
    //getting a JSON object inside JSON array
    JSONObject jhotelrec = array1.getJSONObject(i);    
    System.out.println("Hotel Name= "+jhotelrec.getString("name")+"\n"+"Geo Codes= "+jhotelrec.getJSONArray("geoPoint").getString(0)+","+jhotelrec.getJSONArray("geoPoint").getString(1));
    }

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

}


Monday, July 4, 2011

xml parsing with java

In certain situations we java programmers may need to access information in XML documents using a java xml parser. This post will guide you to parse a xml document with java, using DOM parser and Xpath.

xmlfile.xml

Given XML document is quite lengthy, but do not worry because parsing a lengthy XML document is as easy as parsing a short XML document :) .

<a>
<e>
<hotels class="array">
   <e class="object">
    <addressLine1 type="string">4 Rue du Mont-Thabor</addressLine1>
    <amenities class="array">
     <e type="string">24</e>
     <e type="string">31</e>
     <e type="string">42</e>
     <e type="string">52</e>
     <e type="string">9</e>
    </amenities>
    <brandCode type="string">69</brandCode>
    <cachedPrice type="number">935</cachedPrice>
    <city type="string">Paris</city>
    <country type="string">US</country>
    <geoPoint class="array">
     <e type="number">48.86536</e>
     <e type="number">2.329584</e>
    </geoPoint>
    <hotelRateIndicator type="string">2</hotelRateIndicator>
    <id type="number">56263</id>
    <name type="string">Renaissance Paris Vendome Hotel</name>
    <neighborhood type="string" />
    <popularity type="number">837</popularity>
    <starRating type="string">5</starRating>
    <state type="string">IdF</state>
    <telephoneNumbers class="array">
     <e type="string" />
    </telephoneNumbers>
    <thumbnailUrl type="string">http://www.orbitz.com//public/hotelthumbnails/53/97/85397/85397_TBNL_1246535840051.jpg
    </thumbnailUrl>
    <total type="number">250</total>
    <ypid type="string">YN10001x300073304</ypid>
   </e>
   <e class="object">
    <addressLine1 type="string">39 Avenue de Wagram</addressLine1>
    <amenities class="array">
     <e type="string">24</e>
     <e type="string">31</e>
     <e type="string">42</e>
     <e type="string">9</e>
    </amenities>
    <brandCode type="string">69</brandCode>
    <cachedPrice type="number">633</cachedPrice>
    <city type="string">Paris</city>
    <country type="string">US</country>
    <geoPoint class="array">
     <e type="number">48.877106</e>
     <e type="number">2.297451</e>
    </geoPoint>
    <hotelRateIndicator type="string">3</hotelRateIndicator>
    <id type="number">112341</id>
    <name type="string">Renaissance Paris Arc de Triomphe Hotel</name>
    <neighborhood type="string" />
    <popularity type="number">796</popularity>
    <starRating type="string">5</starRating>
    <state type="string">IdF</state>
    <telephoneNumbers class="array">
     <e type="string" />
    </telephoneNumbers>
    <thumbnailUrl type="string">http://www.orbitz.com//public/hotelthumbnails/21/72/302172/302172_TBNL_1246535872514.jpg
    </thumbnailUrl>
    <total type="number">250</total>
    <ypid type="string">YN10001x300073331</ypid>
   </e>
   <e class="object">
    <addressLine1 type="string">35 Rue de Berri</addressLine1>
    <amenities class="array">
     <e type="string">24</e>
     <e type="string">31</e>
     <e type="string">42</e>
     <e type="string">9</e>
    </amenities>
    <brandCode type="string">82</brandCode>
    <cachedPrice type="number">706</cachedPrice>
    <city type="string">Paris</city>
    <country type="string">US</country>
    <geoPoint class="array">
     <e type="number">48.873684</e>
     <e type="number">2.306411</e>
    </geoPoint>
    <hotelRateIndicator type="string">3</hotelRateIndicator>
    <id type="number">108606</id>
    <name type="string">Crowne Plaza Hotel PARIS-CHAMPS ELYSÉES</name>
    <neighborhood type="string" />
    <popularity type="number">796</popularity>
    <starRating type="string">5</starRating>
    <state type="string">IdF</state>
    <telephoneNumbers class="array">
     <e type="string" />
    </telephoneNumbers>
    <thumbnailUrl type="string">http://www.orbitz.com//public/pegsimages/CP/thumb_PARAT.jpg
    </thumbnailUrl>
    <total type="number">250</total>
    <ypid type="string">YN10001x300161106</ypid>
   </e>
   </hotels>
 </e>
</a>   


XMLsample.java

In this code I have used DOM parser and xpath java library to query xml document. Here I am trying to extract hotel information[Hotel name, geo codes, star rating] from xmlfile.xml document

package com.eviac.blog;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XMLsample {

 public static void main(String[] args) {

  try {
   // loading the xml document into DOM Document object
   DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
   domFactory.setNamespaceAware(true);
   DocumentBuilder builder = domFactory.newDocumentBuilder();
   Document doc = builder.parse("xmlfile.xml");

   // XPath object using XPathFactory
   XPath xpath = XPathFactory.newInstance().newXPath();
   
   // XPath Query, compiling the path using the compile() method
   XPathExpression expr = xpath.compile("//hotels/e/name | //hotels/e/starRating | //hotels/e/geoPoint/e/text()");
   Object result = expr.evaluate(doc, XPathConstants.NODESET);
   NodeList nodes = (NodeList) result;
   for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getTextContent());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


Output
48.86536
2.329584
Renaissance Paris Vendome Hotel
5
48.877106
2.297451
Renaissance Paris Arc de Triomphe Hotel
5
48.873684
2.306411
Crowne Plaza Hotel PARIS-CHAMPS ELYSÉES
5

Monday, June 20, 2011

Working with drupal API

It's been a while since I started working with drupal, without a doubt the best CMS ever. I find working with drupal extremely interesting with all those API functions in hand.

Drupal has convenient ways to handle database work for us, therefore it is advisable to use drupal API as much as possible to get the work done. Moreover updating to a new drupal version from an older version is quite less conflicting if we have followed the drupal API.

recently I got the chance to work with some interesting drupal API functions and thought they might be useful for you as well at some point.

  1. node_load()
  2. Given nid(node id) as the parameter this function loads that node from drupal database. I'm not exaggerating if I say this functions helps us to get full control over any node.dreamy isn't it?

    Example usage 1
    <?php 
    $node=node_load(820);//loads the node with the nid equals to 820 and store it in $node variable
    print_r($node);//prints all the information associated with the node, yikes it's lengthy :P 
    ?>
    
    After loading a particular node it is possible to get almost every information related to it.

    Example usage 2
    <?php 
    echo $node->body;//prints the content of the node
    echo $node->title;//prints the title of the node
    ?>
    
  3. truncate_utf8()
  4. truncate_utf8() function truncates a string to a specified number of characters.

    Example usage
    <?php 
    $node=node_load(820);
    $content=truncate_utf8(strip_tags($node->body),400,true,true);//limits the body content of a node to 400 characters
    ?>
    
  5. l()
  6. Creating a link using html is super easy even for a web development newbie, it is possible to use the same method in drupal development, but if you follow drupal API that's not the best way to create a link. l() function comes to the stage at this moment as the drupal's way to create links.

    Example usage
    <?php 
    print l("click here","node/820");
    ?>
    
    above is exactly identical to following
    <a href="node/820">click here</a>
    
  7. url()
  8. url() generates and internal(eg: node/1) or external url.

    Example usage
    <?php 
    $path="node/820";
    $link=url($path,array('absolute'=>TRUE));
    ?>
    
  9. drupal_get_path_alias()
  10. Given an internal drupal path this function returns the alias set by admin.

    Example usage
    <?php 
    $path="node/820";
    $alias=drupal_get_path_alias($path);
    ?>
    

Tuesday, May 24, 2011

Getting started with drupal module development

Drupal is a very handy CMS, there are tons of modules written to extend the functionalities of drupal. This post will guide you to write a simple drupal module.

There must be at least two files to create a drupal module,

  • module_name.info
  • module_name.module

In this example I will use module_name as "cities". Then my two files would be cities.info and cities.module

Create a folder inside sites/all/modules which has the same name as your module, in this case it's "cities". Inside cities create two files cities.info and cities.module

It is possible to save your module in module folder but it is not recommended as that folder is kinda reserved for drupal core module. Instead of messing with core guys it is advisable to maintain a separate place for custom modules.

cities.info

cities.info file contains all the necessary information for drupal to know about your module. name, description, core are the musts in this file. There are also set of optional info which you can include but here in this example I only use required information only.

; $Id$
name = cities
description = This is a module that display list of cities 
core = 6.x


cities.module

what exactly is a hook?

Here is a good question if you are a newbie to drupal module development. Concept of hook is very important when it comes to drupal module development. Module system in drupal is based on hook, simply it's a php fuction which defines set of parameters and a result type. Hooks allow modules to interact with the drupal core.

In this example module I've used three hooks, hook_help, hook_perm and hook_block.

hook_help : provides help and additional information.
hook_perm : defines permissions for the module.
hook_block: creates a block or set of blocks.

We have to replace hook with our module name when using them.

This example block module cities will display a list of cities pulled out of a database.

<?php
// $Id: cities.module$

/**
 * @file
 * This is a module that display list of cities
 */

/**
 * Implementation of hook_help().
 */
function cities_help($path, $arg) {
  switch ($path) {
    case 'cities':
      return '<p>'. t('<b>help hook. This is a module that display list of cities.</b>') .'</p>';
  }
}

/**
 * Implementation of hook_perm().
 */
function cities_perm() {
  return array('access cites');
}

/**
 * grabbing data from the database
 */

global $arr; 
$arr=array();
global $datas;
$datas="";

$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('cities', $link);

$sql = "SELECT name FROM city";
$sel = mysql_query($sql);
   
   if (mysql_num_rows($sel) > 0) { 
    $i=0;
    while($row = mysql_fetch_array($sel)) {
          
     $arr[$i]=$row['name'];
     $i=$i+1;
    }
    }
    
 foreach( $arr as $key => $value){
   $datas=$datas." ".$value."<br/>";
  }
  mysql_close();

/**
 * Implementation of hook_block().
 */
function cities_block($op = 'list', $delta = 0, $edit = array()) {
global $datas;
  if ($op == "list") {
    $block = array();
    $block[0]["info"] = t('cities');
    return $block;
  }
  elseif ($op == 'view') {
    $block_content = '<p>This is a block that display list of cities.</p>';
    $block['subject'] = 'City List';
    $block['content'] = $datas;
    return $block;
  }
}


Omitting the closing php tag is a drupal coding standard which prevents runtime issues.


Don't forget to enable your module (administrator-->modules) and pick a suitable place (administrator-->block) for it. Available permissions for this module can be viewed and customized from administrator-->permissions

That's it, now with this basic knowledge in hand it's not far away when you write more complex modules.

Tuesday, April 12, 2011

Star rating with MooStarRating

I'm not lying if I say javascript gives life to lifeless webpages. Javascript libraris make it easier for the developers to develop JavaScript-based applications especially with AJAX. Mootools is such a javascript framework. moostarrating is a mootools plugin which creates a javascript/ajax based attractive star rating system.

Following example shows you how to use moostarrating system and how to save the rating in a database using an Ajax call.

First download mootools core using this link.

Download the moostarrating plugin using this link. This page describes how to use the plugin but I thought it might be useful for all of you if I put here everything from the scratch.

I have deployed this example in a local environment, I recommend you to use xampp.

After installing xampp in windows, inside Apache Documents directory (C:\xampp\htdocs), create a new folder with a name you want, here I will use the name as "starRate". Extract the moostarrating plugin archive inside "starRate", also mootools core javascript should be placed inside "starRate".

Create a html file called star.html and save it inside "starRate". You can customize the default options and even functions in moostarrating.js the way you want.

star.html

<html>

<script src="mootools-core-1.3.1-full-compat.js"></script> 
 <script src="lorenzos-MooStarRating-422072a/Source/moostarrating.js"></script> 
 <script>   
  
  // When the DOM is ready....
  window.addEvent("domready",function() {
  
  MooStarRatingImages.defaultImageFolder = 'http://localhost/req/lorenzos-MooStarRating-422072a/Graphics/'; //Default images folder definition. You will use your own
   
   // Create our instance
   // Advanced options
   var advancedRating = new MooStarRating({
    form: 'ratingsForm', //Form name 
    radios: 'rating', //Radios name
    half: false, //if you need half star rating just make this true
    imageEmpty: 'star_boxed_empty.png', //Default images are in definition. You will use your own
    imageFull:  'star_boxed_full.png',
    imageHover: 'star_boxed_hover.png', 
    width: 17, 
    tip: 'Rate <i>[VALUE] / 7.0</i>', //Mouse rollover tip
    tipTarget: $('htmlTip'), //Tip element
    tipTargetType: 'html', //Tip type is HTML 
    
    // Send ajax request to server to save rating using "rating.php"
    onClick: function(value) {
          
     var requestHTMLData = new Request({
     url: 'rating.php',
     data: {rating: value}
     });
     requestHTMLData.send();
     }
     });  
   
   
  });
  
 </script> 
 <!-- radios have a default value, 2 -->
 <form name="ratingsForm">
    <label>Select The Number of Stars</label>
    <input type="radio" name="rating" value="1.0" checked="checked"> 
    
    <input type="radio" name="rating" value="2.0">
   
    <input type="radio" name="rating" value="3.0">
   
    <input type="radio" name="rating" value="4.0">
    
    <input type="radio" name="rating" value="5.0">
   
    <input type="radio" name="rating" value="6.0">
    
    <input type="radio" name="rating" value="7.0">
         
 <span id="htmlTip"></span>
</form>

</html>


In this example I use a php file to save the rating in a database. Create a database "rate_db", with a table "rate" with one column, you can use xampp phpmyadmin panel to create databases.

Create a php file called rate.php and save it inside "starRate" folder.

rate.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con){
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("rate_db", $con);

$dataSent = $_POST['rating'];

mysql_query("INSERT INTO rate VALUES('$dataSent')");

mysql_close($con);
?>



Start xampp control panel. Open up your favorite browser and place the following in address bar.

http://localhost/starRate/star.html



Now you'll be able to experience the usage of a fully functional star rating system.

Sunday, March 20, 2011

Getting started with GWT

GWT short for Google Web Development Kit lets programmers to develop Ajax web applications with java. Java codes are converted in to JavaScript and html codes by the GWT compiler. GWT applications are called modules and modules are described using a xml file, assuming the module name as "mymodule" name of the xml file would be "mymodule.gwt.xml". There is atleast one entry point for a module and it is same as the main method in a java program. GWT program code executes with in a HTML file and CSS file is used for alternating the look and feel.

Now that we are familiarized bit with terms and stuff we can move on to writing our own GWT application.

Step 1: Installing GWT plugin for eclipse

If you have already installed eclipse all you have to do is go to "Help" menu, under that "Install New Software" and give the URL as http://dl.google.com/eclipse/plugin/3.6 and click next and complete installation.


step 2: Creating a new project

Select File > New > Web Application Project. Enter the name "com.eviac.blog.helloworld" for the project name and package. By default it will select both "Use Google Web Toolkit" and "Use Google App Engine" as we only using Google Web Toolkit here you will have to deselect Google App Engine.


Now eclipse will create you a project with a package structure as shown below.


step 3: Creating the entry point

Inside the package com.eviac.blog.helloworld.client package create a java class named "HelloWorldGwt"

HelloWorldGwt.java
package com.eviac.blog.helloworld.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorldGwt implements EntryPoint {

 @Override
 public void onModuleLoad() {
  final Label label = new Label("Hello World GWT !!!");
  final Button button = new Button("Click Here");
  button.addClickHandler(new ClickHandler() {
   @Override
   public void onClick(ClickEvent event) {
    label.setVisible(false);
    button.setText("welcome back again!");
    Window.alert("Welcome to GWT");
   }
  });

  RootPanel.get().add(label);
  RootPanel.get().add(button);
 }
}



Inside the package com.eviac.blog.helloworld create Com_eviac_blog_helloworld.gwt.xml file.

Com_eviac_blog_helloworld.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='com_eviac_blog_helloworld'>
  <!-- Inherits Web Toolkit utilities.                        -->
  <inherits name='com.google.gwt.user.User'/>

  <inherits name='com.google.gwt.user.theme.standard.Standard'/>

  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.eviac.blog.helloworld.client.HelloWorldGwt'/>
</module>


Step 3: Creating html page

Inside the folder war create Com_eviac_blog_helloworld.html file

Com_eviac_blog_helloworld.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link type="text/css" rel="stylesheet" href="Com_eviac_blog_helloworld.css">
    <title>Hello World GWT</title>
    <script type="text/javascript" language="javascript" src="com_eviac_blog_helloworld/com_eviac_blog_helloworld.nocache.js"></script>
  </head>

  <body>

    <!-- optional tag: add this if needs history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    <h1><center>Hello World GWT</center></h1>
   
  </body>
</html>


Step 4: creating web.xml file

Inside the folder war/WEB-INF create a xml file called web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

 <!-- Default page to serve -->
 <welcome-file-list>
  <welcome-file>Com_eviac_blog_helloworld.html</welcome-file>
 </welcome-file-list>
</web-app>



Step 5: Creating css file

Inside war falder create a css file named Com_eviac_blog_helloworld.css

Com_eviac_blog_helloworld.css

h1 {
  font-size: 2em;
  font-weight: bold;
  color: #6495ED;
}

.gwt-Label {
 color: #0000FF;
 font: normal 12px tahoma, arial, helvetica, sans-serif;
 height:3.5em;
 width: 10.7em;  
}

.gwt-Button {
 color: #0000FF;
 height:3.5em;
 width: 10.7em;
 font-size: 12px;
 font-family: arial, sans-serif; 
}



Alright now we are done with coding steps but wait for it, one more step to go

Step 6: Running GWT Application

To run right click on the project select Run As->Web Application then it will bring up a new view "Development Mode" copy the url generated.


Install GWT plugin for your web browser using this link.


Now paste the url in the browser and you'll see something like following and that's it.


Now that you know how to build a basic GWT application you can improve it by adding more functionalities and changing the look and feel using css file.

Thursday, February 24, 2011

Internet Control Message Protocol (ICMP)

Why ICMP is important

IP protocol lacks error reporting mechanism and hosting/managing queries. To compensate ICMP protocol comes to the role as a companion to IP protocol giving following two services.

  • Provides error reporting mechanism
  • Hosts and manages queries

Did you have any doubt

ICMP is a network layer protocol as IP is, so one would suspect whether ICMP messages are passed directly to the data link layer. The answer is no. ICMP messages are first encapsulated inside ip datagram and then passed to the below data link layer. Following image clearly shows you how it happens.


Talking about ICMP messages

  • Error reporting messages
  • ICMP acts as error reporting protocol it does not correct errors, error corrections are done by the higher level protocols. ICMP always sends the error messages to original source. There are five types of error messages as listed below.
    • Destination unreachable
    • Source quench
    • Time exeeded
    • Parameter problem
    • Redirection
  • Query messages
  • ICMP can also diagnose network problems through query messages. There are two pairs of query messages used for this purpose today.
    • Echo request or reply
    • Timestamp request or reply

Debugging tools that uses ICMP

ping

ping program can be used to find out whether a host is alive and responding. The source host sends an ICMP echo request message, if the destination host is alive it responds with ICMP echo reply messages.



traceroute

traceroute progam in unix or tracert in windows can be used to trace the route of a packet from source to destination.


Sunday, February 13, 2011

Crypto Samples in java part four -Stream Cipher

SendStream.java

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SendStream {
 
 public static void main(String[] args) {
  
  String data = "This have I thought good to deliver thee rrrr";
  
  //---------------Encryption ---------------------------------

  SecretKey key = null;

  try {
   KeyGenerator keygen = KeyGenerator.getInstance("DES");
   key = keygen.generateKey();

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   
   FileOutputStream fos = new FileOutputStream("cipher.file"); 
   CipherOutputStream cos = new CipherOutputStream(fos, cipher);
   ObjectOutputStream oos = new ObjectOutputStream(cos);   
   
   
   oos.writeObject(data);
   oos.flush();
   oos.close();
   
   
   FileOutputStream fosKey = new FileOutputStream("key.file"); 
   ObjectOutputStream oosKey = new ObjectOutputStream(fosKey); 
   oosKey.writeObject(key);
   oosKey.writeObject(cipher.getIV());

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

 }

}



ReceiveStream.java

package ucsc.cipher;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class RecieveStream {
 
 public static void main(String[] args) {
  SecretKey key = null;

  try {
   FileInputStream fisKey = new FileInputStream("key.file"); 
   ObjectInputStream oosKey = new ObjectInputStream(fisKey); 
   
   key =  (SecretKey)oosKey.readObject();
   
   byte[] iv = (byte[])oosKey.readObject();


   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
   
   FileInputStream fis = new FileInputStream("cipher.file"); 
   CipherInputStream cis = new CipherInputStream(fis, cipher);
   ObjectInputStream ois = new ObjectInputStream(cis);   
   
   
            System.out.println((String)ois.readObject());   
   
  } catch (Exception e) {
   e.printStackTrace();
  } 

  
 }

}


Friday, February 11, 2011

Crypto Samples in java part three - Symmetric key encryption


A secret key is generated and only known by the sender and the receiver. Sender encrypts the plain text in to cypher text using the shared key and sends it to the receiver. After Receiver receives the encrypted message he/she decrypts the message using the shared key and grabs the original plain text (have a look at the image for a better understanding).

import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class SimpleCipher {

 public static void main(String[] args) {

  String data = "This have I thought good to deliver thee";

  // ---------------Encryption ---------------------------------

  byte[] encrypted = null;
  byte[] iv = null;
  SecretKey key = null;

  try {
   KeyGenerator keygen = KeyGenerator.getInstance("DES");/*
                 * get the key
                 * generator
                 * instance
                 */
   key = keygen.generateKey();// generate the secret key

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   /*
    * get cipher engine instance.DES algorithm is used and it requires
    * the input data to be 8-byte sized blocks. To encrypt a plain text
    * message that is not multiples of 8-byte blocks, the text message
    * must be padded with additional bytes to make the text message to
    * be multiples of 8-byte blocks.PKCS5Padding has used for that
    * purpose. note that CBC is a block cipher mode therefore we need
    * an initialization vector to chain blocks.
    */

   cipher.init(Cipher.ENCRYPT_MODE, key);/*
             * initializing cipher engine
             * for encryption
             */

   encrypted = cipher.doFinal(data.getBytes());/* do the encryption */

   iv = cipher.getIV();/*
         * save the initialization vector, remember that
         * we need this only when we are using cipher
         * block chaining mode for encryption
         */

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

  // ---------------Decryption ---------------------------------

  try {

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");/*
                   * get
                   * cipher
                   * engine
                   * instance
                   */

   AlgorithmParameterSpec param = new IvParameterSpec(iv);/*
                  * set the
                  * vector
                  * value
                  */

   cipher.init(Cipher.DECRYPT_MODE, key, param);/*
               * initializing cipher
               * engine for decryption
               */

   byte[] decrypted = cipher.doFinal(encrypted);/*
               * obtain original plain
               * text
               */

   System.out.println(new String(decrypted));

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

 }

}


Monday, January 31, 2011

Crypto Samples in java part two - Message Digest Streams

SendStream.java writes data along with message digest to a file "test".

SendStream.java

import java.io.*;
import java.security.*;

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

   // We need to write data + message digest to this file.
   // Basically this is the file we need to send to the receiver
   FileOutputStream fos = new FileOutputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestOutputStream dos = new DigestOutputStream(fos, md);

   ObjectOutputStream oos = new ObjectOutputStream(dos);

   String data = "This have I thought good to deliver thee, "
     + "that thou mightst not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   // Write the specified object to the ObjectOutputStream
   // Now the message being written to the FileOutputStream
   // Also - this will update the message digest of the written data as well..
   oos.writeObject(data);

   // urns the digest function on or off. The default is on. When it is on, a call to one
   // of the write methods results in an update on the message digest. But when it is off,
   // the message digest is not updated.
   dos.on(false);

   // Now let's also write the message digest to the file,
   oos.writeObject(md.digest());

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}



RecieveStream.java takes file "test" as an input reads the data and calculate digest of that data and compare it with the original message digest read from the file "test".

RecieveStream.java

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

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

   // Here we get a file from the sender - and we need to verify it's message digest
   // The file contains both the message and the digest.
   FileInputStream fis = new FileInputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestInputStream dis = new DigestInputStream(fis, md);

   ObjectInputStream oos = new ObjectInputStream(dis);

   // Read the message from the file
   String data = (String) oos.readObject();
   
   dis.on(false);

   // Original message digest from the input file.
   byte[] originalDigest = (byte[]) oos.readObject();

   if (MessageDigest.isEqual(originalDigest, dis.getMessageDigest().digest())) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}


Saturday, January 29, 2011

Crypto Samples in java part one - Message Digest

Here is a simple java program illustrating how to calculate a message digest and how to verify the message digest.

import java.security.MessageDigest;

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

   // ----------- Calculating digest ---------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   String data = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md.update(data.getBytes());
   byte[] digest = md.digest();

   // -----------Verifying Digest -----------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md2 = MessageDigest.getInstance("SHA");

   String data2 = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md2.update(data2.getBytes());
   byte[] digestOriginal = digest;
   byte[] digestCalc = md2.digest();

   if (MessageDigest.isEqual(digestOriginal, digestCalc)) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

Sunday, January 2, 2011

Synchronous Cilent Server application in java

Client code

Client.java

This program creates a socket connection with the server running on port 9050 on localhost and gets the input stream from the socket by chaining the BufferedReader with the InputStreamReader.


package clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

 public static void main(String args[]) {

  try {
   Socket s = new Socket("127.0.0.1", 9050);

   InputStreamReader streamreader = new InputStreamReader(
     s.getInputStream());
   BufferedReader br = new BufferedReader(streamreader);

   String number = br.readLine();

   System.out.println("Today's number is " + number);
   br.close();

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

 }

}



Server code

Server.java

This program makes a ServerSocket and waits for client Requests. When a client tries to connect the server creates a new socket in a random port(using accept() method), which knows about the ip address and the port number of the client and makes the connection to the client. Also here server uses PrintWriter to sned messages to client.


package mainserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

 public static void main(String args[]) {

  try {
   ServerSocket serverSock = new ServerSocket(9050);

   while (true) {

    Socket sock = serverSock.accept();
    PrintWriter pw = new PrintWriter(sock.getOutputStream());
    String TodayNum = new Server().getNumber();
    pw.println(TodayNum);
    pw.close();
    System.out.println(TodayNum);

   }

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

 }

 public String getNumber() {

  Random rg = new Random();
  int num = rg.nextInt(100);
  String numb = Integer.toString(num);
  return numb;

 }

}



Output

Saturday, January 1, 2011

Writing a C# client to an Axis2 service

Before moving into today's post content I would like to wish all the readers a happy new year 2011!

I am writing this post assuming you already have read my previous post subjected "Getting started with Apache Axis2". In there the client code has written in java, assume a situation where you need to write a client with C#, it is even simpler than writing a client in java.All you have to do is create a new project using microsoft visual studio and add the wsdl of your service(for the given example it is http://localhost:8080/axis2/services/mywebservice?wsdl) as service references and give a desired name for it(in following sample client code it is webserviceref), write the client code and run it



Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using webservice.clients.webserviceref;//name space of the service reference

namespace webservice.clients
{
    class Myclient
    {
        static void Main(string[] args)
        {

            webserviceref.mywebservicePortTypeClient cli = new mywebservicePortTypeClient("mywebserviceHttpSoap12Endpoint");
            Console.WriteLine(cli.sayHello("Hello"));
            Console.ReadLine();

        }
    }
}


Note that you have to start axis2 server before running the program.