Wednesday, April 30, 2014

Remove special character

<script language="javascript" type="text/javascript">
          function RemoveSpecialChar(u_name) {
            u_name.value = u_name.value.replace(/[ \/ , {} [ \] % @ # ! $ & * ` \\ ~ + = " ; ? ( ) | < > ' ^ :-]+/g, "");
           }
   </script>



<s:textfield name="u_name" cssClass="input_field"  javascript:RemoveSpecialChar(this); valid(this)"></s:textfield>

Monday, January 6, 2014

Remove Special Characters from Textbox Using JavaScript

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Remove Special Characters from the Textbox using JavaScript</title>
<script language="javascript" type="text/javascript">
function RemoveSpecialChar(txtName) {
if (txtName.value != '' && txtName.value.match(/^[\w ]+$/) == null) {
txtName.value = txtName.value.replace(/[\W]/g, '');
}
}
</script>
</head>
<body>
<div>
<b>Enter Text:</b><input id="txtName"  type="text" onkeyup="javascript:RemoveSpecialChar(this)" />
</div>
</body>
</html>

Monday, April 22, 2013

Upload .csv file in struts1

fileupload.jsp



<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@page import="java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"  session="false"%>
     <%!
       String Path=null;
        HttpSession session;
       String basePath =null;
   
     
     %> <%
       Path = request.getContextPath();
      basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+Path+"/";
     %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Stats Section </title>
 
 
  </head>

<body>
   
     <html:form action="/FileUploadControl" method="post" enctype="multipart/form-data" styleId="stateformid">
            <html:file property="statsfile">Upload</html:file>
            <html:submit>Add</html:submit>
     
      </html:form>
     
</body>
</html>

FileUploadControl.java



package action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import bean.AddFileBean;
import dao.DaoFactory;
import dao.SqlDao;

public class FileUploadControl extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
 {
HttpSession session = request.getSession(false);
ServletContext context =   getServlet().getServletContext();
String excel_location =context.getInitParameter("excelpath");
excel_location =request.getRealPath(excel_location);
excel_location =excel_location+"/";
DaoFactory sql = new SqlDao();
AddFileBean addfile = new AddFileBean();

int i = 0;
int id = 0;
AddFileBean addfile1 =   (AddFileBean)form;
FormFile statsfile = addfile1.getStatsfile();
String fileName1   =   statsfile.getFileName();
if(!fileName1.equals(""))
{
 
    File fileToCreate = null;
   
   
    if(fileName1.equals(""))
    {
    fileName1 = "";
    }
    else
    {
      fileToCreate = new File(excel_location, statsfile.getFileName());
    FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
    fileOutStream.write(statsfile.getFileData());
    fileOutStream.flush();
          fileOutStream.close();
    }
           excel_location=excel_location+statsfile.getFileName();
           String  excel_location1 =  excel_location.replace("\\","/");
          sql.AddData(excel_location1);
 }
else
{
i = 1 ;
}

if(i!=1)
   return mapping.findForward("success");
else
return mapping.findForward("error");
}}



AddFileBean.java


package bean;

import org.apache.struts.upload.FormFile;

public class AddFileBean extends org.apache.struts.validator.ValidatorForm
{

private FormFile statsfile;



public FormFile getStatsfile()
{
return statsfile;
}
public void setStatsfile(FormFile statsfile)
{
this.statsfile = statsfile;
}

}



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:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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_2_5.xsd" id="WebApp_ID" version="2.5">
  <context-param>
    <param-name>excelpath</param-name>
    <param-value>/Excel</param-value>
  </context-param>
  <display-name>nccp</display-name>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>FileUploadControl</display-name>
    <servlet-name>FileUploadControl</servlet-name>
    <servlet-class>Action.FileUploadControl</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUploadControl</servlet-name>
    <url-pattern>/FileUploadControl</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>/fileupload.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>
    <taglib>
      <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
    </taglib>
  </jsp-config>
 
</web-app>

struts-config.xml


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

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
    <form-beans>
<form-bean name="AddFileBean" type="bean.AddFileBean"/>
    </form-beans>

    <global-exceptions>

    </global-exceptions>

    <global-forwards>
        <forward name="welcome"  path="/Welcome.do"/>
    </global-forwards>

    <action-mappings>
<action input="fileupload.jsp" name="AddFileBean" path="/FileUploadControl" scope="request" type="action.FileUploadControl">
            <forward name="success" path="/success.jsp" />
            <forward name="error" path="/error.jsp" />
        </action>
       <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>

    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="action/ApplicationResource"> </message-resources>

    <!-- ========================= Tiles plugin ===============================-->
    <!--
    This plugin initialize Tiles definitio n factory. This later can takes some
    parameters explained here after. The plugin first read parameters from
    web.xml, thenoverload them with parameters defined here. All parameters
    are optional.
    The plugin should be declared in each struts-config file.
    - definitions-config: (optional)
    Specify configuration file names. There can be several comma
    separated file names (default: ?? )
    - moduleAware: (optional - struts1.1)
    Specify if the Tiles definition factory is module aware. If true
    (default), there will be one factory for each Struts module.
    If false, there will be one common factory for all module. In this
    later case, it is still needed to declare one plugin per module.
    The factory will be initialized with parameters found in the first
    initialized plugin (generally the one associated with the default
    module).
    true : One factory per module. (default)
    false : one single shared factory for all modules
    - definitions-parser-validate: (optional)
    Specify if xml parser should validate the Tiles configuration file.
    true : validate. DTD should be specified in file header (default)
    false : no validation

    Paths found in Tiles definitions are relative to the main context.
    -->
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
        <set-property property="moduleAware" value="true" />
    </plug-in>

    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
</struts-config>










Upload .csv file in struts2

fileupload.jsp



<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="false"%>
<html>
<head>
 <s:head />
   <title>File Upload Page</title>
</head>
 <s:actionerror/>
 <body>
   <table border="0" align="center" bordercolor="red">
    <s:form action="uploadAction" method="POST" enctype="multipart/form-data">
 <tr>
      <td style="color: red;">
    Chose File:    <s:file name="uploadFile"  size="40" cssStyle="color:green"/>
        <s:iterator value="fieldErrors.uploadFile"><s:property/></s:iterator>
      </td>
 </tr>
  <tr>
       <td>
          <s:submit value="Upload" name="submit" cssStyle="color:green"/>
      </td>
 </tr>
    </s:form>
    </table>
 </body>
 </html>


FileUploadAction.java



package action;
import java.io.File;

import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import sqldao.DaoFactory;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{
private static final long serialVersionUID = 1L;


private File uploadFile;
private String uploadFileContentType;
private String uploadFileFileName;

public File getUploadFile() {
return uploadFile;
}
public void setUploadFile(File uploadFile) {
this.uploadFile = uploadFile;
}

public String getUploadFileContentType() {
return uploadFileContentType;
}
public void setUploadFileContentType(String uploadFileContentType) {
this.uploadFileContentType = uploadFileContentType;
}

public String getUploadFileFileName() {
return uploadFileFileName;
}
public void setUploadFileFileName(String uploadFileFileName) {
this.uploadFileFileName = uploadFileFileName;
}
DaoFactory dao = DaoFactory.getDao("sql");

public String execute()
{
try{
if(uploadFileFileName==null){
addFieldError("uploadFile", "file is required");
return INPUT;
}
String name = getUploadFileFileName();
        String []fileext = name.split("\\.");
        String ext = fileext[1];
if(ext.equals("csv")){
ServletContext context = ServletActionContext.getServletContext();
        String filePath = context.getRealPath("csvfile");
        String csv_location  = filePath+"/";
                 File fileToCreate = new File(csv_location, uploadFileFileName);
                 FileUtils.copyFile(uploadFile, fileToCreate);
                 String filePathname = csv_location+uploadFileFileName;
                 String filerealpath  = filePathname.replace("\\", "/");
        dao.insertdata(filerealpath);
}else{
  addFieldError("uploadFile", "Upload only csv file");
  return INPUT;
        }
}catch(Exception e)
{
e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;
}
return SUCCESS;
}

public Object getModel(){

return null;
}

}


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.multipart.maxSize" value="164703120" />
     <constant name="struts.ui.theme" value="simple"/>
    <include file="struts-default.xml"/>
    <package name="a" extends="struts-default">
   
        <action name="uploadAction" class="action.FileUploadAction"> 
        
            <interceptor-ref name="exception" />
<interceptor-ref name="alias" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="prepare" />
<interceptor-ref name="i18n" />
<interceptor-ref name="chain" />
<interceptor-ref name="debugging" />
<interceptor-ref name="profiling" />
<interceptor-ref name="scopedModelDriven" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload">
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="checkbox" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams"> dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="input">/index.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_2_5.xsd" id="WebApp_ID" version="2.5">
  <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>







Struts2 Framework Interceptors


Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below:
SNInterceptor & Description
1alias
Allows parameters to have different name aliases across requests.
2checkbox
Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked.
3conversionError
Places error information from converting strings to parameter types into the action's field errors.
4createSession
Automatically creates an HTTP session if one does not already exist.
5debugging
Provides several different debugging screens to the developer.
6execAndWait
Sends the user to an intermediary waiting page while the action executes in the background.
7exception
Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection.
8fileUpload
Facilitates easy file uploading.
9i18n
Keeps track of the selected locale during a user's session.
10logger
Provides simple logging by outputting the name of the action being executed.
11params
Sets the request parameters on the action.
12prepare
This is typically used to do pre-processing work, such as setup database connections.
13profile
Allows simple profiling information to be logged for actions.
14scope
Stores and retrieves the action's state in the session or application scope.
15ServletConfig
Provides the action with access to various servlet-based information.
16timer
Provides simple profiling information in the form of how long the action takes to execute.
17token
Checks the action for a valid token to prevent duplicate formsubmission.
18validation
Provides validation support for actions

Tuesday, April 2, 2013

Multithreading in java

Multithreading is a  process of executing multiple threads simultaneously. Thread is basically a lightweight subprocess , a smallest  unit of processing .

Multithreading is  mostly  used games, animation etc.



Extending the Thread Class
The steps for creating a thread by using the fi rst mechanism are:
 1. Create a class by extending the Thread class and override the run() method:
class MyThread extends Thread {
 public void run() {
 // thread body of execution
 }
 }
 2. Create a thread object:
MyThread thr1 = new MyThread();
 3. Start Execution of created thread:
thr1.start();



THREAD LIFE CYCLE
The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.
During its life cycle the thread moves from one state to another depending on the operation performed by it
or performed on it as illustrated in Fig. 14.4. A Java thread can be in one of the following states:
∑ NEW
 A thread that is just instantiated is in new state. When a start() method is invoked, the thread
moves to the ready state from which it is automatically moved to runnable state by the thread
scheduler.
∑ RUNNABLE (ready running)
 A thread executing in the JVM is in running state.
∑ BLOCKED
 A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread
performs an I/O operation and moves to next (runnable) state.
∑ WAITING
 A thread that is waiting indefi nitely for another thread to perform a particular action is in this state.
∑ TIMED_WAITING (sleeping)
 A thread that is waiting for another thread to perform an action for up to a specifi ed waiting time is in
this state.

Monday, April 1, 2013

Variable and Datatype in java


Variable  : -   Variable is name of memory location .

 There are three  types of  variables in java.

 1. local
2.  instance
3.  static


1. local

    variable declare inside the meth