Tuesday, January 24, 2012

Integration of simple Captcha 1.1.1

Integration of simple Captcha 1.1.1
===================================

Step 1:
========

in jsp where you required, Copy the below table .

Note
====
1)You should have all the format tag keys in your message properties
2)modify the src tag as required
3)make sure that reloadCaptcha , images are available to the page.


       
        <table align="center" width="98%" border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td colspan="2" style="font-size: 11px;font-weight: bold"><fmt:message key="captcha.label.captchaInfo"/></td>
            </tr>
            <tr><td class="ClsLabel" width="35%"><fmt:message key="captcha.label.picture" />:</td><td>
            <iframe id="iframeCaptch" zindex="999" frameborder="0"  vspace="0"  hspace="0" marginwidth="0" marginheight="0"  width="260px"  scrolling="no"  height="50px" src="<c:out value="${contextRoot}"/>/captcha/getSimpleCaptchaImage.do"></iframe>
            <img src="<c:out value="${contextRoot}"/>/images/refresh_icon.gif" title="Click here to refresh the image(picture)" onclick="javascript:reloadCapctha()">
            </td></tr>
            <tr><td>&nbsp;</td><td><fmt:message key="captcha.label.characters"/></td></tr>
            <tr><td class="ClsLabel"><span class="ClsRequiredFields">*</span><fmt:message key="captcha.label.typeCharacters"/>:</td><td><input type="text" maxlength="8" name="txtCaptchaAnswer" id="txtCaptchaAnswer" value="" style="width:250px" class="validate[required,minSize[8]]"></td></tr>
        </table>

Step 2
======

copy the below function, such that it is available to the JSP page.

function reloadCapctha() {
        document.getElementById('iframeCaptch').src="<c:out value="${contextRoot}"/>/captcha/getSimpleCaptchaImage.do";
    }
   
step 3
=======

Captcha Controller
===================
package com.jlr.onlinereservation.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.gimpy.DropShadowGimpyRenderer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Controller
public class CaptchaController
{
    private static Log log = LogFactory.getLog(CaptchaController.class);

   @RequestMapping("/captcha/getSimpleCaptchaImage.do")
    public void getSimpleCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    if (log.isDebugEnabled())
    {
        log.debug("Invoking getSimpleCaptchaImage");
    }
    try
    {
        Captcha captcha = new Captcha.Builder(250, 50).addText(new DefaultTextProducer(8), new DefaultWordRenderer()).addBackground(new GradiatedBackgroundProducer())
            .gimp(new DropShadowGimpyRenderer()).addNoise().addBorder().build();
        CaptchaServletUtil.writeImage(response, captcha.getImage());
        request.getSession().setAttribute(Captcha.NAME, captcha);
    } catch (Exception ex)
    {
        log.error("Error getSimpleCaptchaImage" + ex.getMessage());
    }
    }


    public static boolean validateCaptcha( HttpServletRequest request ) {
        Captcha captcha = (Captcha) request.getSession().getAttribute( Captcha.NAME );
        String answer = request.getParameter( "txtCaptchaAnswer" );
        if( captcha.isCorrect( answer ) ) {
            return true;
        }
        return false;
    }
}


Step 4
======

Use the Static method validateCaptcha(request).

the method output will be a boolean value , if the entered letters matched, it will return true and page will be saved
else you can handle as required.

sample code
============

 if (CaptchaController.validateCaptcha(request))
        {
       
        // save logic
         }
         else
       
         {
          request.setAttribute("message", "The text you entered for the verfication text box(CAPTCHA) was not correct.");

         }
   
    Note if you are using  simle Cattcha 1.2.1
   
    the for the above code to work in getSimpleCaptchaImage method , the below changes required
   
    // code for 1.1.1
    Captcha captcha = new Captcha.Builder(250, 50).addText(new DefaultTextProducer(8),
    new DefaultWordRenderer()).addBackground(new GradiatedBackgroundProducer())
   
    // code for 1.2.1
   
    private static final char[] DEFAULT_CHARS = new char[] { 'a', 'b',
                    'c', 'd', 'e', 'f', 'g', 'h', 'k', 'm', 'n', 'p', 'r', 'w',
                    'x', 'y', '2', '3', '4', '5', '6', '7', '8', };
                   
    Captcha captcha = new Captcha.Builder(250, 50).addText(new DefaultTextProducer(8,DEFAULT_CHARS),
    new DefaultWordRenderer()).addBackground(new GradiatedBackgroundProducer());
   
   
    you can download jars from the below links
    =============================================
   
    http://sourceforge.net/projects/simplecaptcha/files/
   
    note: download files for JDK 1.5
   
   
   
   

Thursday, January 12, 2012

MySQL: MYISAM vs INNODB


MYISAM: 
does not support transactions rollback and row level locking. 

INNODB: 
supports above features as well as ACID (Atomicity, consistency, isolation, and durability).

To convert from MyISAM to InnoDB use script:


SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
ALTER TABLE table_name1 TYPE = innodb;
ALTER TABLE table_name2 TYPE = innodb;
SET FOREIGN_KEY_CHECKS = 1;

MYSQL: Restoring DB from .sql backup

To restore a mysql database:
mysql -u my_user_name -p db_name < my_sql_file.sql

MySQL Database backup (mysqldump) from command line

As the database grows in size the convenient GUI tools became too slow, at some point it is easier to log in to the database server and do it from the command line...

mysqldump --user MY_USER_NAME -p DB_NAME> /var/www/UNIQUE_NAME_AND_DATE.sql
Enter password: MY_PASSWORD

// To compress on Linux
#compress, you can also use gzip
tar cvzf UNIQUE_NAME_AND_DATE.sql.tar UNIQUE_NAME_AND_DATE.sql

# delete sql
rm /var/www/UNIQUE_NAME_AND_DATE.sql

#download:
http://www.DOMAIN_NAME.com/UNIQUE_NAME_AND_DATE.sql.tar

# after transfer delete
rm /var/www/UNIQUE_NAME_AND_DATE.sql.tar

Detached Criteria with join


public List fetchYesterdayGames()
{
DetachedCriteria dc = DetachedCriteria.forClass(TeamGame.class);
dc.setFetchMode("game", FetchMode.JOIN);
DetachedCriteria dcGame = dc.createCriteria("game");
dcGame.add(Expression.lt("startDate", new Date()));
dc.add(Expression.isNull("headline"));
List teamGames = getHibernateTemplate().findByCriteria(dc);
return teamGames;
}

Hibernate Detached criteria with projections (GROUP BY)

Examples of Spring/Hibernate compare, group by, order by (sort) functionality:
    public List fetchDetailMetrics(Date dateFrom, Date dateTo, String navPage, String navOption, OrganizationDTO org)
    {
List pageViews = new ArrayList();
log.warn("Date from " + dateFrom + " to " + dateTo);
DetachedCriteria metrics = DetachedCriteria.forClass(MetricsForUserSession.class);
metrics.add(Expression.between("dateTime", dateFrom, dateTo));
metrics.add(Expression.eq("navOption", navOption));
metrics.add(Expression.eq("navPage", navPage));
if (org != null)
{
    log.warn(" org " + org.getName());
    metrics.add(Expression.eq("organization.id", org.getId()));
}
ProjectionList projectList = Projections.projectionList();
// group by
projectList.add(Projections.groupProperty("entityId"));
// alias of the column head
projectList.add(Projections.alias(Projections.rowCount(), "count"));
metrics.setProjection(projectList);
// order by, sorting
metrics.addOrder(Order.desc("count"));

List results = getHibernateTemplate().findByCriteria(metrics);
if (results == null || results.size() <>
    log.warn("fetched nothing");
else
    log.warn("fetched " + results.size());
log.warn("fetched navPages " + results.size());
for (Object[] column : results)
{
    log.warn(column[0] + " " + column[1]);
    PageView pageView = new PageView();
    determineDescription(pageView, column, navPage);
    pageView.setViewCount(new Integer(column[1].toString()));
    pageViews.add(pageView);
}
return pageViews;
    }

Limit resultset in Hibernate

To limit the number of records/results returned by the search criteria(notice we are not using DetachedCriteria): 

Criteria criteria = getSession().createCriteria(MyClass.class);
criteria.setMaxResults(100);
List< MyClass > list = criteria.list();
if (list != null && list.size() > 0)
{
    log.warn("Found " + list.size() + " Impressions");
}
return list;

Using TINY_INT for Java Boolean types with Hibernate

THE PROBLEM: By default Hibernate persists properties that are of Java Boolean or boolean type as CHAR type with values 0 and 1 in our MySQL database. This is efficient, but when we want to look at the database using our GUI tools, these values both display as the same meaningless box character. This is because the ASCII values 0 and 1, both represent non-printable characters.

THE SOLUTION: If we force Hibernate to make these columns TINY_INT type, our tools will display the values correctly as “0” and “1”. Hibernate allows us to do this by creating a custom type and assigning it to all of our boolean properties. Here’s how:
1. Create a custom Hibernate type. We extend Hibernate’s abstract BooleanType and override a few methods to customize it for our needs.
OneZeroBoolean.java
package com.example.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.dialect.Dialect;
import org.hibernate.type.BooleanType;

public class OneZeroBoolean extends BooleanType
{
private static final long serialVersionUID = 1L;

public Object get(ResultSet rs, String name) throws SQLException
{
if (rs.getObject(name) == null)
return null;
int code = rs.getInt(name);
return code != 0;
}

public void set(PreparedStatement st, Object value, int index) throws SQLException
{
if (value == null)
st.setObject(index, null);
else
st.setInt(index, Boolean.TRUE.equals(value) ? 1 : 0);
}

public int sqlType()
{
return Types.TINYINT;
}

public String objectToSQLString(Object value, Dialect dialect) throws Exception
{
return ((Boolean)value).booleanValue() ? "1" : "0";
}

public Object stringToObject(String xml) throws Exception
{
if ("0".equals(xml))
{
return Boolean.FALSE;
} else
{
return Boolean.TRUE;
}
}
}
2. Register this new type with Hibernate. We are using annotations for our hibernate configuration, so this is done in the package-info.java file in the package where our entity classes are defined. Here register our new type under the name “onezero-boolean”. You can use any name you like (unless it’s already used by hibernate). We will reference this name later when we declare the boolean properties themselves.
package-info.java
@TypeDefs( { @TypeDef(name = "onezero-boolean", typeClass = OneZeroBoolean.class) })
package com.example.model;

import org.hibernate.annotations.TypeDefs;
import org.hibernate.annotations.TypeDef;
NOTE: In order to use these package-level annotations we need to tell the Hibernate configuration to look for them. Your configuration may be in hibernate.cfg.xml or you may be doing it in Spring. Here are examples from both…
Hibernate.cfg.xml: Add a mapping within <session-factory> telling hibernate to look for package-level annotations in the specified package.
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
...
<mapping package="com.example.model" />
...
Spring: Spring provides some helpers to configure a hibernate session factory as an alternative to specifying everything in hibernate.cfg.xml. In Spring 2.0 it’s the org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean class. Here is a snippet of the configuration including the extra piece needed for package annotations:
applicationContext.xml
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<!-- This property tells it to look at our package-level annotations -->
<property name="annotatedPackages">
<list>
<value>com.example.model</value>
</list>
</property>
<property name="annotatedClasses">
<list>
<value>com.example.model.Entity1</value>
<value>com.example.model.Entity2</value>
...
</list>
</property>
</bean>
3. Where ever boolean or Boolean type properties are declared in the entity classes, tell hibernate to use our new custom type. This is done with the hibernate @Type annotation; just specify the name that we used to register our custom type above.
Entity1.java
package com.example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.Type;

@Entity
public class Entity1
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@Type(type="onezero-boolean")
private boolean active;

//Getters and Setters
...
}
That’s all there is to it. This same type can be applied to any and/or all boolean properties in our entities. Hibernate schema generation will generate TINY_INT columns for us and hibernate persistence will store boolean values as 1(true) and 0(false) in those columns.

Case insensitive query in hibernate

We ran into a situation where we needed to match a string from our application to a string in the database. A very common task. But this time we needed it to be a case insensitive match. In order to do that using Hibernate annotations, we ended up using Restrictions.ilike().

Here is some example code:

public List fetchByCountry(String country)
{
DetachedCriteria criteria = DetachedCriteria.forClass(MobileCarrier.class);
criteria.add(Restrictions.ilike("country", country, MatchMode.EXACT));
return getHibernateTemplate().findByCriteria(criteria);
}

The ilike method is a case insensitive like statement, and when combined with a MatchMode.EXACT, it accomplishes the task of an exact string case insensitive match

How to fetch total record count using Hibernate Criteria


Criteria criteria = getSession().createCriteria(getReferenceClass());

criteria.setProjection(Projections.projectionList().add(Projections.countDistinct("id"))

Oracle database and schema creation

Oracle Installation and Configuration:

The Oracle 10g CD contains folder: Oracle 10g
Under that there are 2 folders:
  1. Oracle 10g Client
  2. Oracle 10g Server
First install Oracle Server. Go into Oracle 10g\Oracle 10g Server\10g_win32_db\Disk1
Click on Setup.exe

Remember to choose the installation in a drive that has disk space say C Drive.
Default installation does not allow you to change the location.
Advance installation allows you to change the location.

Next install Oracle Client. It is under: Oracle 10g\Oracle 10g Client

There are 2 versions and we want to install the latest version. The latest version is under: Oracle 10g\Oracle 10g Client\10201_client_win32

Go into: Oracle 10g\Oracle 10g Client\10201_client_win32\client and click Setup.exe

Choose the Administrator radio button for installation of the Administrator components can continue.




Next you have to create a Database Instance
Name it: <INSTANCE NAME>
For all the sys/system etc passwords give: <password>

Choose the following program from Start Menu to create a Database Instance:


 





















THIS IS THE IMPORTANT SCREEN



Then continue further as usual and create the database.Under this instance <INSTANCE> create different schemas for different projects


Schema creation should be preceded by User creation using Enterprise Management Console:



Once you start the Enterprise Management Console, a command window starts. Do not close it.






Add your Instance to the Tree.Login into it as user sys with sysdba and password as <PASSWORD>.

To Create user go as specified below, right click and create the user. The Role and System tab should be set with the proper privileges for the user









Note: BE SURE TO GET THE Tick Mark in blue before saving it