Tuesday, October 25, 2011

CONVERT A TABLE COLUMN(CHAR) TO ANOTHER DATA TYPE(INTEGER)


If you want to change character to integer in postgresql use the following



1) Create a function
CREATE OR REPLACE FUNCTION otc_chartoint(chartoconvert character varying)
  RETURNS integer AS
$BODY$
SELECT CASE WHEN trim($1) SIMILAR TO '[0-9]+'
        THEN CAST(trim($1) AS integer)
    ELSE NULL END;

$BODY$
  LANGUAGE 'sql' IMMUTABLE STRICT;



2)Run this query
 ALTER TABLE <Table Name> ALTER COLUMN <Column Name> TYPE integer USING otc_chartoint(<Column Name>);

Thursday, October 13, 2011

Username and Password Validation in JSP using Postgresql

Index.jsp


<h2><font color="#0000FF"><b>Validation&nbsp;</b></font></h2>
<form name="frm" action="Validation" method="Post" >
Name:<input type="text" name="username" value=""/><br>
<b>
Password:</b><input type="password" name="password" value=""/>
<input type="submit" value="Check" />
</form>


Web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.4">

<display-name>Welcome to Tomcat</display-name>
<description>Welcome to Tomcat</description>

<servlet>
<servlet-name>Validation</servlet-name>
<servlet-class>User.Validation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Validation</servlet-name>
<url-pattern>/Validation</url-pattern>
</servlet-mapping>

</web-app>

User.Validation.java


package User;

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validation extends HttpServlet{

private static final long serialVersionUID = 1L;
private ServletConfig config;

public void init(ServletConfig config)
 throws ServletException{
this.config=config;
  }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{

PrintWriter out = response.getWriter();
String connectionURL = "jdbc:postgresql://localhost/test";
Connection connection=null;
ResultSet rs;
String userName = null;
String passwrd  = null;
response.setContentType("text/html");
String jspun = request.getParameter("user");
String jsppd = request.getParameter("pass");
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(connectionURL, "postgres", "postgres");
String sql = "select user_nm, passwd from user_pass where user_nm='"+jspun+"' and passwd='"+jsppd+"'";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
userName = rs.getString("user_nm");
passwrd  = rs.getString("passwd");
}
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
}

if(userName.equals(jspun) && passwrd.equals(jsppd)){
out.println("User is Valid");
}
else{
out.println("You are not a Valid User");
}
}
}


Sql

create database test;

create table user_pass (
user_nm character varying(30) NOT NULL,
  passwd character varying(128)
);


Friday, September 30, 2011

Struts


1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
  • Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

  • View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

  • Controller:The controller reacts to the user input. It creates and sets the model
2 .What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

3.What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

4. What is Struts?  
Struts is an open source software that helps developers to easily build web application. It is a web page development framework which comprises of Java Servlets, Java Server Pages, custom tags, and message resources into a single framework. It is also a cooperative platform for development teams as well as independent developers.

5. Explain the components of Struts?
Struts is based on the MVC design pattern and its components can be categorized into:
Model: Components like business logic / business processes and data are parts of this.
View: It contains JSP, HTML etc.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.


6.What are the core classes of the Struts Framework?
Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.
  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).
  • Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

7. How will we make any Of the Message Resources Definitions file available to the Struts Framework Environment?
Message Resources Definitions file are simple property files which consists of messages that can be used in the struts applications. Message Resources Definitions files can also be added to the struts-config.xml file using <message-resources /> tag.
E.g. <message-resources parameter="Message Resources" />

4. What is Struts Validator Framework?
Struts Framework provides the functionality to validate the form data. This can be used to validate data on both the client side as well as server side. It emits the java scripts and can be used to validate data on the user’s browser and incase of server side validation, it is done by sub classing the From Bean with DynaValidatorForm class.
The Validator framework comes integrated with the Struts Framework and can be used without doing any extra change in settings.

5. Is struts thread safe?
Struts is thread safe as well as thread-dependant. Light-weight Action object handles the response to a request instead of individual servlets. The Action class is instantiated only once and lets the other requests to be threaded through the original object available. This technique helps to provide the best possible throughput and conserves resources. A properly-designed application will exploit this further by routing related operations through a single Action.

6. What are the core classes of the Struts Framework?
The core classes of Struts framework are:
ActionServlet is the back bone of the whole web application.
ActionForm is a Java bean that associates one or more ActionMappings.
The business logic is wrapped by the Action class which provides an interface to the Model of the application.
ActionMapping is used to provide mappings for Objects to Actions.
ActionForward represent the destination for the controller.

7. What are the different kinds of actions in Struts?
The different kinds of actions in Struts are as follows:
a. ForwardAction.
b. IncludeAction.
c. DispatchAction.
d. LookupDispatchAction.
e. SwitchAction.

8. What is Action Class?
The Action Class is a part of the Model. Its purpose is to translate the HttpServletRequest to the business logic and use the Action, we need to have a Subclass and overwrite the execute() method, In which all the database/ business processing are done. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method and its return type is used by the Struts Framework to forward the request to the file according the value of the returned ActionForward object.


13.What is role of Action Class?
An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

14.In which method of Action class the business logic is executed ?
In the execute() method of Action class the business logic is executed.

public ActionForward execute( 
	    ActionMapping mapping,
             ActionForm form,
             HttpServletRequest request,
             HttpServletResponse response)
          throws Exception ;

execute() method of Action class:
  • Perform the processing required to deal with this request
  • Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
  • Return an appropriate ActionForward object


6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

7.What is role of ActionServlet?
ActionServlet performs the role of Controller:
  • Process user requests
  • Determine what the user is trying to achieve according to the request
  • Pull data from the model (if necessary) to be given to the appropriate view,
  • Select the proper view to respond to the user
  • Delegates most of this grunt work to Action classes
  • Is responsible for initialization and clean-up of resources

9. What are the various Struts tag libraries?
The various Struts tag libraries are:
a. Bean tag library – to access JavaBeans and their properties.
b. HTML tag library - to give standard HTML output, like forms, text boxes, etc.
c. Logic tag library – in order to generate conditional output, iteration capabilities and flow management.
d. Tiles or Template tag library - for those application using tiles.
e. Nested tag library – in order to use the nested beans in the application.

10. How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
a. Programmatic exception handling: It is the explicit try/catch blocks in the code that can throw exception. It works well when any error occurs in the custom value
b. Declarative exception handling: In this we either define <global-exceptions> handling tags in the struts-config.xml or exception handling tags within <action></action> tag. It works well when error occurs in custom page and applies only to exceptions thrown by Actions.

11. What are the contents of web.xml and struts-config.xml? Explain the difference between them.
The web.xml file contains the information used by servlets and JSPs, having the description of the application, mapping information about servlets and URL, JSP configuration information, error page information without the exceptions.
The struts-config.xml file contains information about struts framework at the time of deploying the web application. It includes information about form bean, action mappings, controller information containing the buffer size, content type, etc.

12. What is SwitchAction & ForwardAction in struts?
A SwitchAction switches between modules and forwards the control to the URL specified in the new module. There are two parameters namely page, to which control is forwarded after switching and prefix that specifies the module to which the control is switched.
A ForwardAction is used to forward a request to the specified URL, represented as a destination to the controller to which it is sent after the action is completed.

13. What is Struts Flow?
Struts Flow is a port of Cocoon's Control Flow to Struts in order to allow complex workflow, like multi-form wizards, which is easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of web pages that have to be sent to the client, at any given point of time in an application.


8.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().

14. Why is ActionForm a base class rather than an interface?
Making ActionForm a class gives advantage of the single inheritance restriction of Java in order to make difficult for people to do things that they are not supposed to.
However, if ActionForm is implemented as interface encourages matching of property types to the underlying business tier, violating one of the important purpose of ActionForm and also encourages using of existing DAO objects which violates MVC design pattern. 

10.Describe validate() and reset() methods ?

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.



public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)


reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

public void reset() {}

Tuesday, September 27, 2011

Captcha Image Work in Struts -- Java Code



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Captcha extends Action {

private static final long serialVersionUID = 1L;

private Random generator = new Random();
private final static String SIMPLE_CAPCHA_SESSION_KEY = "SIMPLE_CAPCHA_SESSION_KEY";


private static char[] captchars =
new char[] {
'A',
'B',
'C',
'D',
'E',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'G',
'F',
'H',
'Q',
'R',
'Y',
'N',
'M',
'P',
'U',
'V',
'Z',
'W',
'X'
};

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
HttpServletResponse resp) throws IOException, ServletException{

//System.out.println("Inside Captcha");

//ActionForward actionForward;
//HttpSession session = request.getSession();

//=========================================================================================
int ImageWidth = 200;
int ImageHeight = 70;

int car = captchars.length - 1;

String test = "";
for (int i = 0; i < 6; i++) {
test += captchars[generator.nextInt(car) + 1];
}
// this key can be read from any controller to check whether user
// is a computer or human..

req.getSession().setAttribute(Captcha.SIMPLE_CAPCHA_SESSION_KEY, test);

req.setAttribute("test", test);

//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + test);
//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + req.getAttribute("test"));
//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + req.getSession().getAttribute(Captcha.SIMPLE_CAPCHA_SESSION_KEY));
BufferedImage bi =
new BufferedImage(
ImageWidth + 10,
ImageHeight,
BufferedImage.TYPE_BYTE_INDEXED);

Graphics2D graphics = bi.createGraphics();
graphics.setBackground(Color.white);
graphics.setColor(Color.white);

graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());

//graphics.drawLine( 0, generator.nextInt(ImageHeight)+1, ImageWidth, generator.nextInt(ImageHeight)+1);

graphics.setColor(Color.black);
//AttributedString attstr = new AttributedString(test);

//graphics.drawString(attstr.getIterator(), 0, 50);

//Font font = new Font()

TextLayout textTl =
new TextLayout(
test,
new Font("Courier", Font.BOLD, 40),
new FontRenderContext(null, true, false));
//AffineTransform textAt = graphics.getTransform();

textTl.draw(graphics, 50, 50);
int w = bi.getWidth();
int h = bi.getHeight();
shear(graphics, w, h, Color.black);
this.drawThickLine(
graphics,
50,
generator.nextInt(ImageHeight) + 1,
ImageWidth,
generator.nextInt(ImageHeight) + 1,
4,
Color.getColor("#FFFFFF"));
resp.setContentType("image/jpg");

try {
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(resp.getOutputStream());
//System.out.println("------------->"+ encoder);
encoder.encode(bi);
} catch (IllegalArgumentException e) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
e.printStackTrace();
return null;
}
//=========================================================================================



return null;
}

private void shear(Graphics g, int w1, int h1, Color color) {

shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}

public void shearX(Graphics g, int w1, int h1, Color color) {

int period = generator.nextInt(10) + 5;

boolean borderGap = true;
int frames = 15;
int phase = generator.nextInt(5) + 2;

for (int i = 0; i < h1; i++) {
double d =
(double) (period >> 1)
* Math.sin(
(double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}

}

public void shearY(Graphics g, int w1, int h1, Color color) {

int period = generator.nextInt(30) + 10; // 50;

boolean borderGap = true;
int frames = 15;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d =
(double) (period >> 1)
* Math.sin(
(double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}

}

}

private void drawThickLine(
Graphics g,
int x1,
int y1,
int x2,
int y2,
int thickness,
Color c) {


// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);

double scale = (double) (thickness) / (2 * lineLength);

// The x and y increments from an endpoint needed to create a rectangle...
double ddx = -scale * (double) dY;
double ddy = scale * (double) dX;
ddx += (ddx > 0) ? 0.5 : -0.5;
ddy += (ddy > 0) ? 0.5 : -0.5;
int dx = (int) ddx;
int dy = (int) ddy;

// Now we can compute the corner points...
int xPoints[] = new int[4];
int yPoints[] = new int[4];

xPoints[0] = x1 + dx;
yPoints[0] = y1 + dy;
xPoints[1] = x1 - dx;
yPoints[1] = y1 - dy;
xPoints[2] = x2 - dx;
yPoints[2] = y2 - dy;
xPoints[3] = x2 + dx;
yPoints[3] = y2 + dy;

g.fillPolygon(xPoints, yPoints, 4);
}


}

Captcha Image Creation in struts - Java code


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Captcha extends Action {

private static final long serialVersionUID = 1L;

private Random generator = new Random();
private final static String SIMPLE_CAPCHA_SESSION_KEY = "SIMPLE_CAPCHA_SESSION_KEY";


private static char[] captchars =
new char[] {
'A',
'B',
'C',
'D',
'E',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'G',
'F',
'H',
'Q',
'R',
'Y',
'N',
'M',
'P',
'U',
'V',
'Z',
'W',
'X'
};

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
HttpServletResponse resp) throws IOException, ServletException{

//System.out.println("Inside Captcha");

//ActionForward actionForward;
//HttpSession session = request.getSession();

//=========================================================================================
int ImageWidth = 200;
int ImageHeight = 70;

int car = captchars.length - 1;

String test = "";
for (int i = 0; i < 6; i++) {
test += captchars[generator.nextInt(car) + 1];
}
// this key can be read from any controller to check whether user
// is a computer or human..

req.getSession().setAttribute(Captcha.SIMPLE_CAPCHA_SESSION_KEY, test);

req.setAttribute("test", test);

//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + test);
//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + req.getAttribute("test"));
//System.out.println("++++++++++++++++++++++++++++++++++++++++++= " + req.getSession().getAttribute(Captcha.SIMPLE_CAPCHA_SESSION_KEY));
BufferedImage bi =
new BufferedImage(
ImageWidth + 10,
ImageHeight,
BufferedImage.TYPE_BYTE_INDEXED);

Graphics2D graphics = bi.createGraphics();
graphics.setBackground(Color.white);
graphics.setColor(Color.white);

graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());

//graphics.drawLine( 0, generator.nextInt(ImageHeight)+1, ImageWidth, generator.nextInt(ImageHeight)+1);

graphics.setColor(Color.black);
//AttributedString attstr = new AttributedString(test);

//graphics.drawString(attstr.getIterator(), 0, 50);

//Font font = new Font()

TextLayout textTl =
new TextLayout(
test,
new Font("Courier", Font.BOLD, 40),
new FontRenderContext(null, true, false));
//AffineTransform textAt = graphics.getTransform();

textTl.draw(graphics, 50, 50);
int w = bi.getWidth();
int h = bi.getHeight();
shear(graphics, w, h, Color.black);
this.drawThickLine(
graphics,
50,
generator.nextInt(ImageHeight) + 1,
ImageWidth,
generator.nextInt(ImageHeight) + 1,
4,
Color.getColor("#FFFFFF"));
resp.setContentType("image/jpg");

try {
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(resp.getOutputStream());
//System.out.println("------------->"+ encoder);
encoder.encode(bi);
} catch (IllegalArgumentException e) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
e.printStackTrace();
return null;
}
//=========================================================================================



return null;
}

private void shear(Graphics g, int w1, int h1, Color color) {

shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}

public void shearX(Graphics g, int w1, int h1, Color color) {

int period = generator.nextInt(10) + 5;

boolean borderGap = true;
int frames = 15;
int phase = generator.nextInt(5) + 2;

for (int i = 0; i < h1; i++) {
double d =
(double) (period >> 1)
* Math.sin(
(double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}

}

public void shearY(Graphics g, int w1, int h1, Color color) {

int period = generator.nextInt(30) + 10; // 50;

boolean borderGap = true;
int frames = 15;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d =
(double) (period >> 1)
* Math.sin(
(double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}

}

}

private void drawThickLine(
Graphics g,
int x1,
int y1,
int x2,
int y2,
int thickness,
Color c) {


// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);

double scale = (double) (thickness) / (2 * lineLength);

// The x and y increments from an endpoint needed to create a rectangle...
double ddx = -scale * (double) dY;
double ddy = scale * (double) dX;
ddx += (ddx > 0) ? 0.5 : -0.5;
ddy += (ddy > 0) ? 0.5 : -0.5;
int dx = (int) ddx;
int dy = (int) ddy;

// Now we can compute the corner points...
int xPoints[] = new int[4];
int yPoints[] = new int[4];

xPoints[0] = x1 + dx;
yPoints[0] = y1 + dy;
xPoints[1] = x1 - dx;
yPoints[1] = y1 - dy;
xPoints[2] = x2 - dx;
yPoints[2] = y2 - dy;
xPoints[3] = x2 + dx;
yPoints[3] = y2 + dy;

g.fillPolygon(xPoints, yPoints, 4);
}


}