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" />