Wednesday 9 November 2011

Communications Link Failure Due to Underlying Exception



I was using  Spring 3.x along with mySql for some of my Web app,after considerable idle time (server is up and running but no request hits to the app say for around 6 hrs)it ended up in the following exception



type Exception report


message 


description The server encountered an internal error () that prevented it from fulfilling this request.


exception 


org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: StatementCallback; SQL [SELECT * from TABLE_PARENT]; Communications link failure due to underlying exception: 


** BEGIN NESTED EXCEPTION ** 


java.net.SocketException
MESSAGE: Software caused connection abort: socket write error


STACKTRACE:


java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2744)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1612)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1232)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:440)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:395)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:455)
at com.pm.dboard.dao.PMDBoardDAO.fetchDomains(PMDBoardDAO.java:77)
at com.pm.dboard.service.PMDboardService.fetchDomains(PMDboardService.java:23)
at com.pm.dboard.controller.DBoardController.getDashBoard(DBoardController.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:403)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:301)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:162)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:140)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)




This error was solved after adding the following properties to the datasource bean in the spring's dispatcher-servlet.xml



<property name="testOnBorrow" value="true"/>
<property name="validationQuery" value="SELECT 1"/>


so my datasource bean will look like





<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xxxxx" />
<property name="username" value="durga" />
<property name="password" value="s3cret" />
<property name="testOnBorrow" value="true"/>
               <property name="validationQuery" value="SELECT 1"/>
</bean>


I took considerable amount of time to figure this out and guess this post may come in handy .


Some more configurable properties at  http://commons.apache.org/dbcp/configuration.html


Thanks for reading.
cheers ... :-)


Wednesday 31 August 2011

jquery imgnotes



imgnotes is nothing but notes over images,still not clear?okie, this is something similar to tagging the images as we do in social networking sites like facebook,orkut...etc.




Include the following in the head of your html:



<link rel="stylesheet" type="text/css" href="css/imgnotes.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.imgnotes-0.1.js"></script>


and the files can be downloaded from http://plugins.jquery.com/project/ImgNotes.


The notes to be tagged is given in json format,for eg as below



notes = [ {
"x1" : "195",
"y1" : "183",
"height" : "20",
"width" : "26",
"note" : "<b>  DP means DurgaPrasad not Dharu Party</b>"
} ];





x1 - The X co-ordinate of the top-left corner of the note area
y1 - The Y co-ordinate of the top-left corner of the note area
note - The text of the note, it supports HTML as well
height and width specifies the image range to be covered.
x1 and y1 are relative the position of the image on which the notes will be displayed, so when you move the image around in your page the the notes will move with it.
and the following piece of js will do the work for you.
$(window).load(function() {
$('#tern').imgNotes(notes);
  //someMoreOnClickFunctions();
});

This plugin is very useful in making the images of your website more dynamic and user interactive and can be used to make various parts of your static image as navigational sources....
Thanks for Reading.... cheers :-)



Monday 29 August 2011

Jquery - Image appender Plugin to tag



I was using a lot of jquery plug-ins say for Date component,for creating charts,for sorting tables and just thought of writing a very simple plug-in (jqueryImageAppender.js) to start with.

The compressed version of the jqueryImageAppender.js  is as below.This takes 3 params
1.id of the container(table)
2.Path of the image to be appended
3.Position to be placed (front of tr or end of tr)

so, this function appends the image to each tr at the specified position (at the begin or end)




appendImage('DATA_TABLE','list.gif','not_end') will result in the table as below.










Thanks for reading...cheers  ;-)

Tuesday 23 August 2011

Sample Stock Market Simulator - Spring 3.0



    The module I've decided to work is simple and the following use case describes it.

    I shall use
    Spring 3 mvc,
    jdbc template,  
    mysql, 
    Tomcat 7
    js and jquery Ajax



















and the proj structure looks as below.

    











will update ...cheers :-)

Sunday 7 August 2011

Obsolete Object References




Unlike C and C++ ,Java takes care of memory management through Garbage-collector,but  care must be taken to avoid the unintentional objects (Obsolete Object References ) occurring.An obsolete reference is a reference that will never be dereferred again.

refer the following sample code of  Stack.

































When the pop is called the copy of the reference is poped out ,but there will be unintentional reference still lying in the array  and it will be replaced for the push of a new item.


But,if there are series of pop outs and no new elements pushed there it results in many obsolete references.This can be avoided by nulling out the references after each pop as below.













Eliminating this unintentional references results in  Better performance, less memory, and When nulling out the references, if they get de-referred to later by a mistake, you will get a NullPointerException (as you should!)

Its always beneficial to detect programming errors as quickly as possible.

(Inspired from Effective Java Item:5)


Cheers. . . .  ;-)

Friday 5 August 2011

PermGen - OOME(out of memory error) -Tomcat 7








PermGen  - OOME(out of memory error) -Tomcat 7




PermGen (Permananet Generation) space is the place where JVM stores the classes.Classes are stored in the permgen space using class loaders and unique  class identifiers.Each webapp has its own class loader which allows the use of the different version of classes(with same name) in permgen space with out any conflicts.


So,a webapp has its own class loader and a new class loader is created for every reload.The class loaders are garbage collected by the garbage collector when the application stops.But,in case if some reference still exists even after the application is stopped,the class loaders will not be garbage collected,say you are developing a web app where some reference still exists and on every reload or restart of your server,the permgen is heaping up.
The Permgen space is limited and when the classloaders grow up it results in OOME.To,avoid this we must see that no reference to the webapp remains after the app is stopped.




some sceanrios which can cause Permgen space errors are some references to JDBC driver registration,logging frameworks,threads started but not stopped,non removal of objects in thread locals etc.


Apache Tomcat 7.x has come up with many features,Web application memory leak detection and prevention is one of them.JreMemoryLeakPreventionListener is the new life cycle listener class added that calls the various java apis that are known to retain a reference to the current context class loader.If the webapp is the fist to call such apis then there may result in unnecessary existence of references and hence the unrequired class loaders and so the OOME.If the Tomcat calls the java apis first,the memory leaks can be prevented and hence the JreMemoryLeakPreventionListener.This feature also comes with ability to detect the memory leakage occurence,this is added as enhancement to the WebappClassLoader






These seems to be a good enhancement and we should be seeing less PermGen space error with Tomcat 7.x






Cheers... :-)

Thursday 4 August 2011

Java Static Block





I was working on the requirement of extracting the contents from a html page(Which is not that dynamic,in the sense no frequent changes) and format it, display on the front end(jsp in my case).


I opted  HtmlUnit and grepped the contents and transferred them to the front end.Since,the HtmlUnit has to parse the tables,, the page rendering was very slow.


Static block for rescue(since the html is not so dynamic and has no frequent changes),parsed the html and load the contents at the time of class loading.


The loaded data will be served for each request instead of loading data for each request and decreasing the page rendering time and the static block looks as below and it worked like a charm ;-).


So,the elementList in the above code will be populated (which is time consuming) during the class load and happens only once and this would be used in the request serving methods.Load once Serve manier times.




Cheers... Happy Coding ;-)

Monday 1 August 2011

HtmlUnit



HtmlUnit provides an API to invoke web pages,fill the input fields,submit the forms.It is used to simulate the browser actions and is intended to use along with junit or testng .Apart,from testing HtmlUnit can also be used to grep the data from the browser and it supports many calls like getElementsByTagName("****"),getElementById("***"),getInputByName("****") etc.


The following sample code illustrates the use of HtmlUnit to input the fields and submit click action.This sounds similar to selenium,but here there is no browser invocation stuffs, it is  "GUI-Less browser for Java programs" and can capture the content of the browser,can be the data from tables,fields,container divs (similar to js functions nodes,cells,siblings etc).it also provides good support to js and ajax calls.






























The following case uses HtmlUnit along with Junit to test the web browser 





@Test
public void homePage_Firefox() throws Exception {
    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_2);
    final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
    assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());

    webClient.closeAllWindows();
}


More examples can be found here




cheers... happy coding !! :-)


Table Sorting Jquery plugin

The sorting of the data has become quiet easy using jquery plugin.Here goes the sample code to sort  the table.

Include the jquery and Jquery.tablesorter js files.



any related selector can be used for the container,in the above piece of code DATA_TABLE1 is the id of the table.


Parser[i] is undefined 


Case 1:


I've encountered the above error while trying to sort and the reason for the error was there were some empty
<tr> tags present in the table(since,I was using dynamic creation of the table empty <tr> tags sneaked in and on removal of them it  went on fine)


Case 2:


The same error can happen when trying to sort a empty table and be sure that if you are creating the container(dynamically),the sort is applied once the table is filled up.






Cheers and Happy Coding  :-)

Wednesday 27 July 2011

Java-Encryption



When your application has log in form or registration form,you may need to save the passwords of the users to the db.The best practice when saving passwords is using java encryption.There are some implicit algorithms used for encryption and the following code uses the SHA algorithm.



So,now the encrypted values can be put to the db and the same can be used while validating the user entered password  with out any decryption.I mean follow the same encryption process and validate the entry.

More info on Cryptographic Hash functions can be found here.

Cheers..... :-)

Monday 25 July 2011

Jquery-Ajax



It is important to mention the return data type of response you are expecting from your ajax call.My response was simple string with delimiter as ^ and was working fine on I.E and Chrome.But,when switched to firefox, encountered some problem.The problem was I.E browser was  assuming return data type as text , and so it was fine,but where as the firefox is taking default type of response as  xml and was causing the problem.










So, please be sure about the data types supported and is good to mention in your ajax call to save your time.


Click here for more Info on data types supported
















 Cheers...... :-)

Tuesday 19 July 2011

Bubble Sort - Java







 Cheers...... :-)

Jquery -simplified js

In this article,let us see how we can use jquery in the place of  java script and minimize the lines of code.

Case 1:

let us say,your form has 100 input text fields and you have a use case clearing the values on click of reset button .This can be easily acheived using jquery as below where :input is the selector to select all input types









Case 2:

let's say you need the value selected in the group of  radio buttons ,let us consider the radio buttons name is gender














Case 3:


Lets take a use case where you have a number of check boxes which may need to be check or un-check at a single shot,this can be easily achieved as below















All the above stuff can be achieved using js but not that easily as in jquery.for more selectors refer JQUERY SELECTORS



cheers..... :-)

Sunday 17 July 2011

Jquery - charts



There are lot of jquery plugins and sophisticated js available for creating graphical reports.The following code uses the jgcharts.js to create the sample charts.

I'm using a plain html here and lil bit of Json for the data and remaining is self explanatory .






Cheers.... :-)

Singleton -the 1.5 way



Reference : Effective Java Edition 2


There are two ways to implement Singleton pattern in Java
1.  public final instance field or static factory method to create/get instance.
2. if you are using Java >= 1.5. You can use Enum for Singleton– this way you get Singleton functionality easily and you don't need to worry about the Serialization.

Sample Code:

  and can use in the following way.

 static DatabaseManager dbMgr=DBUtil.INSTANCE.getDBManager();


cheers....  :-)

Tuesday 12 July 2011

SEJ (Spring Ejp JSP)

Hi,

I started an application using the following.


Spring 3.0 (few concepts like DI,auto wiring,annotation based controllers)
EJP(for db operations)
JSP(front end),
Plain Ajax 
Jquery and JS
Mysql(backend)
Junit
Ant

Will keep posted all the details once done...


cheers... ;-)

Monday 11 July 2011

ConcurrentModificationException - Fail-fast Operations


Most of the time we use ArrayList ,add objects,remove and iterate through them in the List.Go through the following code.



The above code will result in 
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at CSSCreator.main(CSSCreator.java:16)

This is because of fail-fast operation .Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.


The best way to avoid ConcurrentModificationException is to use iterator while you have modifications to be done for the arraylist which you are iterating.

Using iterator in the following way also ends up with ConcurrentModificationException.


The right way of using it will be as follows and it makes sense because the iterator object knows where it is in the list as the list is being scanned.

 I had some tough time with this ConcurrentModificationException and thought of sharing(may be useful to some one at some point of time).....  

cheers ;-)

Saturday 9 July 2011

Spring 3.0 -Sample Controller Example


The following is the very basic Example Which I  tried out on Spring 3.0.The following screen hits include

1.Jars used for my sample.
2.Web.xml
3.Dispatcher-servlet.xml
4.Sample Controller code.
5.jsp samples.
6.Build.xml
7.Build.properties.

Since this code is of very basic,there's no much explanation deserved ;-)

1.Jars:






















2.web.xml









4.Sample controller:



































5. index.htm and result.jsps



<html>
<head>
<title>Spring 3 Example index.dp</title>
</head>
<body>
<a href="demo.html">Login</a>
</body>
</html>





<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>result</title>
</head>
<body>
${message}
</body>
</html>




Build.xml
 Tasks  deploy and deploywar in the following build file would use the build.properties to copy the war or the application folder to the webapps folder of tomcat. The lib and home mentioned in the build properties file may vary with tomcat versions and should change as needed.






build.properties :








Thursday 30 June 2011

JDk 1.7 ~String in Switch and Multi Catch~

JDK 1.7 also supports using String in your switch case and multi catch option as shown under.




Swicth case is alternative to your if else condition but only when you need to check for the equality condition(Switch will not support < or > )
When there is choice to be made between if else or switch,its better to opt to switch because of readabilty and fastness in execution (Jump table or Branch table concepts)....thats it for now cheeeers !! ;-)

JDK 1.7 ~java.util.Objects~

Working with Jdk 1.7 early access download,one of the enhancements made is introduction of java.util.Objects similar to that of java.util.Collections.The Objects class supports some null safe and null tolerant methods.Check the following class for some hint.

1.Equals Support



  To know its usefulness let us say your code looks as follows:


     if(foo.equals(foo2)) { //do something }

what if foo is null,you will encounter null pointer exception(else may be you need to have one more check for null),with java.util.Objects


 Objects.equals(foo,foo2)) if foo is null,it will return false :-)






2.Hashing Support:


Most of the standards and technologies need their classed\s to override equals and hashcode method(atleast some times u may need to for better performance e.g. HashMap usage), java.util.objects provides a better way of hashing.



 This is very useful especially for your DTO objects which may contain many number of fields.

 hashCode(Object o):int -->>  Returns the hash code of a non-null argument and 0 for a null argument.


and there is some more enhancements made toString() with null support.

Thats it for now.... cheers ;-)