Thursday, January 16, 2014

Simple Web Service with JBoss AS

Introduction

What is a Web Service?

Web service is a application that provide client application to use server applications methods. Assume you have a simple java programme with several classes. You can use those classes only inside your programme( or you have to include them as lib files). If you develop your programme as web service and host it in a application server, then client programms can use those classes( actually the methods inside those classes) via a network. Special thin about web services is it is platform independent. That means you may develop your web service using java, but clients that use the web service need not to be java, it may be .Net or any other language. 

How it works

When we publish a web service to a application server, we can get a xml document called WSDL(there are several technologies, but for this article I make things simple). This is the key to the web service, it contains all the method signatures, what is the address that web service can access, what are the protocols used etc. When creating client side we use this document to specify way of communication with the server application. Then how the platform independence comes into action? When we sending messages we use a protocol, that means both sides knows what they are sending and receiving. When a client needs to request something from server it converts its message to that protocol, when server side get the request it converts it back to original version that the server application can understands. Same thing happens with the other way of communication. Most popular protocol is SOAP. You can read more from here

Things we need

  • JDK 1.5 (or higher).
  • JBoss App Server.
  • Apache Maven (Read this how to install maven)
  • IDE (I used Intellij Idea 12.0)
If you are using JBoss 5.0.0 or lesser version please make sure you install JBoss WS framework to your application server. Read this article to install those applications on to your pc.


For the rest of this article I assume you have installed and configured above things correctly.

Folder structure for web application (war)

Server can identify our application as web application, if we bundle the classes and other necessary files in the following manner. At the end of the this article I'm going to bundle all the necessary files into .war file using Maven build tool.



  • classes folder contains all the classes in our application.
  • lib folder contains all the libraries that need for the application
  • web.xml file contains instructions to the server that which classes need to be loaded when web service is in action.
  • for our discussion let's forget about other files/folders

Implementation

  •  Create a java project (make sure you don't select any project modules such as web services, web services clients etc. for the first time we are going to start from the scratch)
  • Then right click on the project name in Intellij and select add framework support, select maven and click ok.
  • Now you have a clean maven java project. 
Now you have a project with pom.xml file. Folder structure should look like this.
  • Right click on your java folder (in Intellij project tab) and select New > Package
  • Give your package a name. ( I gave com.webservice)
  • Now right click on main folder and select New>Directory. create a directory called webapp and inside that create a directory called WEB-INF (this is the folder that contains web.xml file so give names exactly as above)
Now we are ready to go.


Create a class in com.webservice package
This is the class that our web service methods are implemented.
Now we can implement methods for our web service. Let’s create helloworld method that returns a string.

Now we need to make this class a web service class and this method a web service method. We can do it by adding annotations.  Just before your class name add @WebClass and before your method name add @Webmethod. After adding those annotations it will not recognize by our program, put cursor on those words and press Alt+enter to import  javax.jws.WebMethod and javax.jws.WebService.

Here is the WebClass

 package com.webservice;  
 import javax.jws.WebMethod;  
 import javax.jws.WebService;  
 /**  
  * Created by IntelliJ IDEA.  
  * User: Chann  
  * Date: 1/15/14  
  * Time: 9:58 PM  
  * To change this template use File | Settings | File Templates.  
  */  
 @WebService  
 public class WebClass {  
     @WebMethod  
    public String helloWebService(String name){  
      return "Hello "+ name;  
    }  
 } 
Now create a file named web.xml inside WEB-INF folder and add followings to that file. This is the file that contains details about our web service to server. <servlet-class> tag defines the classes that are related to web service. Let’s postpone to discuss about url-patterns and other stuff.

 <web-app>  
   <servlet>  
     <servlet-name>HelloWebService</servlet-name>  
     <servlet-class>com.webservice.WebClass</servlet-class>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>HelloWebService</servlet-name>  
     <url-pattern>/*</url-pattern>  
   </servlet-mapping>  
 </web-app>  
Now it’s almost done coding our web service. Now we need to build these classes and package them to a war file to deploy in JBoss server
We use maven to build our project. We have a pom.xml file in our project. Let’s modify it to do our job.

We need to package our web service as a war file. That is done through the <packaging> tag.

 <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
   <modelversion>4.0.0</modelversion>  
   <groupid>groupId</groupid>  
   <artifactid>WebService</artifactid>  
   <version>1.0-SNAPSHOT</version>  
   <packaging>war</packaging>  
   <dependencies>  
     <dependency>  
       <groupid>com.sun.xml.bind</groupid>  
       <artifactid>jaxb-core</artifactid>  
       <version>2.2.8-b01</version>  
     </dependency>  
     <dependency>  
       <groupid>com.sun.xml.bind</groupid>  
       <artifactid>jaxb-impl</artifactid>  
       <version>2.2-promoted-b65</version>  
     </dependency>  
   </dependencies>  
   <build>  
     <plugins>  
       <plugin>  
         <artifactid>maven-war-plugin</artifactid>  
         <version>2.4</version>  
         <configuration>  
           <packagingexcludes>WEB-INF/lib/*.jar</packagingexcludes>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  
 </project> 
we need to add the war plugin to make a war using maven. That is the reason to add maven-war-plugin to our pom.xml file. We need to add <packagingExcludes> tag to bundle our WEB-INF folder without addional jar files(some times it gives errors if we keep those jar lib files inside WEB-INF folder). And additionally we need to add two dependencies to work properly. Now we can make our project. Either click package in maven life-cycle in Intellij idea(in left side) or open project folder via cmd prompt ( open cmd prompt and navigate to project folder) and then type maven clean install, press enter. You can find the war file in target folder inside project folder.

Now you can put this war file inside JBoss>Server>default>deploy folder. And run the Start.bat file inside JBoss > bin folder to start the server.

Now your web service is in action. 

Thursday, August 8, 2013

Tank Game with Artificial Intelligence

As a programming challenge module project, we develop this game using C# and XNA




 Game objectives are
  • —clients acting as “tanks” accumulating points while making sure of their own survival.
  • —The tanks are capable of shooting shells (bullets) and these bullets will move 3 times faster than a tank.
  • —The environment is made out of four kinds of blocks
    • —Brick wall 
    • —Stone wall
    • —Water
    • —Blank cell
Brick Wall – Brick walls will be considered as obstacles. Players can shoot and break walls. 4 shots will break the wall and it becomes a blank cell
Stone – obstacles. cannot be shot. Bullets cannot pass through.
Water – Pits. Cannot go through but can shoot through

Game Initiation
  • A timer gets initiated when the first player resister for a game.
  • When the 5th player joins the game or in the event of the timer expiring, the server will issue the game starting message to all the players that are already registered with the server.
  • —As discussed before, any join request by a client hereafter until the end of the game instance will be rejected.
  • —The game will be played in a 20x20 grid.

Joining the Game
—If the client’s request can be honoured, the server replies with a message in the following format.
S:P<num>: < player location x>,< player location y>:<Direction>#
—For an example the first player to register in a game instance may get a message like,
S:P1: 1,1:0#
—Direction
—0 North
—1 East,
—2 South
—3 West
—All other map details vary with each game instance and will be sent in the following format

I:P1: < x>,<y>;< x>,<y>;< x>,<y>…..< x>,<y>: < x>,<y>;< x>,<y>;< x>,<y>…..< x>,<y>: < x>,<y>;< x>,<y>;< x>,<y>…..< x>,<y># 


Moving And Shooting
—If the request direction is the same as the current direction, the server will try to move the client 1 cell in the said direction.
—Otherwise the tank will be rotated to face the requested direction

E.g.:
—If the tank is facing North and the client issues the command UP#, the server will try to move the tank up by 1 cell
—If the tank is facing North and the client issues the command DOWN#, the server change the tank direction to South. —
—When the client want to move/rotate their tank or shoot, it must issue the relevant command from the following list.
—UP#
—DOWN#
—RIGHT#
—LEFT#
—SHOOT#
—A client can issue one of these commands each second

—If the request of the client cannot be honoured due to some reason, it will be immediately communicated.
—OBSTACLE#
—CELL_OCCUPIED#
—DEAD#
—TOO_QUICK#
—INVALID_CELL#
—GAME_HAS_FINISHED#
—GAME_NOT_STARTED_YET#
—NOT_A_VALID_CONTESTANT#
—Otherwise the server will update its internal variables
Once per second the server will broadcast a global update to all the clients documenting its internal variables about the clients.

G:P1;< player location x>,< player location y>;<Direction>;< whether shot>;<health>;< coins>;< points>: …. P5;< player location x>,< player location y>;<Direction>;< whether shot>;<health>;< coins>;< points>: < x>,<y>,<damage-level>;< x>,<y>,<damage-level>;< x>,<y>,<damage-level>;< x>,<y>,<damage-level>…..< x>,<y>,<damage-level>#

Acquiring Coins 
—For two reasons coins will appear on the map.
  • —Random treasures 
  • —Spoils of war 
The players are supposed to collect them by moving to the cell where the coin pile is.
When a player collect a pile of coins, their coin count and the point count will get increased by that amount—



The server will send the following message to signal the appearing event of a pile of coins.

C:<x>,<y>:<LT>:<Val>#
—x - <int>
—y - <int>
—LT -<int> the time that the pile of coins will be on the map before it automatically disappears
—Val – value of the coins
—There are three ways to acquire points
   —Breaking bricks -Each time a shell (bullet) from a player damages a brick wall, a constant amount of points is added to the player’s point count.
   —Collecting coins -—As described in the previous topic
—   Spoils of war 



Life Pack
—Similar to the piles of coins, life packs will appear on empty cells.
—The method of taking a life pack is similar to the method of taking a treasure.
—When a client takes a life pack, 20% of the initial health will be added to their health.
—Note that it is possible for a client, at some point of the game, to have a health value which is greater than the initial health value.
—The server will send the following message to signal the appearing event of a Life Pack.

L:<x>,<y>:<LT>#
—x - <int>
—y - <int>
—LT -<int> the time that the life pack will be on the map before it automatically disappears


Killing

—A bullet hit will reduce the health of a tank by 10% of the initial health
—A player who has health of 0% (or less) will die and drop their coins at the point of death. But they will not lose the current points. However 25% of the points of the victim will be added to the killer.
—The dropped pile of coins is no different from a randomly created pile of coins. Thus the killer do not have a claim on it, it can be picked up by any remaining client.


Penalties and Death
—If a client hits an obstacle (a standing brick wall or a stone wall), a fixed number of points will be deducted from the client.
—The deduction takes place per each turn, thus if a client keeps hitting an obstacle, it will continuously lose points. 

—As described in a previous slide, clients can shoot over water. But if the client tries to move the tank in to a cell with water, the client will be killed.
—Since there is no killer here other than the environment, no body will be credited with points and the coins of the slain client will not drop to the ground.
—But they will get their coin count set to zero nevertheless.

End Game
—The game ends if one of the following happens;
—All the clients are dead
—The game lifetime counter expires
—All the coin piles (random or otherwise) finished appearing on the map and all the appeared coin piles either has been claimed by a client or disappeared.
—When the game ends, the player with most points will be declared the winner. And the message GAME_FINISHED# will be broadcasted to all the clients.

Saturday, August 3, 2013

How to install Joomla on WAMP server

This tutorial will teach you how to install a fresh copy of joomla into your wamp server. If you are a beginner to joomla, it is a content management system(CMS) that you can use to maintain a web site of your own. It is easier to test our site in local machine before it is hosted in the internet. So we use WAMP server(it works as a actual server, if you are linux user you can use LAMP)

If you are not familiar with WAMP or LAMP please refer these before continue.
Learn more about WAMP
How to install lamp on linux

What you need before start


  • WAMP server must be installed on your pc
  • check whether it is working or not by typing "localhost" on your browser, it will give you something like this.

if you get a browser window like above, you're ready to go. Otherwise please refer to your wamp installation tutorial again. you can use this one as well. Click here

Then follow these steps carefully.

Step 1

Download Joomla installation files from here
Joomla 3.0 is the newer version of Joomla( but here I'm using version 2.5.8)
You will get a zip file and extract it to wherever you want.

Step 2

Open your www folder, usualy this is located in C://wamp folder. 
www folder is the location we put all of our website files. so copy and paste your previously extracted joomla folder to the www folder. Let's name that folder as "My Site"

Step 3

Now we want to create a database for our web site. so open your browser and go to "localhost" by simply typing "localhost" on your browser address bar.
Then you will be directed to wamp server home page. Click on "phpmyadmin"
At there you can create a database for your web site. (I'm not going to describe it here)
Name your database as 'joomla' (you can use your own name)

Step 4

Locate your browser to "localhost".
At there you can see your joomla folder under My Projects, ( we named it as "My Site")
Click on the folder "My Site"
You will see a page like this.
You can select your preferred language for your installation. I leave it as English. Then click next.(upper right corner)
Then you will see the pre installation check window. 
Here you must see all the settings as 'green' except display errors and output buffering... you can switch off those two by simply using following steps. but it is not mandatory. 
Click on your wamp icon in the taskbar( lower right corner). select php> php settings
then deselect display errors and output buffering
now come back to your browser window and click "check again". now you must see all the things in green. if not please check your php settings and other relevant settings.
Click next
you will see the licence agreement. Read it and click next

Step 5

This is a critical part. now you can see the database configuration window. here we are introducing our previously created database to the joomla installation. 


select database type as "mysql"
host name is 'localhost'
then enter your mysql username and password, usually username is root and password is empty. But if you have changed them before you have to enter those changed values.
Enter the database name as 'joomla' ( you have to enter the database name as we created in the step 3)
leave other settings as it is.. Then click next

Step 6


now you are asked to create a FTP account. FTP account simply use to transfer files to your website. But here we don't need a ftp account just keep it as it is and click next.

Step 7


now you are almost done. Enter a site name. Then enter valid email address. Admin username and password. This user name and password is used to log into the back-end of your web site. all the configuration is done through this account. Just remember what you enter here.Click next

Step 8

In this window click "Remove installation folder" button. It will simply removes files which are used to install joomla on your server. Now you are done.
You can check your site by clicking "site" button on top right corner. You can visit your joomla administrator page by clicking "Administrator" button.