Wednesday, June 25, 2008

Spring JDBC - SQL with params

ex: String sql="select distinct PRIMARY_OWNER from "+xyzSchema+"v_rptg rptg"+
" where rptg.fac_id=:facId and " +
" (:cDate >= cit_eff_asof_dt and :cDate < cit_eff_until_dt) "
+ " and (:cDate >= en_eff_asof_dt and :cDate < en_eff_until_dt) ";

So now you'll hve to bind the highlighted variables in the query.

Object[] params = { facId,cDate, cDate, cDate, cDate};

To your query, pass in sql and the parameters bound (ex: for i/p parameter like :cDate in your query, params should contain a cDate in the same order as it expects in the query)

long clietnOid=queryForLong(sql,params);

Monday, June 23, 2008

Tokens in Struts

Purpose: To prevent a page from being re-submitted when user hits refresh or hits submit multiple times or user clicks on back / forward on your browser and hits submit again

Solution: Tokens in Struts 2.0

Token Methods:

The methods we care about are:

saveToken(HttpServletRequest req)
isTokenValid(HttpServletRequest req)
resetToken(HttpServletRequest req)

Once of the basic concept for implementing tokens:

1) Always provide a setupForInsertOrUpdate dispatch method or indvidual Action. You could also break it up into setupForInsert and setupForUpdate if you so desire. Regardless, make sure you always go through this Action method before you go to your form.
2) In your setup method make sure to call "saveToken(request)." This puts a unique key into Session scope and will cause this token to be placed on your resulting JSP.
In your Action's update/insert dispatch method or your Action's execute method, make sure to first check if "isTokenValid(request)." This compares the token in Session with the one submitted through the Request. If they match, the token is valid and it's ok to procede with the update/insert. If they do not match, the user is likely simply resubmitting a stale page so we return from our action immediately. We need to remember before we leave our update/insert method that we call "resetToken(request)" so that we place a new token into Session scope, otherwise the old token will remain and it will match the one on the form and will allow duplicate submisssions.


Example:

public ActionForward setUpForInsertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("setUpForInsertOrUpdate");
saveToken(request);
EmployeeForm employeeForm = (EmployeeForm)form;
if (isUpdate(request, employeeForm)) {
Integer id = Integer.valueOf(employeeForm.getEmployeeId());
Employee employee = empService.getEmployee(id);
BeanUtils.copyProperties(employeeForm, employee);
}
prep(request);
return mapping.findForward(Constants.SUCCESS);
}



public ActionForward insertOrUpdate(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.debug("insertOrUpdate");
EmployeeForm employeeForm = (EmployeeForm)form;
if ( !isTokenValid(request) ) {
return mapping.findForward(Constants.INVALID_TOKEN);
}
if (validationSuccessful(request, employeeForm)) {
Employee employee = new Employee();
BeanUtils.copyProperties(employee, employeeForm);
if (isUpdate(request, employeeForm)) {
logger.debug("update");
empService.updateEmployee(employee);
} else {
logger.debug("insert" );
empService.insertEmployee(employee);
}
populateEmployees(request);
resetToken(request);
return mapping.findForward(Constants.SUCCESS);
} else {
prep(request);
return mapping.findForward(Constants.FAILURE);
}
}


-Smile ...tokens are making your life easy :D

Friday, June 20, 2008

Running db scripts from command prompt

During development, we usually put all the sql scripts on a separate .sql file and run them at once, when you move your code on to other servers for testing purposes.

Here is how you run the scripts from the command prompt.


1) Open a command prompt at the folder where you have your sql scripts
2) execute sqlplus userid/pwd@srgtdev
3) above command will connect you to the oracle and give u a sql>
4) run the following
5) start filename.sql


woo huu all sqls in the batch file will be run successfully and you are good to go. here is an sample batch sql file

set echo on
spool 7_tpa_srgdbo_datascripts.sql.log

--set escape on

delete xyz where template_id in (-7);
INSERT INTO XYZ (TEMPLATE_ID, TEMPLATE_NAME, UPDATE_DATE, STATUS, TYPE, ASSESSMENT_TYPE_ID) VALUES (-7, 'FBI - Test7', SYSDATE, 'InActive', 'FBI', 1);

delete from XYZ_template where template_id = 999;

INSERT INTO XYZ_TEMPLATE (TEMPLATE_ID, TEMPLATE_NAME, UPDATE_DATE, STATUS, TYPE, ASSESSMENT_TYPE_ID, HANDLER_CLASS, HANDLER_JSP, HANDLER_PDF, HANDLER_TEMPLATE_TYPE) VALUES (999, 'Notch Template', SYSDATE, 'InActive', 'NOTCH', 1, 'com.xyz.say.service.Sample', '', '', '');

/* delete temporary data */
delete xyz_template where template_id in (-7);

----------- notching data script starts

delete from xyz_notching_template_qestn where template_id = 20001;

delete from xyz_assessment_type_value where assessment_value_id > 20000 and assessment_value_id < 20034;

delete from xyz_template where template_id = 20001;

delete from xyz_ASSESSMENT_TYPE where ASSESSMENT_TYPE_ID > 20000 and ASSESSMENT_TYPE_ID < 20016;



COMMIT;



spool off
set echo off


-Happy Coding Sonu

Thursday, June 19, 2008

Reading from Properties file into Spring Application Context.xml

Problem: How to read a value from your properties file into your spring's applicationContext.xml..?

Here is how you do it. spring's angle brackets are replaced with []

[bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"]
[property name="location" value="classpath:application.properties"/]
[/bean]

[!-- A sample bean that needs some settings. --]
[bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"]
[property name="driverClassName" value="${jdbc.driver}"/]
[property name="url" value="${jdbc.url}"/]
[property name="username" value="${jdbc.username}"/]
[property name="password" value="${jdbc.password}"/]
[/bean]


Ex: If your properties file is :

jdbc.driver=org.h2.Driver
jdbc.url=jdbc:h2:mem:example
jdbc.username=sa
jdbc.password=asdfa

you can these values directly into ur application ctxt.

More info read:

Wednesday, June 18, 2008

SimpleDateFormat Example in Java

public class DateFormattingTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String myDate="Fri Dec 07 17:58:41 EST 2007";
SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");
try{

Date d1=sdf.parse(myDate);

String s1=sdf2.format(d1);

System.out.println("Date d1 is :"+d1);
System.out.println("Formatted String is :"+s1);

}catch(Exception e){
System.out.println("Date Parsing Exception");

}

}

}


Usage: When you have a String, and if you want to convert it into a java.util.Date,
SimpleDateFormat's instance should indicate the format of your input string for java to parse and convert it into a Date:

Ex: String myDate="Fri Dec 07 17:58:41 EST 2007";

SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");sdf should tell java the format of your input string for it to be able to parse it to a date like:

//Input is a String
//sdf indicates the format of date in i/p String
//Output is a Date


Date d1=sdf.parse(myDate);

Scenario 2: When you have a Date and if you want to convert it into a String,

your SimpleDateFormat object should indicate the format you wish to convert your string into and use format in this case.

ex: SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");

//Input is Date
//sdf indicates the format of the String you wish to see it as output
//Output is formatted String


String s1=sdf2.format(d1);

Sunday, June 15, 2008

TCP / IP

Transmission Control Protocol / Internet Protocol

TCP/IP is a connectionless protocol. Information is transfered in packets. Each of these packets is sent through the network individually. There are provisions to open connections to systems. However at some level, information is put into packets, and those packets are treated by the network as completely separate. For example, suppose you want to transfer a 15000 octet file. Most networks can't handle a 15000 octet packet. So the protocols will break this up into something like 30 500-octet packets. Each of these packets will be sent to the other end. At that point, they will be put back together into the 15000-octet file. However while those packets are in transit, the network doesn't know that there is any connection between them. It is perfectly possible that packet 14 will actually arrive before packet 13. It is also possible that somewhere in the network, an error will occur, and a packet won't get through at all. In that case, that packet has to be sent again. In fact, there are two separate protocols involved in doing this. TCP (the transmission control protocol) is responsible for breaking up the message into packets, reassembling them at the other end, resending anything that gets lost, and putting things back in the right order. IP (the internet protocol) is responsible for routing individual packets. It may seem like TCP is doing all the work. And in small networks that is true. However in the Internet, simply getting a packet to its destination can be a complex job. A connection may require the packet to go through several networks at Rutgers, a serial line to the John von Neuman Supercomputer Center, a couple of Ethernets there, a series of 56Kbaud phone lines to another NSFnet site, and more Ethernets on another campus. Keeping track of the routes to all of the destinations and handling incompatibilities among different transport media turns out to be a complex job. Note that the interface between TCP and IP is fairly simple. TCP simply hands IP a packet with a destination. IP doesn't know how this packet relates to any packet before it or after it.

Friday, June 13, 2008

Increase virtual memory in eclipse

Increasing JVM's virtual memory to avoid core dumps or Out of Memory Error.

1) rt click on ur eclipse.exe or on the shortcut on ur desktop
2) goto shortcut tab and in target specify the jvm vmargs parameter as Xms and Xmx properties.

C:\Suneetha\Dwnld\eclipse\eclipse.exe -product com.genuitec.myeclipse.product.ide -vmargs -Duser.language=en -Xms256M -Xmx512M -XX:PermSize=128M -XX:MaxPermSize=256M


--Sunny

Monday, June 9, 2008

3 C's for Success

Confidence : Confidence in getting things done

Control : Controlled execution of your ideas

Courage : Courage To think big

-Suni

Friday, June 6, 2008

Spring Quick Ref Guide

What is Spring ?

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

Spring is a lightweight, inversion of control AOP based container framework.

What are features of Spring ?

Lightweight:

spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.

Inversion of control (IOC):

Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP):

Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

Container:

Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:

Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.

Transaction Management:

Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.

JDBC Exception Handling:

The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

What is a BeanFactory?

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

What is XMLBeanFactory?

BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.

BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.

MyBean myBean = (MyBean) factory.getBean("myBean");

Explain Bean lifecycle in Spring framework?

1. The spring container finds the bean’s definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.

6. If an init-method is specified for the bean, it will be called.

7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.


What are the important beans lifecycle methods?


There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.


What is Auto wiring?

You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

What is a Target?

A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

What are the different points where weaving can be applied?

Compile Time

Classload Time

Runtime

Thursday, June 5, 2008

Hrithik Photos Test

Regular Expressions in Java

Regular Expressions in Java:

A regular expression works by matching a String against a template or pattern (a Pattern object in Java), and in its simplest form, returning a boolean to say "yes, the string does look like the pattern" or "no, that doesn't match".

As of release 1.4 of Java, though, there's a standard package
java.util.regex
that's shipped with the JRE, and that's what we'll look at in this module.
"^\\S+@\\S+$"

is a regular expression to see if the string entered is an e-mail

Ex:

Pattern email = Pattern.compile("^\\S+cat\\S+$");

Matcher match=email.matcher("vandicated");
if(match.matches()){
System.out.println("Matches vindicated pattern");
}else{
System.out.println("No Match found");
}


If you want to match at the start of a String, start your pattern with a ^ character; if you want to match at the end, conclude your pattern with a $ character. Should you specify both a ^ and a $, then you're looking to match the complete String to your regular expression.

The ^ and $ elements are known as "anchors" as they tie the start and/or the end of the String down; this group as a whole is also known as "assertions" because they don't match any specific characters in the incoming string, they just assert that while the match is running a certain condition must occur at the given point in the match.


If you write

[abcdef]


in your regular expression, then you're matching any one character from the list given (a b c d e or f). You can expand this capability further by using a minus sign to specify a character range, thus

[a-z]
any lower case letter
[0-9a-fA-F]
any hexadecimal character


and if you want to match any character except one from a list, you can start the character list with an ^ character, for example:

[^a-z]
any character except a lower case letter
[^%0-9]
any character except a digit or a % character

but that would get messy really fast, so there are some common groupings available in Java's regular expressions:

\s
any white space character
\d
any digit
\w
any word character (letter, digit, underscore)


If you want any character except one of these, use a capital letter:

\S
any character that is not a white space
\D
any character that is not a digit
\W
any character that is not a word character


Sequences such as \s will be familiar to you if you use Perl's regular expressions, but there are other character groups too; these use a POSIX standard definition of the character groups, but it's extended and the format isn't taken from Perl, nor PHP, nor Tcl nor SQL!

\p{Space}
Alternative to \s for "any white space"
\p{Blank}
Space or tab character
\p{Alpha}
Any letter (upper or lower case)
\p{Graph}
Any visible character
\p{InGreek}
Any Greek letter
\p{Sc}
A currency symbol


You can negate these groups using \P rather than \p thus

\P{Graph}
Any character that is not visible


One final grouping, the ultimate group if you like, is the "." (full stop or period) character, which matches virtually any character.


COUNTS


The fourth main group (after anchors, literal characters, and character groups) are the counts; you use these in regular expressions if you want to give a quantity to a literal character or group, and you add the count character into you pattern directly after the element to which it applies. There are three very common counts:

+
one or more
*
zero or more
?
zero or one

Source: http://www.wellho.net/solutions/java-regular-expressions-in-java.html

Fun exploring new things. :)