Struts 2 Hello World

Tuesday, June 30, 2009

I had seen many new deveopers struggling against struts2 hello world example. So I decided to write a small example.

Below are the required libraries to run this example which are easily availabel
struts2-core-2.0.11
xwork-2.0.4
commons-logging-1.0.4
commons-logging-api-1.1
freemarker-2.3.8
ognl-2.6.11
The structure of the applictaion which I am following is (Eclipse IDE)

Struts2Demo
|---src
| |----org
| | |----vinod
| | | |----action
| | | | |----HelloWorld.java
|---struts.xml
|---WebContent
| |---jsp
| |---HelloWorld.jsp
|---index.jsp
|---WEB-INF
| |---lib
| |---web.xml

It is true that different IDE's use different structure, but at last when war is build they follow same structure.
Lets start...

HelloWorld.java


package org.vinod.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorld extends ActionSupport{
String greetings = null;
public String execute() throws Exception {
setGreetings("Hello World");
return SUCCESS;
}

/**
* @return the greetings
*/
public String getGreetings() {
return greetings;
}

/**
* @param greetings the greetings to set
*/
public void setGreetings(String greetings) {
this.greetings = greetings;
}
}

HelloWorld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 Example</title>
</head>
<body>
<s:property value="greetings"/>
<body>
<html>

index.jsp

<@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 Example</title>
</head>
<body>
<s:action name="HelloWorldAction" executeResult="true"></s:action>
</body>
</html>

struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="hello" extends="struts-default">
<action name="HelloWorldAction"
class="org.vinod.action.HelloWorld">
<result>/jsp/HelloWorld.jsp</result>
</action>
</package>
</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


Enjoy the struts2(most popular java framework today)

Image Hosted by ImageShack.us

Image Hosted by ImageShack.us


BlueTooth Connectivity Through Java

Monday, June 29, 2009

Using the following code you can start bluetooth connection in your mobile. This will register the service(UUID) while starting the bluetooth
connection. You can find the active bluetooth devices near to your mobile which has registered same service(UUID) and you can connect with them.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.bluetooth.*;
import java.util.*;

/**
* @author test
*/
public class Blue extends MIDlet implements CommandListener,DiscoveryListener {
      private List activeDevices;
      private List activeServices;
      private Command select,exit;
      private Display display;
      private LocalDevice local=null;
      private DiscoveryAgent agent = null;
      private Vector devicesFound = null;
      private ServiceRecord[] servicesFound = null;
      private String connectionURL = null;

      public void startApp() {
            display = Display.getDisplay(this);
            activeDevices = new List("Active Devices", List.IMPLICIT);
            activeServices = new List("Active Services", List.IMPLICIT);
            select = new Command("Select", Command.OK, 0);
            exit = new Command("Exit", Command.EXIT, 0);
            activeDevices.addCommand(exit);
            activeServices.addCommand(exit);
            activeDevices.setCommandListener(this);
            activeServices.setCommandListener(this);
            try {
                  local = LocalDevice.getLocalDevice();
            } catch (Exception e) {
            }
            doDeviceDiscovery();
            display.setCurrent(activeDevices);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }

      public void commandAction(Command cmd, Displayable disp) {
            if (cmd == select && disp == activeDevices) {
                  int device = activeDevices.getSelectedIndex();
                  doServiceSearch((RemoteDevice) devicesFound.elementAt(device));
                  display.setCurrent(activeServices);
                  //doServiceSearch( (RemoteDevice)devicesFound.firstElement());
            }
            if (cmd == select && disp == activeServices) {
                  int service = activeServices.getSelectedIndex();
                  connectionURL = servicesFound[service].getConnectionURL(0, false);
                  try {
                        StreamConnection sc = (StreamConnection) Connector.open(connectionURL);
                        OutputStream outStream = connection.openOutputStream();
                        PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
                        pWriter.write("Response String from SPP Server\r\n");
                        pWriter.flush();
                        pWriter.close();
                  } catch (Exception e) {
                        Alert alert = new Alert("");
                        alert.setString(e.toString());
                        display.setCurrent(alert);
                  }
            }
            if (cmd == exit) {
                  destroyApp(false);
            }
      }
      public void inquiryCompleted(int param) {
            switch (param) {
                  case DiscoveryListener.INQUIRY_COMPLETED:
                        /* Inquiry completed normally, add appropriate code
                         * here
                         */
                        if (devicesFound.size() > 0) {
                              activeDevices.addCommand(select);
                              activeDevices.setSelectCommand(select);
                        } else {
                              try {
                                    activeDevices.append("No Devices Found", null);
                                    startServer();
                              } catch (Exception e) {
                              }
                        }
                        break;

                  case DiscoveryListener.INQUIRY_ERROR:
                        // Error during inquiry, add appropriate code here.
                        break;

                  case DiscoveryListener.INQUIRY_TERMINATED:
                        /* Inquiry terminated by agent.cancelInquiry()
                        * Add appropriate code here.
                        */
                        break;
            }
      }

      public void serviceSearchCompleted(int transID, int respCode) {
            switch (respCode) {
                  case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_ERROR:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                        break;
                  case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                        break;
            }
      }

      public void servicesDiscovered(int transID, ServiceRecord[] serviceRecord) {
            servicesFound = serviceRecord;
            activeServices.append(servicesFound.toString(), null);
            activeServices.addCommand(select);
            activeServices.setSelectCommand(select);
      }

      public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
            String str = null;
            try {
                  str = remoteDevice.getFriendlyName(true);
            } catch (Exception e) {
            }
            activeDevices.append(str, null);
            devicesFound.addElement(remoteDevice);
      }

      private void doDeviceDiscovery() {
            try {
                  local = LocalDevice.getLocalDevice();
            } catch (BluetoothStateException bse) {
                   // Error handling code here
            }
            agent = local.getDiscoveryAgent();
            devicesFound = new Vector();
            try {
                  if (!agent.startInquiry(DiscoveryAgent.GIAC, this)) {
                        // Inquiry not started, error handling code here
                  }
            } catch (BluetoothStateException bse) {
                  // Error handling code here
            }
      }

      private void doServiceSearch(RemoteDevice device) {
            int[] attributes = {0x100, 0x101, 0x102};
            UUID[] uuids = new UUID[1];
            uuids[0] = new UUID("1101", false);
            try {
                  agent.searchServices(attributes, uuids, device, this);
            } catch (BluetoothStateException e) {
                  Alert alert1 = new Alert("Error");
                  alert1.setString(e.toString());
                  display.setCurrent(alert1);
            }
      }

      public void startServer() throws IOException {
            UUID uuid = new UUID("1101", false);
            //Create the service url
            String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
            //open server url
            StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
            //Wait for client connection
            System.out.println("\nServer Started. Waiting for clients to connect...");
            StreamConnection connection = streamConnNotifier.acceptAndOpen();
            RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
            System.out.println("Remote device address: " + dev.getBluetoothAddress());
            System.out.println("Remote device name: " + dev.getFriendlyName(true));

            //read string from spp client
            try {
                  DataInputStream in = (DataInputStream) connection.openDataInputStream();
                  /*BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
                  String lineRead=bReader.readLine();
                  System.out.println(lineRead);*/
                  /*//send response to spp client
                  OutputStream outStream=connection.openOutputStream();
                  PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
                  pWriter.write("Response String from SPP Server\r\n");
                  pWriter.flush();
                  pWriter.close();*/
                  streamConnNotifier.close();
            }
      }