Saturday, July 20, 2013

TCL EXAMPLES - Variables

ex_var.tcl


set four 4
set four_real 4.0
set three 3

set threefourths [expr $three / $four]
puts "threefourths: $threefourths"

set threefourths_real [expr $three / $four_real]
puts "threefourths_real: $threefourths_real"

Sunday, June 9, 2013

TCL Tutorials -Expressions


ex_expression.tcl


set r 2.0
set pi [expr { 4 * atan(1.0) }]
set area [expr {$pi * $r * $r}]

puts "r      : $r"
puts "pi     : $pi"
puts "area     : $area"

Friday, June 7, 2013

TCL Tutorials - Quoting


An Example of how to use quotes in tcl


ex_quoting.tcl

set years 32
set years_sub "I am $years";
set years_no_sub {I am $years};

puts "this string got substituted - weak quoting"
puts $years_sub

puts "this string did not substitute - rigid quoting"
puts $years_no_sub

Wednesday, June 5, 2013

TCL Tutorials - Line Continuation


This examples states the use of line continuation

ex_02.tcl

set members { \
abc \
def \
ghi \
jkl \
}
puts $members

Tuesday, June 4, 2013

TCL Tutorials- Comments

I am starting TCL tutorials and will be posting it on a daily basis

comment_example.tcl


#this is a comment

set real_years 4
set dog_name "spot"; #another comment
set dog_years [expr (7*$real_years)]

puts "my dog $dog_name is $real_years"
puts "he acts $dog_years old"

Monday, April 1, 2013

Breadth First Search In TCL

I searched the web for a bfs code and could not find one in tcl that is easy so came up with this one .


bfs.tcl
---------

set visited [list]
set START "0"
set END "5"
set nonodes 6
set graph(0) {}

proc printpath visited {

set path ""
foreach node $visited {
lappend path $node  
}
puts $path
}
proc initgraph { cnt } {

global graph
for {set i 0} {$i < $cnt } { incr i } {
set graph($i) {}
}
}
proc addedge { node1 node2 } {

global graph

set adjacent $graph($node1)
lappend adjacent $node2
set graph($node1) $adjacent
}

proc isconnected { node1 node2 } {

global graph

set adjacent $graph($node1)
return [lsearch -exact $adjacent $node2]
}

proc getadjacentnodes { node1 } {

global graph
return $graph($node1)
}

proc breadthfirstsearch { visited } {

global END START
set nodes [getadjacentnodes [lindex $visited end]]

for {set i 0} {$i < [llength $nodes] } { incr i } {

set node [lindex $nodes $i]
set b [lsearch -exact $visited $node]
if { $b == 1} {
continue
}
set b [string compare $node $END]
if { $b == 0} {
lappend visited $node
printpath $visited

set visited [lreplace $visited [expr [llength $visited]-1] [expr [llength $visited]-1]]
break
}
}
for {set i 0} {$i < [llength $nodes] } { incr i } {

set node [lindex $nodes $i]
set b1 [lsearch -exact $visited $node]
set b2 [string compare $node $END]
if { $b1 == 1  ||  $b2 == 0 } {
continue;
}
lappend visited $node
breadthfirstsearch $visited
set visited [lreplace $visited [expr [llength $visited]-1] [expr [llength $visited]-1]]
}
}

initgraph $nonodes

addedge "0" "1"
addedge "1" "2"
addedge "1" "3"
addedge "1" "4"

addedge "2" "5"
addedge "3" "5"
addedge "4" "5"
addedge "1" "5"

set visited [list $START]

breadthfirstsearch $visited

Tuesday, January 22, 2013

Control VLC Player

Hello all i searched the net for a way in which vlc player can be controlled
And here is the steps

Start VLC using the following command

vlc --extraintf http

Then run the following commands to control it

Play
-------
wget http://127.0.0.1:8080/requests/status.xml?command=pl_play

Stop
-------
wget http://127.0.0.1:8080/requests/status.xml?command=pl_stop






Pause
----------
wget http://127.0.0.1:8080/requests/status.xml?command=pl_pause

Next
-------
wget http://127.0.0.1:8080/requests/status.xml?command=pl_next

Prev
-------
wget http://127.0.0.1:8080/requests/status.xml?command=pl_previous

Monday, December 10, 2012

STRUTS 2 Example Append Tag

Append.jsp
---------------

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!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=UTF-8">

<title>Append Tag Example</title>

</head>

<body>

<h1>Struts 2 Append tag example</h1>

Combine ArrayList1 and ArrayList2 into a single iterator.

<s:append id="AppendList">

<s:param value="%{list1}" />

<s:param value="%{list2}" />

</s:append>

<s:iterator value="%{#AppendList}">

<li><s:property /></li>

</s:iterator>

</body>

</html>
--------------------------------------------------------------------------------------------------------------------------

index.jsp
-------------

<body>

<a href="AppendTag.action">Append Control Tag Example</a>

</body>
--------------------------------------------------------------------------------------------------------------------------
AppendTag.java
----------------------

package kites;

import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
import org.apache.struts2.util.AppendIteratorFilter;

public class AppendTag extends ActionSupport {

private List<String> list1 = new ArrayList<String>();
private List<String> list2 = new ArrayList<String>();

public String execute() throws Exception {

list1.add("USER1");
list1.add("USER2");
list1.add("USER3");

list2.add("user1");
list2.add("user2");
list2.add("user3");

return SUCCESS;
}
public List<String> getList1() {
return list1;
}
public List<String> getList2() {
return list2;
}
}


--------------------------------------------------------------------------------------------------------------------------
struts.xml
---------------

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" />

<constant name="struts.devMode" value="false" />

<constant name="struts.custom.i18n.resources" value="ApplicationResources" />

<package name="default" namespace="/" extends="struts-default">

<action name="AppendTag" class="kites.AppendTag">

<result name="success">/Append.jsp</result>

</action>

</package>

</struts>


--------------------------------------------------------------------------------------------------------------------------

Friday, October 5, 2012

Android Call Blocking

Android Manifest
---------------------------------
<receiver android:name="com.kites.profile.util.PhoneCallReceiver">
            <intent-filter android:priority="100">
                <action android:name="android.intent.action.PHONE_STATE"/>
             </intent-filter>
        </receiver>
 <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

------------------------------------------------------------------------------------------
PhoneCallReceiver.java
--------------------------------
package com.kites.profile.util;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsManager;
import android.util.Log;

public class PhoneCallReceiver extends BroadcastReceiver {
    boolean active = true;
    String replymsg = "";


    Context context = null;
    private static final String TAG = "Phone call";
    private ITelephony telephonyService;
    TelephonyManager telephony = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "Receving....");
        telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
        telephony.listen(customPhoneListener,
                PhoneStateListener.LISTEN_CALL_STATE);

    }

    public void endCall() {
        try {

            Class c = Class.forName(telephony.getClass().getName());
            Method m = c.getDeclaredMethod("getITelephony");
            m.setAccessible(true);
            telephonyService = (ITelephony) m.invoke(telephony);
           
           telephonyService.silenceRinger(); //comment this for android 2.3 and above

            telephonyService.endCall();
            // s
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class CustomPhoneStateListener extends PhoneStateListener {

        private static final String TAG = "CustomPhoneStateListener";

        public void onCallStateChanged(int state, String incomingNumber) {

            Log.v(TAG, "WE ARE Receiving!");
            Log.v(TAG, incomingNumber);
            Log.v(TAG, incomingNumber);            if (active) {
                endCall();
                sendSMS(incomingNumber, replymsg);
            }

            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                Log.d(TAG, "RINGING");
                break;
            }
        }

        public void sendSMS(String no, String msg) {
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(no, null, msg, null, null);
        }
    }
}
--------------------------------------------------------------------------------------------
ITelephony.aidl
---------------------------
package com.android.internal.telephony;

  interface ITelephony {

  
    boolean endCall();

 
    void answerRingingCall();

  
    void silenceRinger();

  }

Thursday, September 27, 2012

Checking Status Of Remote Server

This function will help you identify the status of a remote server


public static boolean check(String ip,int port){
        boolean flag=false;
        try {
            Socket soc= new Socket();
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
           
           
            soc.connect(socketAddress, 5000); // 5 second timeout
            flag=true;
        } catch (Exception e) {
            // TODO: handle exception
            flag=false;
        }
        return flag;
    }

Saturday, September 22, 2012

Line Graph Using Google

Chart.html

I got this piece of code from google api site .
It is pretty handy in generating a line graph


<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses','Profit'],
          ['2004',  1000,      400,1000-400],
          ['2005',  1170,      460,1170-460],
          ['2006',  660,       1120,660-1120],
          ['2007',  1030,      540,1030-540],
            ['2008',  1030,      540,1030-540]
        ]);

        var options = {
          title: 'Company Performance'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Thursday, September 20, 2012

DSA Batch Verification Algorithm

GenSig.java
----------------------------


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

class GenSig {

    public static void main(String[] args) {
   //     args=new String[]{"LabelDemo.java"};
        /* Generate a DSA signature */

        if (args.length != 1) {
            System.out.println("Usage: GenSig nameOfFileToSign");
            }
        else try{

            /* Generate a key pair */

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

            keyGen.initialize(1024, random);

            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey priv = pair.getPrivate();
            PublicKey pub = pair.getPublic();


            /* Create a Signature object and initialize it with the private key */

            Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

            dsa.initSign(priv);

            /* Update and sign the data */

            FileInputStream fis = new FileInputStream(args[0]);
            BufferedInputStream bufin = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                dsa.update(buffer, 0, len);
                };

            bufin.close();

            /* Now that all the data to be signed has been read in,
                    generate a signature for it */

            byte[] realSig = dsa.sign();

       
            /* Save the signature in a file */
            FileOutputStream sigfos = new FileOutputStream("sig");
            sigfos.write(realSig);

            sigfos.close();


            /* Save the public key in a file */
            byte[] key = pub.getEncoded();
            FileOutputStream keyfos = new FileOutputStream("suepk");
            keyfos.write(key);

            keyfos.close();
            System.out.println("Signature Generated");

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }

    };

}






----------------------------------------------------------------------------
Usage: GenSig nameOfFileToSign

-------------------------------------------------------------------------------------------------------------------------
VerSig.java
--------------------

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

class VerSig {

    public static void main(String[] args) {

        /* Verify a DSA signature */
       // args =new String[]{"suepk","sig","1"};//LabelDemo.java"};
        if (args.length != 3) {
            System.out.println("Usage: VerSig publickeyfile signaturefile datafile");
            }
        else try{

            /* import encoded public key */

            FileInputStream keyfis = new FileInputStream(args[0]);
            byte[] encKey = new byte[keyfis.available()]; 
            keyfis.read(encKey);

            keyfis.close();

            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);

            KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
            PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

            /* input the signature bytes */
            FileInputStream sigfis = new FileInputStream(args[1]);
            byte[] sigToVerify = new byte[sigfis.available()];
            sigfis.read(sigToVerify );

            sigfis.close();

            /* create a Signature object and initialize it with the public key */
            Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
            sig.initVerify(pubKey);

            /* Update and verify the data */

            FileInputStream datafis = new FileInputStream(args[2]);
            BufferedInputStream bufin = new BufferedInputStream(datafis);

            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                sig.update(buffer, 0, len);
                };

            bufin.close();


            boolean verifies = sig.verify(sigToVerify);

            System.out.println("signature verifies: " + verifies);


        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
};

    }

}
--------------------------------------------------------------------------------------------------------
Usage: VerSig publickeyfile signaturefile datafile
---------------------------------------------------------------------------------


Tuesday, September 18, 2012

Struts2 Programs Tags 015 if elseif else tag

IfControlTag.jsp
------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>

<!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=UTF-8">

<title>Insert title here</title>

</head>

<body>

<s:set name="Name" value="%{'Gyan'}" />

<s:if test="%{#Name=='Singh'}">You Working with--

<div><s:property value="%{#Name}" /></div>

<div>Your Name is Gyan</div>

</s:if>

<s:elseif test="%{#Name=='Gyan'}">You Working with--

<div><s:property value="%{#Name}" /></div>

<div>My Name is Gyan</div>

</s:elseif>

<s:else>for false condition

<div>Your Name is Not Specified</div>

</s:else>

</body>

</html>
--------------------------------------------------------------------------------------------------------------------------
index.jsp
---------------
<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!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=UTF-8">

<title>If Control Tag</title>

</head>

<body>

<ul>

<li><a href="IfControlTag.jsp">IF Control Tag Example</a></li>

</ul>

</body>

</html>
---------------------------------------------------------------------------------------------------------------------
Result.java
-------------------
 package kites;

import com.opensymphony.xwork2.ActionSupport;

public class Result extends ActionSupport{

public String execute() throws Exception {

return SUCCESS;

}

}
-----------------------------------------------------------------------------------------------------------------------
struts.xml
------------------

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.enable.DynamicMethodInvocation"

value="false" />

<constant name="struts.devMode" value="false" />

<constant name="struts.custom.i18n.resources"

value="ApplicationResources" />

<package name="kites" extends="struts-default" namespace="/">

<action name="Result" class="kites.Result" >

<result name="SUCCESS">/IfControlTag.jsp</result>

</action>

</package>

</struts>
---------------------------------------------------------------------------------------------------------------------


Tuesday, September 11, 2012

Android Programs 005 RadioButton

RadioButtonDemo.java
--------------------------------------

package com.kites.radiotest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;

public class RadioButtonDemo extends Activity
    implements RadioGroup.OnCheckedChangeListener{

    RadioGroup rg;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        rg=(RadioGroup)findViewById(R.id.rg);
        rg.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group,
                                int checkedId) {
        if (group==rg) {
            if (checkedId==R.id.r1) {
               
            }
            else if (checkedId==R.id.r2) {
               
            }
            else if (checkedId==R.id.r3) {
               
            }
        }
    }
}
-----------------------------------------------------------------------------------------------------------------------------
main.xml
----------------

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
    xmlns:android=
    "http://schemas.android.com/apk/res/android"
    android:id="@+id/rg"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
        <RadioButton android:id="@+id/r1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio1" />

        <RadioButton android:id="@+id/r2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio2" />

        <RadioButton android:id="@+id/r3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio3" />
</RadioGroup>
-------------------------------------------------------------------------------------------------------------------------------

Monday, September 3, 2012

STRUTS2 Examples 014 Non Field Validators

home.jsp
--------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Home Page</title>
</head>
<body bgcolor="lightblue"><br><br><br><br><br>
<h1>Welcome </h1><s:property value="userName"/>
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------------
login.jsp
-------------
<%@ taglib prefix="s" uri="/struts-tags"%>
<link href="<s:url value="css/style.css"/>" rel="stylesheet"
type="text/css" />
<s:actionerror />
<center>
<h1>Please Login</h1>
</center>
<s:form method="POST" action="nonField">
<s:textfield name="userName" label="User Name" />
<s:textfield name="password" label="Password" />
<s:submit label="Submit" />
</s:form>
----------------------------------------------------------------------------------------------------------------------------------
LoginAction.java
---------------------------
package com.kites.action;

import com.kites.model.LoginModel;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class LoginAction extends ActionSupport implements
        ModelDriven<LoginModel> {

    private static final long serialVersionUID = 1L;
    LoginModel model;

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        if (!model.getUserName().equals("")) {
            return SUCCESS;
        }
        return INPUT;
    }

    @Override
    public LoginModel getModel() {
        // TODO Auto-generated method stub
        model = new LoginModel();
        return model;
    }

}

---------------------------------------------------------------------------------------------------------------------------
LoginAction-validation.xml
-------------------------------------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Home Page</title>
</head>
<body bgcolor="lightblue"><br><br><br><br><br>
<h1>Welcome </h1><s:property value="userName"/>
</body>
</html><!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>

<validator type="expression">
<param name="fieldName">userName</param>
<message>You must enter the User Name</message>
</validator>

<validator type="expression">
<param name="fieldName">password</param>
<message>You must enter Password</message>
</validator>

</validators>

--------------------------------------------------------------------------------------------------------------------------------
LoginModel.java
----------------------------
package com.kites.model;

import java.io.Serializable;

public class LoginModel implements Serializable {

    private static final long serialVersionUID = 1L;
    private String userName;
    private String password;
   
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
   
    public String display(){
        return "input";
    }
}
-------------------------------------------------------------------------------------------------------------------------------
struts.xml
----------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.devMode" value="true" />

<package name="kites" namespace="/" extends="struts-default">

<action name="login" method="display" class="com.kites.model.LoginModel">
<result name="input">login.jsp</result>
</action>

<action name="nonField" class="com.kites.action.LoginAction">
<result name="success">home.jsp</result>
<result name="input">login.jsp</result>
</action>

</package>

</struts>
-------------------------------------------------------------------------------------------------------------------------------
web.xml
----------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<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>
</web-app>
-------------------------------------------------------------------------------------------------------------------------------

Sunday, September 2, 2012

Android Examples 004 CheckBox

CheckBoxDemo.java
------------------------------------


package com.kites.checkboxdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class CheckBoxDemo extends Activity
    implements CompoundButton.OnCheckedChangeListener {

    CheckBox cb;
   
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
       
        cb=(CheckBox)findViewById(R.id.check);
        cb.setOnCheckedChangeListener(this);
/*       
        cb.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener(){
                public void onCheckedChanged(
                    CompoundButton buttonView,   
                    boolean isChecked) {
       
                }
            }
        );
*/   
    }
    public void onCheckedChanged(
        CompoundButton buttonView,           
            boolean isChecked) {
        if (isChecked) {
            cb.setText("This checkbox is: checked");
        }
        else {
            cb.setText("This checkbox is: unchecked");
        }
    }
}

------------------------------------------------------------------------------------------------------------------
main.xml
----------------
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
    xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This checkbox is: unchecked" />

Monday, August 27, 2012

STRUTS2 Programs 013 field validator

EmailValidationAction.java
-------------------------------------------
package kites;

import com.opensymphony.xwork2.ActionSupport;

public class EmailValidationAction extends ActionSupport {

private String email;

public String getEmail() {

return email; }

public void setEmail(String email) {

this.email = email; }

@Override

public String execute() throws Exception {

// TODO Auto-generated method stub

return SUCCESS; }

}

------------------------------------------------------------------------------------------------------------------------------
EmailValidationAction-validation.xml
------------------------------------------------------------
<!DOCTYPE validators PUBLIC

"-//OpenSymphony Group//XWork Validator 1.0.2//EN"

"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="email">
<field-validator type="requiredstring">
<message>Email id is required</message>
</field-validator>
<field-validator type="email">
<message>Please enter valid email id.</message>
</field-validator>
</field>

</validators>

---------------------------------------------------------------------------------------------------------------------------------
index.jsp
--------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib uri="/struts-tags" prefix="s" %>

<html>

<head><title>Email_Validator_Example</title><s:head/></head>

<body>Email_Validator_Example.....

<s:form action="emailvalidation.action">

<s:textfield name="email" label="Email-Id :"></s:textfield>

<s:submit></s:submit></s:form>

</body>

</html>

--------------------------------------------------------------------------------------------------------------------------------
struts.xml
----------------
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" />

<constant name="struts.devMode" value="false" />

<package name="kites" namespace="/" extends="struts-default">

<action name="emailvalidation" class="kites.EmailValidationAction">

<result name="input">index.jsp</result>

<result name="error">index.jsp</result>

<result>successJsp.jsp</result>

</action></package>

</struts>

-------------------------------------------------------------------------------------------------------------------------------
success.jsp
-------------------
<%@ page language="java"

contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib uri="/struts-tags" prefix="s" %>

<html>

<head><title>Insert title here</title></head>

<body>Email-Id....

<s:property value="email"/></body>

</html>

-------------------------------------------------------------------------------------------------------------------------------
web.xml
-----------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<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>
</web-app>

------------------------------------------------------------------------------------------------------------------------------

Sunday, August 26, 2012

Android Example Edit Text

FieldDemo.java
-------------------------

package com.kites.fielddemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class FieldDemo extends Activity {

public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

EditText fld=(EditText)findViewById(R.id.field);
fld.setText("Hello " +"World");
String st =fld.getText();

}
}

-------------------------------------------------------------------------------------------------------------------------------
main.xml
---------------

<?xml version="1.0" encoding="utf-8"?>
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/field"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:singleLine="false"
/>

Friday, August 24, 2012

JSTL CORE Tag Example c:out

coutexample.jsp
--------------------------------
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:out Tag Example</title>
</head>
<body>
<c:out value="${'<tag> , &'}"/>
</body>
</html>

Thursday, August 23, 2012

STRUTS2 Programs 012 Client side validation

index.jsp
----------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Index Page</title>
</head>
<body><h3>Struts2_Client_Side_Validation_Example</h3>
<s:a href="registrationForm.action"><FONT color="green" >Go To Login Page..</FONT> </s:a>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------
package.properties
----------------------------------
requiredstring = ${getText(fieldName)} is required.
firstname = Student Name
password= Password


--------------------------------------------------------------------------------------------------------------------------------
RegistrationAction.java
---------------------------------------

package kites.action;

import kites.Model.RegistrationModel;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class RegistrationAction extends ActionSupport implements
ModelDriven<Object> {
RegistrationModel obRegModel;
public String execute() {
return SUCCESS;
}
@Override
public Object getModel() {
obRegModel = new RegistrationModel();
return obRegModel;
}
}

----------------------------------------------------------------------------------------------------------------------------------
RegistrationAction-validation.xml
------------------------------------------------------
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="firstname">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
<field name="password">
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">15</param>
<param name="trim">true</param>
<message >Please enter Min %{minLength} character or Max %{maxLength} Character </message>
</field-validator>
</field>
</validators>
----------------------------------------------------------------------------------------------------------------------------
RegistrationForm.jsp
----------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Registration Form</title></head>
<s:head/>
<body>
<h3 >Struts2_Client_Side_Validation_Example</h3>
<hr>
<font style="color: green;"> Registration Form</font>
<s:form action="registrationProcess.action" name="registration" method="post">
<s:textfield key="firstname" />
<s:password key="password"/>
<s:submit value="Registration"/>
</s:form>
</body>
</html>

---------------------------------------------------------------------------------------------------------------------------------
RegistrationModel.java
--------------------------------------
package kites.Model;

import java.io.Serializable;
public class RegistrationModel implements Serializable
{
private String firstname;
private String password;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
--------------------------------------------------------------------------------------------------------------------------------
RegistrationSuccess.jsp
-------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2 style="color: green">Hi,
<s:property value="firstname"/>
your welcome.</h2>
<h3 style="color: gray;">Login success.</h3>
</body>
</html>

---------------------------------------------------------------------------------------------------------------------------------------
struts.xml
-------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="kites" namespace="/" extends="struts-default">
<action name="registrationForm">
<result>/RegistrationForm.jsp</result>
</action>
<action name="registrationProcess" class="kites.action.RegistrationAction">
<result name="input">RegistrationForm.jsp</result>
<result name="error">RegistrationForm.jsp</result>
<result>RegistrationSuccess.jsp</result>
</action>
</package>
</struts>

--------------------------------------------------------------------------------------------------------------------------------
web.xml
----------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2_Client_Side_Validation_Example</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

------------------------------------------------------------------------------------------------------------------------------------------------