Saturday, February 28, 2015

STRUS2 Custom Validation example

Note: Put all  xml and java files into your src folder

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.devMode" value="true" />
    <package name="default" extends="struts-default">
        <action name="loginAction" class="LoginAction">
            <result name="success">Welcome.jsp</result>
            <result name="input">Login.jsp</result>
        </action>
    </package>
</struts>


 
validator.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator Config 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">

<validators>
    <validator name="alphabetsOnly" class="EliteValidator" />
    <validator name="digitsOnly" class="EliteValidator" />
</validators>


Login-Action.validation.xml

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
   
<validators>
   
    <field name="username">
       
        <field-validator type="requiredstring">
            <message>Empty Username !</message>            
        </field-validator>
       
       
        <field-validator type="alphabetsOnly">
            <message>Digits not allowed in Username</message>            
        </field-validator>
       
    </field>
   
    <field name="password">
       
        <field-validator type="requiredstring">
            <message>Empty Password !</message>            
        </field-validator>
       
    </field>
   
    <field name="mobileNumber">
       
        <field-validator type="requiredstring">
            <message>Empty Mobile Number !</message>            
        </field-validator>
               
        <field-validator type="digitsOnly">           
            <message>Alphabets not allowed in Mobile Number</message>            
        </field-validator>
       
    </field>
   
</validators>

LoginAction.java


import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
   
    private String username;
    private String password;
    private String mobileNumber;
   
    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }
    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    /**
     * @return the mobileNumber
     */
    public String getMobileNumber() {
        return mobileNumber;
    }
    /**
     * @param mobileNumber the mobileNumber to set
     */
    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

}


EliteValidator.java


import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class EliteValidator extends FieldValidatorSupport{

    @Override
    public void validate(Object object) throws ValidationException {
            System.out.println("INSIDE VALIDATE OF ELITEVALIDATOR");
           
            String fieldName = getFieldName();
            String fieldValue = (String)getFieldValue(fieldName, object);
           
            System.out.println("FieldName: "+fieldName);
            System.out.println("fieldValue: "+fieldValue);
           
            if(fieldName.equalsIgnoreCase("username") && fieldValue.matches(".*\\d.*")){
                System.out.println("Found numbers in username");
                addFieldError(fieldName, object);
               
            } else if(fieldName.equalsIgnoreCase("mobileNumber") && (fieldValue.matches(".*\\d.*")==false)){
                System.out.println("Found Alphabets in mobileNumber");
                addFieldError(fieldName, object);
            }
           
            return;
    }

}


Note: PUT JSP IN THE WEBCONTEXT FOLDER OF YOUR APP
Login.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>Login</title>
<style>
    .errorMessage{
        color:red;
        font-size: 11px;
        text-align:right;
    }
</style>
</head>
<body>
    <center>
        <s:form action="loginAction" method="post" validate="true" >
            <s:textfield     name="username" label="Username"    />
            <s:textfield     name="password" label="Password"    />
            <s:textfield      name="mobileNumber" label="Mobile Number"/>
            <s:submit/>
        </s:form>
    </center>
</body>
</html>


Welcome.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    WELCOME TO CUSTOM VALIDATION DEMO PROJECT
</body>
</html>

Friday, February 20, 2015

JQUERY TO COUNT TOTAL SELECTED CHECKBOXES

function checkTotalSeleted(){

   var lengthTotal = $('input[name=ids]:checked').length;

    if(lengthTotal!="0"){
$("#totalSelected").html("Total selected: +lengthTotal);

    }else{
    $("#totalSelected").html("");
   }
}

Thursday, February 12, 2015

CHECK CHECKBOX AND CHANGE ROW COLOR, CLICK ROW AND CHECK CHECKBOX AND CHANGE ROW COLOR, CLICK PARENT AND CHECK ALL CHECKBOXES



$(document).ready(function() {

             //  CHECK PARENT CHECKBOX AND SELECT ALL CHILD CHECKBOXES

   $('#selectAll').click(function(event) {  //on click    
       if(this.checked) { // check select status
        $("[name=ids]").prop("checked", true); 
        $('tr').addClass('selected');  
       }else{
        $("[name=ids]").prop("checked", false);
        $('tr').removeClass('selected');
       }
   });

             //  SELECT CHECKBOX AND CHANGE ROW COLOR
   

   $("table").on("change", ":checkbox", function() {
    if(this.checked){
    $(this).parents("tr").addClass('selected');
    }else{
    $(this).parents("tr").removeClass('selected');
    }
   });

           // CLICK ON ROW AND CHANGE ITS COLOR AND CHECKED CHECKBOX
           $('#'+tableId ).on( 'click', 'tr', function (event) {
                  if (event.target.type !== 'checkbox') {
                  $(this).toggleClass('selected');
                         $(':checkbox', this).trigger('click');
                  }       

           });

});

Wednesday, February 11, 2015

JAVA SCRIPT HOW TO ADD FUNCTION INTO JSON OBJECT

var beanPropertyArray = [];

columnData = {
    "1": "One", 
     "2": "Two", 
    "myFun": function ( ) {
                                            return 1*2;
                                 }

beanPropertyArray.push(columnData);

Noyr : now direct use the beanPropertyArray as a JSON object it will give you the function in the json data. Do NOT use JSON.stringify(beanPropertyArray).


Tuesday, February 3, 2015

SLF4J DBSPY TEST CODE

Required Libs

log4j-1.2.16.jar
log4jdbc4-1.2.jar
log4j-over-slf4j-1.7.5.jar
slf4j-api.jar
slf4j-jdk14.jar
slf4j-log4j12-1.7.5.jar

slf4j-simple-1.7.5.jar

Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class SpyEngine {

public static void main(String[] rk) {

try {

  Class.forName("net.sf.log4jdbc.DriverSpy");
Connection conn = DriverManager.getConnection( "jdbc:log4jdbc:oracle:thin:@192.168.8.87:1521:aaadb", "username", "password");

PreparedStatement prStmt = conn.prepareStatement("select * from tablename");
prStmt.execute();
prStmt.close();

  conn.close();
 
} catch (Exception e) {
System.out.println("Error: " + e);

}

}

Keep Visiting..
Write your comment..


Monday, February 2, 2015

HOW TO SEND AND RECEIVE ARRAYLIST TO ACTION IN STRUTS2

jars
gson-2.2.4.jar
struts2-json-plugin-2.3.16.3.jar
and other required jar files for struts2


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.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<constant name="struts.enable.SlashesInActionNames" value="true" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />

<package name="searchPkg" namespace="/searchNs" extends="json-default">

<action name="*/*/*" class="com.elitecore.nvsmx.policydesigner.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<result type="json">
<param name="root">pageDataList</param>
</result>
</action>

</package>  


</struts>

ACTION/CONTROLLER

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

/**
 * @author Kirpalsinh.raj
 *
 */
public class PkgCTRL extends ActionSupport {
private List<PkgData> pageDataList = new ArrayList<PkgData>(10);

public String getPageData(){
 
try {        
            Gson gson = new Gson();
            List<PkgData> pkgDatas = gson.fromJson(listData, new TypeToken<List<PkgData>>() {}.getType());             
           
            int iBeginIndex = 3;                        
            int iEndIndex = 10;
           
            if(iEndIndex > pkgDatas.size()){
               iEndIndex = pkgDatas.size();
            }
           
            pageDataList.clear();
            pageDataList =  pkgDatas.subList(iBeginIndex, iEndIndex);    
       }
   }      
}catch (Exception e) {
   LogManager.getLogger().trace(MODULE,e);
}

return Results.SUCCESS;
}

}


JSP
<%@page import="com.google.gson.reflect.TypeToken"%>
<%@page import="java.util.*"  %>
<%@page import="com.raj.nvsmx.pd.model.pkg.PkgData,com.google.gson.Gson" %>
<%@page import="com.google.gson.Gson" %>
<%@page import="java.lang.reflect.Type" %>

<%
List<PkgData> pkgsList = (List<PkgData>) request.getAttribute("pkgsList");
Type pkgListType = new TypeToken<List<PkgData>>() {}.getType();
String json = new Gson().toJson(pkgsList,pkgListType);
%>
<script>

function getListData(){
 var url = "/searchNs/pkg/Pkg/getPageData";

 $.ajax({
   type: "POST",    
   url: contextPath+url,
   data: {listData:'<%=json%>'},    
   success: function(jsonDataArray){     
    for (var i = 0; i < jsonDataArray.length; i++) {    
    jsonDataArray[i].description
    jsonDataArray[i].packageMode
    jsonDataArray[i].status
    jsonDataArray[i].validityPeriod            
        }
   },
   error: function(jsonData){
   }
});
}


</script>

POJO

public class PkgData implements Serializable {


private static final long serialVersionUID = 1L;

private String id;          
private String name;                
private String description;         
private String type;                
private String status;              
private String packageMode;                
private Integer validityPeriod;     
private String validityPeriodUnit;
private Double price;               
private Timestamp createdDate;        
private Long createByStaffId;

...setter and getter method

}

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...