Search This Blog

Thursday, June 3, 2010

Spring

Spring focuses around providing a way to manage your business objects.

Spring is an application framework in which spring MVC is
one of the modules of spring framework. Spring uses the
concept of IOC/DI where the objects are not hard coded in
java but they are injected using construtor/setter
injection.

Spring is an ideal framework for test driven projects

Applications built using Spring are very easy to unit tes

Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code

Spring provides a consistent framework for data access

this consistency in the Spring approach to JDBC, JMS, JavaMail, JNDI and many other important APIs.

Spring's main aim is to make J2EE easier to use and promote good programming practice

no logging packages in Spring, no connection pools, no distributed transaction coordinator

Spring container manages relationships between objects

Dependency Injection is a form of IoC that removes explicit dependence on container API, two major flavors of Dependency Injection are Setter Injection (injection via JavaBean setters); and Constructor Injection (injection via constructor arguments)

highly configurable MVC web framework

Spring's MVC model is most similar to that of Struts, although it is not derived from Struts

Spring Controller is similar to a Struts Action in that it is a multithreaded service object


Spring provides a very clean division between controllers, JavaBean models, and views

Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies

custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it


Steps:-
++++++++

1. Open MyEclipse Editor [or] any editor
2. Create a new Project [java project]
3. Add neccessary Jar Files in lib [ spring, hibernate core 3.1, jre 1.5+ ]
4. Create your DB
5. Create spring-hibernate.xml
6. Create xxxFormBean.hbm.xml
7. Write a xxxFormBean.java
8. Write a DAO
9. Write a program to call


Sample DB Create [MYSQL]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

create database springdb;
use springdb;

create table employee ( id int(10) unsigned NOT NULL auto_increment primary key, name varchar(20), age int(3), salary numeric(10,2));

insert into `employee`(`id`,`name`,`age`,`salary`) values ( NULL,'vijay','25','10000');
insert into `employee`(`id`,`name`,`age`,`salary`) values ( NULL,'kumar','20','5000');


spring-hibernate.xml  [save inside src folder]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="myDataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springdb" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="mappingResources">
            <list>
                <value>./Employee.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            </value>
        </property>
    </bean>

    <bean id="hibernateTemplate"
        class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory">
            <ref bean="mySessionFactory" />
        </property>
    </bean>

    <bean id="employeeDao" class="spring.hibernate.EmployeeDao">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate" />
        </property>
    </bean>


</beans>


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="spring.hibernate.Employee" table="employee" lazy="false">
    <id name="id" column="id">
        <generator class="increment"/>
    </id>

    <property name="name">
        <column name="name"/>
    </property>
    <property name="age">
        <column name="age"/>
    </property>
    <property name="salary">
        <column name="salary"/>
    </property>
</class>
</hibernate-mapping>


Employee.java
~~~~~~~~~~~~~

package spring.hibernate;

public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public int getId(){
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getAge(){
        return age;
    }  

    public void setAge(int age){
        this.age = age;
    }

    public double getSalary(){
        return salary;
    }

    public void setSalary(double salary){
        this.salary = salary;
    }

    public String toString(){
        return "Id = " + id + ", Name = " + name + ", Age = "
            + age + ", Salary = " + salary;
    }
}


EmployeeDao.java
~~~~~~~~~~~~~~~~~~~

package spring.hibernate;

import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import spring.hibernate.Employee;

public class EmployeeDao
{

    private HibernateTemplate    hibernateTemplate;

    public void setHibernateTemplate ( HibernateTemplate hibernateTemplate )
    {
        this.hibernateTemplate = hibernateTemplate;
    }

    public HibernateTemplate getHibernateTemplate ()
    {
        return hibernateTemplate;
    }

    public Employee getEmployee ( final int id )
    {
        HibernateCallback callback = new HibernateCallback () {
            public Object doInHibernate ( Session session ) throws HibernateException, SQLException
            {
                return session.load ( Employee.class, id );
            }
        };
        return (Employee) hibernateTemplate.execute ( callback );
    }

    public void saveOrUpdate ( final Employee employee )
    {
        HibernateCallback callback = new HibernateCallback () {
            public Object doInHibernate ( Session session ) throws HibernateException, SQLException
            {
                session.saveOrUpdate ( employee );
                return null;
            }
        };
        hibernateTemplate.execute ( callback );
    }
}


SpringTest.java
~~~~~~~~~~~~~~~~~

package spring.hibernate;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class SpringTest
{

    public static void main ( String [] args )
    {

        Resource resource = new FileSystemResource ( "bin/spring-hibernate.xml" );
        BeanFactory factory = new XmlBeanFactory ( resource );

        Employee employee = new Employee ();
        employee.setId ( 123 );
        employee.setName ( "ABC" );
        employee.setAge ( 20 );
        employee.setSalary ( 15000.00d );

        EmployeeDao employeeDao = (EmployeeDao) factory.getBean ( "employeeDao" );
        //employeeDao.saveOrUpdate ( employee );

        Employee empResult = employeeDao.getEmployee ( 1 );
        System.out.println ( empResult );
    }
}

drvijayy2k2@gmail.com

Wednesday, June 2, 2010

One line Description on Design Pattern

Design Pattern:

Observer Pattern     : Weather Monitoring application, Meet the Observer Pattern
Decorator Pattern     : Constructing a Drink Order with Decorators
Factory Pattern        : Define interface to create object
Singleton Pattern     : One Instance, global use
Command Pattern     : Order a Command to do specific process
Adapter design pattern     : (often referred to as the wrapper pattern or simply a wrapper)                 translates one interface for a class into a compatible interface
Facade Pattern         : facade is an object that provides a simplified interface to a                 larger body of code, such as a class library
Method Pattern         : Described how the method will works /steps.
Iterator Pattern    : loop...
Composite Pattern    :
State Pattern        : like scope
Proxy Pattern        : ..
Compound Pattern    : Join all or more patterns together, [patterns of patterns]

OWASP Top 10 Secure for web Application

The OWASP Top 10 Web Application Security Risks:
  • A1: Injection
  • A2: Cross-Site Scripting (XSS)
  • A3: Broken Authentication and Session Management
  • A4: Insecure Direct Object References
  • A5: Cross-Site Request Forgery (CSRF)
  • A6: Security Misconfiguration
  • A7: Insecure Cryptographic Storage
  • A8: Failure to Restrict URL Access
  • A9: Insufficient Transport Layer Protection
  • A10: Unvalidated Redirects and Forwards

Disable Browser Cache

Every time you use your web browser, your computer collects information about how you use it as well as generating local copies of files and documents you have viewed. This information is stored in folders on your hard drive and can be accessed by navigating to that folder or using a viewing utility within the web browser itself. Items that are stored include the cookies that the site you visit creates to store your preferences or

login information

, image files, html pages, PDF documents and even video files. In short, anything that you can access through the internet.

Advantages:-
~~~~~~~~~~~~~~
*. his automatic caching can be convenient, as it helps increase the speed of the page loading on your next visit

DisAdvantages:-
~~~~~~~~~~~~~~~~
*. it's also a major privacy risk.

Note: You may be visiting sites that you don't want others in your family to visit or maybe you want to ensure important username and password are kept private

Clear Login Credentials and Menu Constructing page based on Permissions etc..

For JSP,JSF:-
Apply this below code in all your view files..


             <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta http-equiv="Cache-control" content="no-cache"/>
            <meta http-equiv="Cache-control" content="no-store"/>          
            <meta http-equiv="Pragma" content="no-cache">
            <meta http-equiv="expires" content="0">

             <%
                        response.setHeader("Cache-Control", "no-cache");
                        response.setHeader("Pragma", "no-cache");
                        response.setDateHeader("Expires", 0);
                        response.setHeader("Cache-Control", "no-store");
            %>

Sanitize HTML

Takes a provided HTML string and removes any potentially dangerous XSS HTML tags using a whitelist approach. Useful when you want to allow a small subset of "safe" HTML tags in user content.

you may write your own code or

you can use OWASP API
http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API

Monday, May 31, 2010

Simple Captcha

SimpleCaptcha
Installing

Installing SimpleCaptcha is no different than installing most other libraries for a J2EE container: a jar is deployed to WEB-INF/lib and web.xml is updated. These steps are described in detail below.

   1. Download SimpleCaptcha
   2. Copy the jar file to your WEB-INF/lib directory
   3. Add a mapping to web.xml. There are three servlets provided out of the box: StickyCaptchaServlet, SimpleCaptchaServlet, and ChineseCaptchaServlet. All generate CAPTCHA image/answer pairs, but StickyCaptchaServlet and ChineseCaptchaServlet are “sticky” to the user’s session: page reloads will render the same CAPTCHA instead of generating a new one. An example mapping for StickyCaptchaServlet:

    <servlet>
        <servlet-name>StickyCaptcha</servlet-name>
        <servlet-class>nl.captcha.servlet.StickyCaptchaServlet</servlet-class>
        <init-param>
            <param-name>width</param-name>
            <param-value>250</param-value>
        </init-param>
        <init-param>
            <param-name>height</param-name>
            <param-value>75</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>StickyCaptcha</servlet-name>
        <url-pattern>/stickyImg</url-pattern>
    </servlet-mapping>

The width and height parameters are optional; if unprovided the image will default to 200×50.

   4. Restart your webserver.
   5. Browse to the location given by the url-pattern defined in web.xml, e.g., http://localhost:8080/stickyImg. If everything has been set up correctly you should see a CAPTCHA image.
   6. Now create a JSP called captcha.jsp. Add the following code inside the <body> element:

          <img src="/stickyImg" />
          <form action="/captchaSubmit.jsp" method="post">
              <input name="answer" />
          </form>

   7. Create another JSP called captchaSubmit.jsp. Add the following:

          <%@ page import="nl.captcha.Captcha" %>
          ...
          <% // We're doing this in a JSP here, but in your own app you'll want to put
          // this logic in your MVC framework of choice.
          Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
          request.setCharacterEncoding("UTF-8"); // Do this so we can capture non-Latin chars
          String answer = request.getParameter("answer");
          if (captcha.isCorrect(answer)) { %>
              <b>Correct!</b>
          <% } %>

   8. Browse to /captcha.jsp. You should get your CAPTCHA image, as well as a form for entering your answer. Submit the form and see what happens.

Clear Broswer Cache for J2ee

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Cache-control" content="no-cache"/>
<meta http-equiv="Cache-control" content="no-store"/>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="expires" content="0">

<%
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store");
%>
</head>

Friday, May 7, 2010

Block Brute Force Attacks

Brute Force Attacks

A common threat web developers face is a password-guessing attack known as a brute force attack. A brute-force attack is an attempt to discover a password by systematically trying every possible combination of letters, numbers, and symbols until you discover the one correct combination that works. If your web site requires user authentication, you are a good target for a brute-force attack.

An attacker can always discover a password through a brute-force attack, but the downside is that it could take years to find it. Depending on the password's length and complexity, there could be trillions of possible combination. To speed things up a bit, a brute-force attack could start with dictionary words or slightly modified dictionary words because most people will use those rather than a completely random password. These attacks are called dictionary attacks or hybrid brute-force attacks. Brute-force attacks put user accounts at risk and flood your site with unnecessary traffic.

Hackers launch brute-force attacks using widely available tools that utilize wordlists and smart rulesets to intelligently and automatically guess user passwords. Although such attacks are easy to detect, they are not so easy to prevent. For example, many HTTP brute-force tools can relay requests through a list of open proxy servers. Since each request appears to come from a different IP address, you cannot block these attacks simply by blocking the IP address. To further complicate things, some tools try a different username and password on each attempt, so you cannot lock out a single account for failed password attempts.

Blocking Mechanism

* For advanced users who want to protect their accounts from attack, give them the option to allow login only from certain IP addresses.
* Assign unique login URLs to blocks of users so that not all users can access the site from the same URL.
* Use a CAPTCHA to prevent automated attacks (see the sidebar "Using CAPTCHAs").
* Instead of completely locking out an account, place it in a lockdown mode with limited capabilities.


Here are conditions that could indicate a brute-force attack or other account abuse:

* Many failed logins from the same IP address
* Logins with multiple usernames from the same IP address
* Logins for a single account coming from many different IP addresses
* Excessive usage and bandwidth consumption from a single use
* Failed login attempts from alphabetically sequential usernames or passwords
* Logins with a referring URL of someone's mail or IRC client
* Referring URLs that contain the username and password in the format http://user:password@www.example.com/login.htm
* If protecting an adult Web site, referring URLs of known password-sharing sites
* Logins with suspicious passwords hackers commonly use, such as ownsyou (ownzyou), washere (wazhere), zealots, hacksyou, and the like (see www.securibox.net/phpBB2/viewtopic.php?t=8563)


Write OWN CAPCHA - Java example


capcha.jsp
*********

<%@ page import="java.io.*"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.awt.image.*"%>
<%@ page import="javax.imageio.ImageIO"%>
<%@ page import="java.util.*"%>
<%
    response.setHeader ( "Cache-Control", "no-cache" );
    response.setHeader ( "Pragma", "no-cache" );
    response.setDateHeader ( "Expires", 0 );
    response.setHeader ( "Cache-Control", "no-store" );
%>

<%
    try
    {
        int width = 75;
        int height = 35;
        Random rdm = new Random ();
        int rl = rdm.nextInt ();

        String hash1 = Integer.toHexString ( rl );
        String capstr = hash1.substring ( 0, 5 );
        session.setAttribute ( "key", capstr );

        Color background = new Color ( 204, 204, 204 );
        Color fbl = new Color ( 0, 100, 0 );
        Font fnt = new Font ( "SansSerif", 1, 17 );

        BufferedImage cpimg = new BufferedImage ( width, height, BufferedImage.TYPE_BYTE_GRAY );
        Graphics g = cpimg.createGraphics ();
        g.setColor ( background );
        g.fillRect ( 0, 0, width, height );
        g.setColor ( fbl );
        g.setFont ( fnt );
        g.drawString ( capstr, 10, 25 );
        g.setColor ( background );
        g.drawLine ( 10, 17, 80, 17 );
        g.drawLine ( 10, 22, 80, 22 );

        response.setContentType ( "image/jpeg" );
        OutputStream strm = response.getOutputStream ();
        ImageIO.write ( cpimg, "jpeg", strm );
        strm.close ();
    }
    catch ( Exception e )
    {
        e.printStackTrace ();
    }
    finally
    {
        //null
    }
%>


in your jsp
*********

<img src="Cap_Img.jsp" style="height:40px;font-weight: bold;" >




checking.java
**********

 HttpSession session = request.getSession();
        String key = (String) session.getAttribute("key");

        //update captch to another one to avoid proxy attack
        Random rdm = new Random();
        int rl = rdm.nextInt();
        String hash1 = Integer.toHexString(rl);
        String capstr = hash1.substring(0, 5);
        session.setAttribute("key", capstr);
        System.out.println("Debug key " + key);
        String JCaptcha = getTf_JCaptcha();
        System.out.println("Debug getTf_JCaptcha " + getTf_JCaptcha());
        if (key.equals(JCaptcha)) {
response.sendRedirect ( "yourjsp.jsp");
}
else {
//your code 
}

Wednesday, February 24, 2010

How to extract SWF Flash animation from Office Excel?

Besides watching Flash videos (FLV files), you should have seen or played some Flash animation game as well (SWF files, a.k.a. Shockwave flash).

And most of the time, you received SWF Flash animation in Microsoft Office document. Very likely, the SWF animation file is embedded in Office Excel.
The reason of embedding SWF animation file in Office document is probably that majority of users is running on Windows / MS Office, and MS Office can serve as a container to run or play the SWF file.

(If you received an un-embedded SWF file, you might able to open and play the SWF animation in web browser that installed with Shockwave Flash add-on)

While the SWF flash appears as an embedded file in Office Excel or Word, you might want to extract or retrieve the embedded SWF flash for your blog.

However, there is no intrinsic or built-in function to extract / retrieve embedded SWF Flash animation from Microsoft Office document files. This is definitely true, that you won’t able to find this wanted feature in Office 2007 as well!

So, how could you do that in case you’re really wanted to do so? OK, here we go:

How to extract SWF Flash animation from Office Excel?

A simple VBA program (a.k.a Visual Basic for Applications) can extract the embedded SWF Flash animation file in less than a minute or so.

The VBA / guide has been tested in Office 2003 Professional, and it should be working perfectly in any Office versions / editions too (e.g. the latest Office 2007), provided the Office system has installed the VBA components.
  1. Open a new Microsoft Excel document,
     
  2. Click the Tools menu, Marco, Visual Basic Editor. You can also press the ALT+ F11 hotkey to bring up the VBA editor,
     
  3. While in MS Visual Basic editor, click the View Code icon on the upper-left panel,
    VBA program to extract or retrieve embedded SWF Flash animation in Excel.
     
  4. Copy the VBA program source code at below here and paste it onto the VBA source code editor,
     
  5. Press F5 to execute the VBA source code,
     
  6. An Open File dialog box prompts you to select the Office Excel document that embed the SWF Flash animation file,
     
  7. A message box appears shortly after the Excel file is selected, with a message that says where the extracted SWF Flash animation file is saved in local hard disk!

The extracted SWF Flash animation file ended with SWF file extension, and it can be open/play in a web browser with Shockwave Flash addon (e.g. Flash9e.ocx in IE7).

The VBA source code used to extract or retrieve SWF Flash animation files that embedded in Microsoft Office Excel or Word:


Sub ExtractFlash()

Dim tmpFileName As String
Dim FileNumber As Integer
Dim myFileId As Long
Dim MyFileLen As Long
Dim myIndex As Long
Dim swfFileLen As Long
Dim i As Long
Dim swfArr() As Byte
Dim myArr() As Byte

tmpFileName = Application.GetOpenFilename("MS Office File (*.doc;*.xls), *.doc;*.xls", , "Open MS Office file")

If tmpFileName = "False" Then Exit Sub

myFileId = FreeFile

Open tmpFileName For Binary As #myFileId

MyFileLen = LOF(myFileId)

ReDim myArr(MyFileLen - 1)

Get myFileId, , myArr()

Close myFileId

Application.ScreenUpdating = False

i = 0

Do While i < MyFileLen

   If myArr(i) = &H46 Then

      If myArr(i + 1) = &H57 And myArr(i + 2) = &H53 Then

         swfFileLen = CLng(&H1000000) * myArr(i + 7) + CLng(&H10000) * myArr(i + 6) + CLng(&H100) * myArr(i + 5) + myArr(i + 4)

         ReDim swfArr(swfFileLen - 1)

         For myIndex = 0 To swfFileLen - 1
            swfArr(myIndex) = myArr(i + myIndex)
            Next myIndex
         Exit Do

      Else
            i = i + 3
      End If

   Else
        i = i + 1
   End If

Loop

myFileId = FreeFile

tmpFileName = Left(tmpFileName, Len(tmpFileName) - 4) & ".swf"

Open tmpFileName For Binary As #myFileId

Put #myFileId, , swfArr

Close myFileId

MsgBox "Save the extracted SWF Flash as [ " & tmpFileName & " ]"

End Sub

Wednesday, February 3, 2010

Invoking Groovy Scripts in JAVA

import java.io.File;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
public class ScriptEngineEmbedGroovy
{
public static void main(String args[]) throws Throwable
{
String[] paths = {"C:\\groovy"};
GroovyScriptEngine gse = new GroovyScriptEngine(paths);
Binding binding = new Binding();
Object[] path = {"C:\\music\\mp3"};
binding.setVariable("args",path);
gse.run("Songs.groovy", binding);
}
}

Hit Counter


View My Stats