Monday, October 22, 2012

Encrypt


import java.security.InvalidKeyException;
import java.security.Key;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;

public class EncryptDemo {
 static String algorithm = "DESede";

 static Key key;
 static Cipher cipher;

 public static void main(String[] args) throws Exception {

key= KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
   byte[] encryptionBytes = encrypt("Om Prakash");
   System.out.println(encryptionBytes);

   System.out.println("Recovered: " + decrypt(encryptionBytes));
 }

 private static byte[] encrypt(String input) throws InvalidKeyException, BadPaddingException,
     IllegalBlockSizeException {
   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] inputBytes = input.getBytes();
   return cipher.doFinal(inputBytes);
 }

 private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException,
     BadPaddingException, IllegalBlockSizeException {
   cipher.init(Cipher.DECRYPT_MODE, key);
   byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
   String recovered = new String(recoveredBytes);
   return recovered;
 }
}

Monday, October 8, 2012


hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql:///omdata</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">root</property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <!-- Mapping files -->
      <mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="pack.Employee" table="EMP">
  <id name="eid" type="long" column="EID"  >
  <generator class="assigned"/>
 </id>

 <property name="ename">
<column name="EMPNAME" />
 </property>
    </class>
</hibernate-mapping>

Employee.java
package pack;
public class Employee {
private String ename;
private long eid;

public void setEid(long l) {
eid = l;
}
public long getEid() {
return eid;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getEname() {
return ename;
}
}


Main.java
package pack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Transaction;
 public class Main {
public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transaction = null;
transaction = session.beginTransaction();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Employee e = new Employee();
e.setEid(3);
e.setEname("Prakash om");
session.save(e);
transaction.commit();
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
//session.flush();
//session.close();

} }}
InputForm.java
package pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InputForm extends JFrame implements ActionListener
{
JTextField tId=new JTextField();
JTextField tName=new JTextField();
JLabel lbl=new JLabel();
JButton btn=new JButton("Save");

InputForm()
{

JPanel p1=new JPanel();
setLayout(null);
p1.setLayout(new GridLayout(4,1));
getContentPane().add(p1);
p1.setBounds(50,50,200,150);

p1.add(tId);
p1.add(tName);
p1.add(btn);
p1.add(lbl);
setSize(300,300);
setVisible(true);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent ev)
{
String ename=tName.getText();
int eid=0;
try{
eid=Integer.parseInt(tId.getText());

SaveInputForm sif=new SaveInputForm(eid,ename);
lbl.setText(sif.status);
}
catch(Exception e)
{
System.out.println(e.getMessage());
lbl.setText(e.getMessage());
}


}

public static void main(String arg[])
{
new InputForm();
}
}
SaveInputForm.java
package pack;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Transaction;
public class SaveInputForm {
String status;
SaveInputForm(int eid,String ename)
{
Session session = null;
try{

// This step will read hibernate.cfg.xml and prepare hibernate for use
@SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transaction = null;
transaction = session.beginTransaction();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Employee e = new Employee();
e.setEid(eid);
e.setEname(ename);
session.save(e);
transaction.commit();
System.out.println("Done");
status="Success";
}catch(Exception e){
System.out.println(e.getMessage());
status=e.getMessage();
}finally{
// Actual contact insertion will happen at this step
//session.flush();
//session.close();

}

}

}

Sunday, September 16, 2012

Automatic Validation in Struts


order-form.jsp

<HTML>
<HEAD><TITLE>Order</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6"><CENTER>
<%@ taglib uri="http://struts.apache.org/tags-html"  prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean"  prefix="bean" %>

<html:errors/>
<html:form action="order"
           onsubmit="return validateOrderFormBean(this);">
  <bean:message key="inputForm.firstName" />
<html:text property="firstName"/><BR>
  <html:submit value="Order Now!"/>
</html:form>
<html:javascript formName="orderFormBean"/>
</CENTER></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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>DemoStruts</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>
        <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
      </welcome-file-list>
</web-app>

struts-config.xml

<struts-config>
 
  <form-beans>
  
    <form-bean name="orderFormBean"
               type="omservlet.OrderFormBean"/>
  </form-beans>
  <action-mappings>
      <action path="/order"
            type="omservlet.Order"
            name="orderFormBean"
            scope="request"
            input="/order-form.jsp">
      <forward name="success"
               path="/WEB-INF/results/order-confirmation.jsp"/>
    </action>
  </action-mappings>
   <message-resources parameter="MessageResources"/>

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

MessageResources.properties
# -- Custom messages for this application --
inputForm.firstName=First name
# -- Standard errors --
errors.header=<UL>
errors.prefix=<LI><B><FONT COLOR="RED">
errors.suffix=</FONT></B></LI>
errors.footer=</UL>
# -- validator --
errors.required={0} is required.
validator-rules.xml
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>

   <global>

      <validator name="required"
            classname="org.apache.struts.validator.FieldChecks"
               method="validateRequired"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       javax.servlet.http.HttpServletRequest"
                  msg="errors.required"/>
   </global>

</form-validation>

Validation.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
  <formset>
    <form name="orderFormBean">
      <field property="firstName"
             depends="required">
        <arg0 key="inputForm.firstName"/>
      </field>
    </form>  </formset> </form-validation>

OrderFormBean.java
package omservlet;
import org.apache.struts.validator.*;

public class OrderFormBean extends ValidatorForm {

// setter and getter methods.

}
Order.java
package omservlet;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class Order extends Action {
 public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
      throws Exception {
    return(mapping.findForward("success"));
  }
}

order-confirmation.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Thanks for Ordering</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>Thanks for Ordering</H1>
</CENTER>
</BODY></HTML>

Monday, July 23, 2012

1.3. Basic Struts Example



WEB-INF\results\

bad-address.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Illegal Email Address</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>invalid Email Address</H1>
Please <A HREF="index.jsp">try again</A>.
</CENTER>
</BODY></HTML>

bad-password.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>invalid password</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>invalid password</H1>
Please <A HREF="index.jsp">try again</A>.
</CENTER>
</BODY></HTML>

confirm.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<HTML>
<HEAD><TITLE>Success</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>You are login successfully.</H1>
<bean:write name="userFormBean" property="name" />
Congratulations.
</CENTER>
</BODY></HTML>

1.2 Basic Struts Example


RegisterAction1.java

package coreservlets;
import javax.servlet.http.*;


import org.apache.struts.action.*;


public class RegisterAction1 extends Action {
  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
      throws Exception {
UserFormBean userBean = (UserFormBean)form;
    String email = userBean.getEmail();
    String password = userBean.getPassword();
if(email.equals("om@gmail.com"))
{
if(password.equals("om"))
return(mapping.findForward("success"));
else
return(mapping.findForward("bad-password"));
}
 else
     return(mapping.findForward("bad-address"));
  }
}

1.1. Basic Struts Example...


UserFormBean.java

package coreservlets;
import java.sql.*;
import org.apache.struts.action.*;


public class UserFormBean extends ActionForm {
  private String email = "Missing address";
  private String password = "Missing password";
  public String getEmail() {
    return(email);
  }


  public String getName()
  {
Connection con=null;
String name="not defined";
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql:///omdatabase","root","root");
Statement stat=con.createStatement();
ResultSet rs=stat.executeQuery("Select * from Student");
while(rs.next())
{
name=rs.getString(1);
}
}
catch(Exception ex)
{
name=""+ex;
}
return name;
  }
  public void setEmail(String email) {
    this.email = email;
  }


  public String getPassword() {
    return(password);
  }


  public void setPassword(String password) {
    this.password = password;
  }
}

1.0.Basic Struts Example


index.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>New Account Registration</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>New Account Registration</H1>
<FORM ACTION="register1.do" METHOD="POST">
  Email address: <INPUT TYPE="TEXT" NAME="email"><BR>
  Password: <INPUT TYPE="PASSWORD" NAME="password"><BR>
  <INPUT TYPE="SUBMIT" VALUE="Sign in me!">
</FORM>
</CENTER>
</BODY></HTML>


\WEB-INF

web.xml


<web-app>
  <!-- Standard Action Servlet Configuration  -->
  <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>
  </servlet>
  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

struts-config.xml

<struts-config>
  <form-beans>
    <form-bean name="userFormBean"
               type="coreservlets.UserFormBean"/>
  </form-beans>
      <global-forwards>
    <forward name="success" 
             path="/WEB-INF/results/confirm.jsp"/>
  </global-forwards>
    <action-mappings>
    <action path="/register1" 
            type="coreservlets.RegisterAction1"
name="userFormBean"
            scope="request">
<forward name="bad-password" 
               path="/WEB-INF/results/bad-password.jsp"/>
<forward name="bad-address" 
               path="/WEB-INF/results/bad-address.jsp"/>
    </action>
  </action-mappings>
</struts-config>

Note- struts.jar must be in /WEB-INF/lib