tag:blogger.com,1999:blog-23227390970680093912024-03-14T14:23:15.654+05:30TechnoCratTechnical blog on Java/JSP
You can contact me at yogesh249@gmail.comYogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.comBlogger172125tag:blogger.com,1999:blog-2322739097068009391.post-70845594725976267682017-11-14T12:50:00.000+05:302017-11-14T12:50:10.719+05:30How to read PDF using JAVA<pre class="brush:java">import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
class mytext
{
public static void main(String[] args)
{
try {
PDDocument document = null;
document = PDDocument.load(new File("H:\\test.pdf"));
document.getClass();
if (!document.isEncrypted()) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
PDFTextStripper Tstripper = new PDFTextStripper();
String st = Tstripper.getText(document);
System.out.println("Text:" + st);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}</pre><br />
<br />
PDF Box API can be downloaded from :<br />
<br />
https://pdfbox.apache.org/index.html<br />
its an open source.<br />
<br />
Also available in my google drive version 2.0.8 - https://drive.google.com/open?id=1S_7Jq-D2FG1ebe04pOywdYy7YxxbTUFr<br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com6tag:blogger.com,1999:blog-2322739097068009391.post-44182508348488331402016-08-05T12:04:00.001+05:302016-08-05T12:04:18.259+05:30Why for each loop doesn't throw ConcurrentModification exception in case List has only 2 elements<pre class="brush:java">
List<Person> first = new ArrayList<Person>();
Person p1=new Person("p1", 1);
Person p2=new Person("p2", 2);
Person p3=new Person("p3", 3);
first.add(p1);
first.add(p2);
first.add(p3);
for(Person p: first)
{
first.remove(p);
}
</pre><br />
The above code will throw ConcurrentModificationException<br />
<br />
Now remove the following code<br />
<br />
<pre class="brush:java">first.add(p3);
</pre><br />
And re-execute the code...<br />
<br />
Now you'll see that no exception will be thrown...<br />
<br />
What's the reason behind this?<br />
<br />
Actually for-each loop uses Iterator behind the scenes<br />
<br />
which gets converted to the following<br />
<br />
<pre class="brush:java"> Iterator i = first.iterator();
while(i.hasNext())
{
Person px = (Person)i.next();
first.remove(px);
}
</pre><br />
In case of two elements, here are the steps that are followed<br />
<ul><li>Iterator is created<br />
<li>hasNext returns true<br />
<li>.next method returns the first element of the list<br />
<li>First element is removed. Now list contains only 1 element.<br />
<li>As iterator has already traversed one element and also list has 1 element, hasNext method will return false<br />
<li>Hence the loop terminates.<br />
</ul>
In case of three elements, here are the steps that are followed
<ul><li>Iterator is created<br />
<li>hasNext returns true<br />
<li>.next method returns the first element of the list<br />
<li>First element is removed. Now list contains 2 elements.<br />
<li>As iterator has already traversed one element and list has 2 elements, hasNext method will return true<br />
<li>control will enter the loop<br />
<li>.next method will see that iterator has been modified and hence throw a ConcurrentModificationException<br />
</ul><br />
<br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-73767656070944695672016-01-19T09:21:00.001+05:302016-01-19T09:53:46.956+05:30Java exception handling best practicesThanks to <a href="http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/">Java exception handling best practices</a><br />
<br />
Before we dive into deep concepts of exception handling best practices, lets start with one of the most important concepts which is to understand that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.<br />
<br />
<p class="heading">Type of exceptions</p><div class="collapsingdiv"><a href="http://4.bp.blogspot.com/-iA1MDktT9ho/Vp2yeTGUTpI/AAAAAAAAhz4/RvIXeJdCDrE/s1600/exceptionhierarchy3.png" imageanchor="1" ><img border="0" src="http://4.bp.blogspot.com/-iA1MDktT9ho/Vp2yeTGUTpI/AAAAAAAAhz4/RvIXeJdCDrE/s640/exceptionhierarchy3.png" /></a><br />
<br />
<br />
<br />
<b>Checked exceptions</b> are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an “in your face” type of exceptions. Java wants you to handle them because they somehow are dependent on external factors outside your program. A checked exception indicates an expected problem that can occur during normal system operation. Mostly these exception happen when you try to use external systems over network or in file system. Mostly, the correct response to a checked exception should be to try again later, or to prompt the user to modify his input.<br />
<br />
<b>Unchecked exceptions</b> are exceptions that do not need to be declared in a throws clause. JVM simply doesn’t force you to handle them as they are mostly generated at runtime due to programmatic errors. They extend RuntimeException. The most common example is a NullPointerException [Quite scary.. Isn’t it?]. An unchecked exception probably shouldn’t be retried, and the correct action should be usually to do nothing, and let it come out of your method and through the execution stack. At a high level of execution, this type of exceptions should be logged.<br />
<br />
<b>Errors</b> are serious runtime environment problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError. They generally crash you program or part of program. Only a good logging practice will help you in determining the exact causes of errors.<br />
<br />
<br />
</div><br />
<p class="heading">User defined custom exceptions</p><div class="collapsingdiv">Anytime when user feels that he wants to use its own application specific exception for some reasons, he can create a new class extending appropriate super class (mostly its Exception.java) and start using it in appropriate places. These user defined exceptions can be used in two ways:<br />
<br />
1) Either directly throw the custom exception when something goes wrong in application<br />
<br />
<pre class="brush:java">throw new DaoObjectNotFoundException("Couldn't find dao with id " + id);
</pre><br />
2) Or wrap the original exception inside custom exception and throw it<br />
<pre class="brush:java">catch (NoSuchMethodException e) {
throw new DaoObjectNotFoundException("Couldn't find dao with id " + id, e);
}
</pre><br />
Wrapping an exception can provide extra information to the user by adding your own message/ context information, while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions.<br />
<br />
Now lets start exploring the best practices followed for exception handling industry wise.<br />
<br />
<br />
</div><br />
<br />
<p class="heading">Best practices you must consider and follow</p><div class="collapsingdiv"><p class="heading">1) Never swallow the exception in catch block</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e) {
return null;
}
</pre>Doing this not only return “null” instead of handling or re-throwing the exception, it totally swallows the exception, losing the cause of error forever. And when you don’t know the reason of failure, how you would prevent it in future? Never do this !!<br />
</div><br />
<p class="heading">2) Declare the specific checked exceptions that your method can throw</p><div class="collapsingdiv"><pre class="brush:java">public void foo() throws Exception { //Incorrect way
}
</pre>Always avoid doing this as in above code sample. It simply defeats the whole purpose of having checked exception. Declare the specific checked exceptions that your method can throw. If there are just too many such checked exceptions, you should probably wrap them in your own exception and add information to in exception message. You can also consider code refactoring also if possible.<br />
<br />
<pre class="brush:java">public void foo() throws SpecificException1, SpecificException2 { //Correct way
}
</pre></div><br />
<p class="heading">3) Do not catch the Exception class rather catch specific sub classes</p><div class="collapsingdiv"><pre class="brush:java">try {
someMethod();
} catch (Exception e) {
LOGGER.error("method has failed", e);
}
</pre>The problem with catching Exception is that if the method you are calling later adds a new checked exception to its method signature, the developer’s intent is that you should handle the specific new exception. If your code just catches Exception (or Throwable), you’ll never know about the change and the fact that your code is now wrong and might break at any point of time in runtime.<br />
</div><br />
<p class="heading">4) Never catch Throwable class</p><div class="collapsingdiv">Well, its one step more serious trouble. Because java errors are also subclasses of the Throwable. Errors are irreversible conditions that can not be handled by JVM itself. And for some JVM implementations, JVM might not actually even invoke your catch clause on an Error.<br />
</div><br />
<p class="heading">5) Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e) {
throw new MyServiceException("Some information: " + e.getMessage()); //Incorrect way
}
</pre>This destroys the stack trace of the original exception, and is always wrong. The correct way of doing this is:<br />
<pre class="brush:java">catch (NoSuchMethodException e) {
throw new MyServiceException("Some information: " , e); //Correct way
}
</pre></div><br />
<p class="heading">6) Either log the exception or throw it but never do the both</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e) {
LOGGER.error("Some information", e);
throw e;
}
</pre>As in above example code, logging and throwing will result in multiple log messages in log files, for a single problem in the code, and makes life hell for the engineer who is trying to dig through the logs.<br />
</div><br />
<p class="heading">7) Never throw any exception from finally block</p><div class="collapsingdiv"><pre class="brush:java">try {
someMethod(); //Throws exceptionOne
} finally {
cleanUp(); //If finally also threw any exception the exceptionOne will be lost forever
}
</pre>This is fine, as long as cleanUp() can never throw any exception. In the above example, if someMethod() throws an exception, and in the finally block also, cleanUp() throws an exception, that second exception will come out of method and the original first exception (correct reason) will be lost forever. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it come out of the finally block.<br />
</div><br />
<p class="heading">8) Always catch only those exceptions that you can actually handle</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e) {
throw e; //Avoid this as it doesn't help anything
}
</pre><b><br />
Well this is most important concept. Don’t catch any exception just for the sake of catching it. Catch any exception only if you want to handle it or, you want to provide additional contextual information in that exception. If you can’t handle it in catch block, then best advice is just don’t catch it only to re-throw it.</b><br />
</div><br />
<p class="heading">9) Don’t use printStackTrace() statement or similar methods</p><div class="collapsingdiv">Never leave printStackTrace() after finishing your code. Chances are one of your fellow colleague will get one of those stack traces eventually, and have exactly zero knowledge as to what to do with it because it will not have any contextual information appended to it.<br />
</div><br />
<br />
<p class="heading">10) Use finally blocks instead of catch blocks if you are not going to handle exception</p><div class="collapsingdiv"><pre class="brush:java">try {
someMethod(); //Method 2
} finally {
cleanUp(); //do cleanup here
}
</pre>This is also a good practice. If inside your method you are accessing some method 2, and method 2 throw some exception which you do not want to handle in method 1, but still want some cleanup in case exception occur, then do this cleanup in finally block. Do not use catch block.<br />
</div><br />
<p class="heading">11) Remember “Throw early catch late” principle</p><div class="collapsingdiv">This is probably the most famous principle about Exception handling. It basically says that you should throw an exception as soon as you can, and catch it late as much as possible. You should wait until you have all the information to handle it properly.<br />
<br />
This principle implicitly says that you will be more likely to throw it in the low-level methods, where you will be checking if single values are null or not appropriate. And you will be making the exception climb the stack trace for quite several levels until you reach a sufficient level of abstraction to be able to handle the problem.<br />
</div><br />
<br />
<p class="heading">12) Always clean up after handling the exception</p><div class="collapsingdiv">If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try -- finally blocks. Inside try block access the resource and inside finally close the resource. Even if any exception occur in accessing the resource, then also resource will be closed gracefully.<br />
</div><br />
<p class="heading">13) Throw only relevant exception from a method</p><div class="collapsingdiv">Relevancy is important to keep application clean. A method which tries to read a file; if throws NullPointerException then it will not give any relevant information to user. Instead it will be better if such exception is wrapped inside custom exception e.g. NoSuchFileFoundException then it will be more useful for users of that method.<br />
</div><br />
<p class="heading">14) Never use exceptions for flow control in your program</p><div class="collapsingdiv">We have read it many times but sometimes we keep seeing code in our project where developer tries to use exceptions for application logic. Never do that. It makes code hard to read, understand and ugly.<br />
</div><br />
<p class="heading">15) Validate user input to catch adverse conditions very early in request processing</p><div class="collapsingdiv">Always validate user input in very early stage, even before it reached to actual controller. It will help you to minimize the exception handling code in your core application logic. It also helps you in making application consistent if there is some error in user input.<br />
<br />
For example: If in user registration application, you are following below logic:<br />
<br />
1) Validate User<br />
2) Insert User<br />
3) Validate address<br />
4) Insert address<br />
5) If problem the Rollback everything<br />
<br />
This is very incorrect approach. It can leave you database in inconsistent state in various scenarios. Rather validate everything in first place and then take the user data in dao layer and make DB updates. Correct approach is:<br />
<br />
1) Validate User<br />
2) Validate address<br />
3) Insert User<br />
4) Insert address<br />
5) If problem the Rollback everything<br />
</div><br />
<br />
<p class="heading">16) Always include all information about an exception in single log message</p><div class="collapsingdiv">LOGGER.debug(“Using cache sector A”);<br />
LOGGER.debug(“Using retry sector B”);<br />
<br />
Don’t do this.<br />
<br />
Using a multi-line log message with multiple calls to LOGGER.debug() may look fine in your test case, but when it shows up in the log file of an app server with 400 threads running in parallel, all dumping information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.<br />
<br />
Do it like this:<br />
<br />
LOGGER.debug(“Using cache sector A, using retry sector B”);<br />
</div><br />
<p class="heading">17) Pass all relevant information to exceptions to make them informative as much as possible<br />
<div class="collapsingdiv">This is also very important to make exception messages and stack traces useful and informative. What is the use of a log, if you are not able to determine anything out of it. These type of logs just exist in your code for decoration purpose.<br />
</div><br />
<p class="heading">18) Always terminate the thread which it is interrupted</p><div class="collapsingdiv"><pre class="brush:java">while (true) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {} //Don't do this
doSomethingCool();
}
</pre><br />
InterruptedException is a clue to your code that it should stop whatever it’s doing. Some common use cases for a thread getting interrupted are the active transaction timing out, or a thread pool getting shut down. Instead of ignoring the InterruptedException, your code should do its best to finish up what it’s doing, and finish the current thread of execution. So to correct the example above:<br />
<pre class="brush:java">while (true) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
break;
}
}
doSomethingCool();
</pre></div><br />
<p class="heading">19) Use template methods for repeated try-catch</p><div class="collapsingdiv">There is no use of having a similar catch block in 100 places in your code. It increases code duplicity which does not help anything. Use template methods for such cases.<br />
<br />
For example below code tries to close a database connection.<br />
<pre class="brush:java">class DBUtil{
public static void closeConnection(Connection conn){
try{
conn.close();
} catch(SQLException ex){
throw new RuntimeException("Cannot close connection", ex);
}
}
}
</pre>This type of method will be used in thousands of places in your application. Don’t put whole code in every place rather define above method and use it everywhere like below:<br />
<pre class="brush:java">public void dataAccessCode() {
Connection conn = null;
try{
conn = getConnection();
....
} finally{
DBUtil.closeConnection(conn);
}
}
</pre></div><br />
<p class="heading">20) Document all exceptions in your application in javadoc</p><div class="collapsingdiv">Make it a practice to javadoc all exceptions which a piece of code may throw at runtime. Also try to include possible course of action, user should follow in case these exception occur.<br />
<br />
That’s all i have in my mind for now. If you found anything missing or you does not relate to my view on any point, drop me a comment. I will be happy to discuss.<br />
</div></div>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-45967262632945145042015-03-19T17:43:00.000+05:302015-03-19T17:43:10.334+05:30How to create a table with fixed columns and headers<br />
<pre class="brush:html"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
table.main
{
width: 700px;
height: 221px;
table-layout: fixed;
}
table.root
{
table-layout: fixed;
}
table.content
{
table-layout: fixed;
width: 1890px;
}
table.head
{
table-layout: fixed;
width: 1890px;
}
table.frozen
{
table-layout: fixed;
}
td
{
line-height: 28px;
}
div.horizontal-scroll
{
width: 703px;
height: 22px;
overflow: hidden;
overflow-x: scroll;
border: solid 1px #666;
}
div.horizontal-scroll div
{
width: 2173px;
height: 1px;
}
div.vertical-scroll
{
height: 227px;
width: 22px;
overflow: hidden;
overflow-y: scroll;
border: solid 1px #666;
}
div.vertical-scroll div
{
height: 377px;
width: 1px;
}
td.inner
{
border-left: 1px solid #666;
border-bottom: 1px solid #666;
padding: 3px;
height: 28px;
}
td.frozencol
{
border-right: 1px double #666;
width: 200px;
}
td.col1
{
border-left: none;
width: 100px;
}
td.bottomcol
{
/*border-bottom: 1px solid #666;*/
}
.col2, .col3, .col4, .col5, .col6, .col7, .col8, .col9, .col10
{
width: 200px;
overflow: hidden;
text-overflow: ellipses;
white-space: nowrap;
}
td.head
{
/*border-bottom: 1px solid #666;*/
background-color: #efefef;
border-top: 1px solid #666;
}
.rightcol
{
border-right: 1px solid #666;
}
.toprow
{
border-top: 0px;
}
div.root
{
margin-left: 0px;
overflow: hidden;
width: 200px;
height: 28px;
border-bottom: 1px solid #666;
}
div.frozen
{
overflow: hidden;
width: 200px; /*border-bottom: 1px solid #666;*/
height: 200px;
}
div.divhead
{
overflow: hidden;
height: 28px;
width: 500px;
border-left: 1px solid #666;
border-right: 1px solid #666; /*border-bottom: 0px solid #666;*/
border-bottom: 1px solid #666;
}
div.content
{
overflow: hidden;
width: 500px;
height: 200px;
border-left: 1px solid #666;
border-right: 1px solid #666; /*border-bottom: 1px solid #666;*/
}
td.tablefrozencolumn
{
width: 200px;
border-right: 3px solid #666;
}
td.tablecontent
{
width: 501px;
}
td.tableverticalscroll
{
width: 24px;
}
div.ff-fill
{
height: 23px;
width: 23px;
background-color: #ccc;
border-right: 1px solid #666;
border-bottom: 1px solid #666;
}
</style>
<!--[if LT IE 7]>
<style type="text/css">
div.ff-fill
{
height: 10px;
width:20px;
}
td.tablecontent
{
width: 500px;
}
div.horizontal-scroll
{
width:700px;
height:20px;
}
div.horizontal-scroll div
{
width: 2100px;
}
div.vertical-scroll
{
height:228px;
width:20px;
}
div.vertical-scroll div
{
height:306px;
}
td.tableverticalscroll
{
width:22px;
}
</style>
<![endif]-->
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="0" cellpadding="0" cellspacing="0" class='main'>
<tr>
<td class='tablefrozencolumn'>
<div id='divroot' class='root'>
<table border="0" cellpadding="0" cellspacing="0" width="100%" class='root'>
<tr>
<td class='inner frozencol colwidth head'>
Head0
</td>
</tr>
</table>
</div>
<div id='divfrozen' class='frozen'>
<table border="0" cellpadding="0" cellspacing="0" width="100%" class='frozen'>
<tr>
<td class='inner frozencol toprow'>
Col0Row2
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row3
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row4
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row5
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row6
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row7
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row8
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row9
</td>
</tr>
<tr>
<td class='inner frozencol'>
Col0Row10
</td>
</tr>
<tr>
<td class='inner frozencol bottomcol rightcol'>
Col1Row11
</td>
</tr>
</table>
</div>
</td>
<td class='tablecontent'>
<div id='headscroll' class='divhead'>
<table border="0" cellpadding="0" cellspacing="0" class='head'>
<tr>
<td class='inner col1 head'>
Head 1
</td>
<td class='inner col2 head'>
Head 2
</td>
<td class='inner col3 head'>
Head 3
</td>
<td class='inner col4 head'>
Head 4
</td>
<td class='inner col5 head'>
Head 5
</td>
<td class='inner col6 head'>
Head 6
</td>
<td class='inner col7 head'>
Head 7
</td>
<td class='inner col8 head'>
Head 8
</td>
<td class='inner col9 head'>
Head 9
</td>
<td class='inner col10 head rightcol'>
Head 10
</td>
</tr>
</table>
</div>
<div id='contentscroll' class='content' onscroll='reposHead(this);'>
<table border="0" cellpadding="0" cellspacing="0" class='content' id='innercontent'>
<tr>
<td class='inner col1 toprow'>
Col1Row2
</td>
<td class='inner col2'>
Col2Row2
</td>
<td class='inner col3'>
Col3Row2
</td>
<td class='inner col4'>
Col4Row2
</td>
<td class='inner col5'>
Col5Row2
</td>
<td class='inner col6'>
Col6Row2
</td>
<td class='inner col7'>
Col7Row2
</td>
<td class='inner col8'>
Col8Row2
</td>
<td class='inner col9'>
Col9Row2
</td>
<td class='inner col10 rightcol'>
Col10Row2
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row3
</td>
<td class='inner'>
Col2Row3
</td>
<td class='inner'>
Col3Row3
</td>
<td class='inner'>
Col4Row3
</td>
<td class='inner'>
Col5Row3
</td>
<td class='inner'>
Col6Row3
</td>
<td class='inner'>
Col7Row3
</td>
<td class='inner'>
Col8Row3
</td>
<td class='inner'>
Col9Row3
</td>
<td class='inner rightcol'>
Col10Row3
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row4
</td>
<td class='inner'>
Col2Row4
</td>
<td class='inner'>
Col3Row4
</td>
<td class='inner'>
Col4Row4
</td>
<td class='inner'>
Col5Row4
</td>
<td class='inner'>
Col6Row4
</td>
<td class='inner'>
Col7Row4
</td>
<td class='inner'>
Col8Row4
</td>
<td class='inner'>
Col9Row4
</td>
<td class='inner rightcol'>
Col10Row4
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row5
</td>
<td class='inner'>
Col2Row5
</td>
<td class='inner'>
Col3Row5
</td>
<td class='inner'>
Col4Row5
</td>
<td class='inner'>
Col5Row5
</td>
<td class='inner'>
Col6Row5
</td>
<td class='inner'>
Col7Row5
</td>
<td class='inner'>
Col8Row5
</td>
<td class='inner'>
Col9Row5
</td>
<td class='inner rightcol'>
Col10Row5
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row6
</td>
<td class='inner'>
Col2Row6
</td>
<td class='inner'>
Col3Row6
</td>
<td class='inner'>
Col4Row6
</td>
<td class='inner'>
Col5Row6
</td>
<td class='inner'>
Col6Row6
</td>
<td class='inner'>
Col7Row6
</td>
<td class='inner'>
Col8Row6
</td>
<td class='inner'>
Col9Row6
</td>
<td class='inner rightcol'>
Col10Row6
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row7
</td>
<td class='inner'>
Col2Row7
</td>
<td class='inner'>
Col3Row7
</td>
<td class='inner'>
Col4Row7
</td>
<td class='inner'>
Col5Row7
</td>
<td class='inner'>
Col6Row7
</td>
<td class='inner'>
Col7Row7
</td>
<td class='inner'>
Col8Row7
</td>
<td class='inner'>
Col9Row7
</td>
<td class='inner rightcol'>
Col10Row7
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row8
</td>
<td class='inner'>
Col2Row8
</td>
<td class='inner'>
Col3Row8
</td>
<td class='inner'>
Col4Row8
</td>
<td class='inner'>
Col5Row8
</td>
<td class='inner'>
Col6Row8
</td>
<td class='inner'>
Col7Row8
</td>
<td class='inner'>
Col8Row8
</td>
<td class='inner'>
Col9Row8
</td>
<td class='inner rightcol'>
Col10Row8
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row9
</td>
<td class='inner'>
Col2Row9
</td>
<td class='inner'>
Col3Row9
</td>
<td class='inner'>
Col4Row9
</td>
<td class='inner'>
Col5Row9
</td>
<td class='inner'>
Col6Row9
</td>
<td class='inner'>
Col7Row9
</td>
<td class='inner'>
Col8Row9
</td>
<td class='inner'>
Col9Row9
</td>
<td class='inner rightcol'>
Col10Row9
</td>
</tr>
<tr>
<td class='inner col1'>
Col1Row10
</td>
<td class='inner'>
Col2Row10
</td>
<td class='inner'>
Col3Row10
</td>
<td class='inner'>
Col4Row10
</td>
<td class='inner'>
Col5Row10
</td>
<td class='inner'>
Col6Row10
</td>
<td class='inner'>
Col7Row10
</td>
<td class='inner'>
Col8Row10
</td>
<td class='inner'>
Col9Row10
</td>
<td class='inner rightcol'>
Col10Row10
</td>
</tr>
<tr>
<td class='inner col1 bottomcol'>
Col1Row11
</td>
<td class='inner bottomcol'>
Col2Row11
</td>
<td class='inner bottomcol'>
Col3Row11
</td>
<td class='inner bottomcol'>
Col4Row11
</td>
<td class='inner bottomcol'>
Col5Row11
</td>
<td class='inner bottomcol'>
Col6Row11
</td>
<td class='inner bottomcol'>
Col7Row11
</td>
<td class='inner bottomcol'>
Col8Row11
</td>
<td class='inner bottomcol'>
Col9Row11
</td>
<td class='inner bottomcol rightcol'>
Col10Row11
</td>
</tr>
</table>
</div>
</td>
<td class='tableverticalscroll' rowspan="2">
<div class='vertical-scroll' onscroll='reposVertical(this);'>
<div>
</div>
</div>
<div class='ff-fill'>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class='horizontal-scroll' onscroll='reposHorizontal(this);'>
<div>
</div>
</div>
</td>
</tr>
</table>
</div>
<script language='javascript' type='text/javascript'>
function reposHead(e) {
var h = document.getElementById('headscroll');
h.scrollLeft = e.scrollLeft;
var f = document.getElementById('divfrozen');
f.scrollTop = e.scrollTop;
}
function reposHorizontal(e) {
var h = document.getElementById('headscroll');
var c = document.getElementById('contentscroll');
h.scrollLeft = e.scrollLeft;
c.scrollLeft = e.scrollLeft;
var sh = document.getElementById('hscrollpos');
sh.innerHTML = e.scrollLeft;
var ch = document.getElementById('contentwidth');
var ic = document.getElementById('innercontent');
ch.innerHTML = ic.clientWidth; //c.scrollWidth;
var ch2 = document.getElementById('contentheight');
ch2.innerHTML = ic.clientHeight; //c.scrollWidth;
var sp = document.getElementById('scrollwidth');
sp.innerHTML = e.scrollWidth;
}
function reposVertical(e) {
var h = document.getElementById('divfrozen');
var c = document.getElementById('contentscroll');
h.scrollTop = e.scrollTop;
c.scrollTop = e.scrollTop;
var sh = document.getElementById('vscrollpos');
sh.innerHTML = e.scrollTop;
var ch = document.getElementById('contentheight');
ch.innerHTML = c.scrollHeight;
var sp = document.getElementById('scrollheight');
sp.innerHTML = e.scrollHeight;
}
</script>
<br />
<br />
Horizonal scroll pos:<span id='hscrollpos'>0</span>px<br />
Vertical scroll pos:<span id='vscrollpos'>0</span>px<br />
Height of inner content elt:<span id='contentheight'>0</span>px<br />
Width of inner content elt:<span id='contentwidth'>0</span>px<br />
Height of scroll elt:<span id='scrollheight'>0</span>px<br />
Width of scroll elt:<span id='scrollwidth'>0</span>px<br />
</form>
</body>
</html>
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-8263127429141333702014-08-29T10:49:00.000+05:302014-08-29T11:10:28.164+05:30How to create multilevel menu's in JSP using recursion..There was a requirement where in I need to create multi-level menu's in a JSP <br />
<br />
A role has certain set of Privileges.<br />
Each privilege may or may not have child privileges..<br />
<br />
Where Privilege has child privileges, it was desired to display a sub menu..<br />
<br />
So this is how I have achieved...<br />
First thing you need to know about this is how to create multi level menu's using HTML and CSS.<br />
(<a href="http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html">http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html</a>)<br />
<br />
and once you learn that you'll have to use recursion in JSP to achieve the above requirement.<br />
<br />
I'll just put the core logic here which is the base of this..<br />
<br />
Create a parent jsp (lets say LoginSuccess.jsp)<br />
<br />
<pre class="brush:java"><ul id="nav">
<c:forEach var="role" items="${userDbObject.roles}">
<li><a href="#item1">${role.roleName}</a>
<ul>
<c:forEach var="priv" items="${role.privileges}">
<c:set value="${priv}" var="myPriv" scope="request"/>
<jsp:include page="showPrivileges.jsp"/>
</c:forEach>
</ul>
</li>
</c:forEach>
</ul>
</pre><br />
<br />
Create a showPrivileges.jsp as follows:<br />
<br />
<pre class="brush:java"><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty myPriv.childPrivileges}">
<c:set var="url" value="${myPriv.privUrl}" />
<c:if test="${not empty url}">
<li><a href="${url}" >${myPriv.privilegeName}</a></li>
</c:if>
<c:if test="${empty url}">
<li><a href="unimplemented.jsp" >unimplemented.jsp</a></li>
</c:if>
</c:if>
<c:if test="${not empty myPriv.childPrivileges}">
<li><a href="#" >${myPriv.privilegeName}</a>
<ul>
<c:forEach var="childPriv" items="${myPriv.childPrivileges}">
<c:set value="${childPriv}" var="myPriv" scope="request"/>
<jsp:include page="showPrivileges.jsp"/>
</c:forEach>
</ul>
</li>
</c:if>
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-74278978254606058742014-08-28T15:21:00.002+05:302014-08-29T10:40:22.425+05:30How to create multi-level menu's using HTML and CSS<p class="heading">Create a style.css as follows</p><div class="collapsingdiv"><pre class="brush:css">body {
font: normal .8em/1.5em Arial, Helvetica, sans-serif;
background: #ebebeb;
width: 900px;
margin: 100px auto;
color: #666;
}
a {
color: #333;
}
#nav {
margin: 0;
padding: 7px 6px 0;
/*background: #7d7d7d repeat-x 0 -110px;*/
background:#7d7d7d;
line-height: 100%;
border-radius: 2em;
-webkit-border-radius: 2em;
-moz-border-radius: 2em;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4);
-moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
/* main level link */
#nav a {
font-weight: bold;
color: #e7e5e5;
text-decoration: none;
display: block;
padding: 8px 20px;
margin: 0;
-webkit-border-radius: 1.6em;
-moz-border-radius: 1.6em;
text-shadow: 0 1px 1px rgba(0,0,0, .3);
}
#nav a:hover {
background: #000;
color: #666;
}
/* main level link hover */
#nav .current a, #nav li:hover > a {
background: #000 ;
color: #fff;
border-top: normal 0px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2);
-moz-box-shadow: 0 1px 1px rgba(0,0,0, .2);
box-shadow: 0 1px 1px rgba(0,0,0, .2);
text-shadow: 0 0px 0 rgba(255,255,255, 1);
}
/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
background: none;
border: none;
color: #666;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
#nav ul a:hover {
background: #0078ff repeat-x 0 -100px !important;
color: #fff !important;
-webkit-border-radius: 0;
-moz-border-radius: 0;
text-shadow: 0 0px 0px rgba(0,0,0, .1);
}
/* dropdown */
#nav li:hover > ul {
display: block;
}
/* level 2 list */
#nav ul {
display: none;
margin: 0;
padding: 0;
width: 185px;
position: absolute;
top: 35px;
left: 0;
background: #ddd repeat-x 0 0;
border: solid 1px #b4b4b4;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3);
-moz-box-shadow: 0 1px 3px rgba(0,0,0, .3);
box-shadow: 0 1px 3px rgba(0,0,0, .3);
}
#nav ul li {
float: none;
margin: 0;
padding: 0;
}
#nav ul a {
font-weight: normal;
text-shadow: 0 1px 0 #fff;
}
/* level 3+ list */
#nav ul ul {
left: 181px;
top: -3px;
}
/* rounded corners of first and last link */
#nav ul li:first-child > a {
-webkit-border-top-left-radius: 9px;
-moz-border-radius-topleft: 9px;
-webkit-border-top-right-radius: 9px;
-moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a {
-webkit-border-bottom-left-radius: 9px;
-moz-border-radius-bottomleft: 9px;
-webkit-border-bottom-right-radius: 9px;
-moz-border-radius-bottomright: 9px;
}
/* clearfix */
#nav:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#nav {
display: inline-block;
}
html[xmlns] #nav {
display: block;
}
* html #nav {
height: 1%;
}
</pre></div><br />
<p class="heading">Create body of your HTML as follows</p><div class="collapsingdiv"><pre class="brush:html">
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Navigation -->
<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#">Categories</a>
<ul>
<li><a href="#">All</a>
<ul>
<li><a href="#">Category 1</a>
<ul class="droprightMenu">
<li>
<a href="#">Category 1.2</a>
<ul>
<li><a href="#">Category 1.2.1</a></li>
</ul>
</li>
<li>
<a href="#">Category 1.3</a>
<ul>
<li><a href="#">Category 1.3.1</a></li>
</ul>
</li>
<li><a href="#">Category 1.4</a></li>
</ul>
</li>
<li><a href="#">Category 2</a></li>
<li><a href="#">Category 3</a></li>
<li><a href="#">Category 4</a></li>
</ul>
</li>
<li><a href="#">Manage</a></li>
</ul>
</li>
<li><a href="#">Profile</a>
<ul>
<li><a href="#">Login</a></li>
<li><a href="#">Register</a></li>
<li><a href="#">Edit Profile</a></li>
<li><a href="#">My Posts</a></li>
<li><a href="#">Logout</a></li>
</ul>
</li>
<li><a href="#">Help</a></li>
</ul>
</body>
</pre></div><br />
And the output will look like:<br />
<br />
<style>
body {
font: normal .8em/1.5em Arial, Helvetica, sans-serif;
background: #ebebeb;
width: 900px;
margin: 100px auto;
color: #666;
}
a {
color: #333;
}
#nav {
margin: 0;
padding: 7px 6px 0;
/*background: #7d7d7d repeat-x 0 -110px;*/
background:#7d7d7d;
line-height: 100%;
border-radius: 2em;
-webkit-border-radius: 2em;
-moz-border-radius: 2em;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4);
-moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
/* main level link */
#nav a {
font-weight: bold;
color: #e7e5e5;
text-decoration: none;
display: block;
padding: 8px 20px;
margin: 0;
-webkit-border-radius: 1.6em;
-moz-border-radius: 1.6em;
text-shadow: 0 1px 1px rgba(0,0,0, .3);
}
#nav a:hover {
background: #000;
color: #666;
}
/* main level link hover */
#nav .current a, #nav li:hover > a {
background: #000 ;
color: #fff;
border-top: normal 0px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2);
-moz-box-shadow: 0 1px 1px rgba(0,0,0, .2);
box-shadow: 0 1px 1px rgba(0,0,0, .2);
text-shadow: 0 0px 0 rgba(255,255,255, 1);
}
/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
background: none;
border: none;
color: #666;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
#nav ul a:hover {
background: #0078ff repeat-x 0 -100px !important;
color: #fff !important;
-webkit-border-radius: 0;
-moz-border-radius: 0;
text-shadow: 0 0px 0px rgba(0,0,0, .1);
}
/* dropdown */
#nav li:hover > ul {
display: block;
}
/* level 2 list */
#nav ul {
display: none;
margin: 0;
padding: 0;
width: 185px;
position: absolute;
top: 35px;
left: 0;
background: #ddd repeat-x 0 0;
border: solid 1px #b4b4b4;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3);
-moz-box-shadow: 0 1px 3px rgba(0,0,0, .3);
box-shadow: 0 1px 3px rgba(0,0,0, .3);
}
#nav ul li {
float: none;
margin: 0;
padding: 0;
}
#nav ul a {
font-weight: normal;
text-shadow: 0 1px 0 #fff;
}
/* level 3+ list */
#nav ul ul {
left: 181px;
top: -3px;
}
/* rounded corners of first and last link */
#nav ul li:first-child > a {
-webkit-border-top-left-radius: 9px;
-moz-border-radius-topleft: 9px;
-webkit-border-top-right-radius: 9px;
-moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a {
-webkit-border-bottom-left-radius: 9px;
-moz-border-radius-bottomleft: 9px;
-webkit-border-bottom-right-radius: 9px;
-moz-border-radius-bottomright: 9px;
}
/* clearfix */
#nav:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#nav {
display: inline-block;
}
html[xmlns] #nav {
display: block;
}
* html #nav {
height: 1%;
}
</style><br />
<ul id="nav"><li><a href="#">Home</a></li>
<li><a href="#">Categories</a> <br />
<ul><li><a href="#">All</a> <br />
<ul><li><a href="#">Category 1</a> <br />
<ul><li><br />
<a href="#">Category 1.2</a><br />
<ul><li><a href="#">Category 1.2.1</a></li>
</ul></li>
<li><br />
<a href="#">Category 1.3</a><br />
<ul><li><a href="#">Category 1.3.1</a></li>
</ul></li>
<li><a href="#">Category 1.4</a></li>
</ul></li>
<li><a href="#">Category 2</a></li>
<li><a href="#">Category 3</a></li>
<li><a href="#">Category 4</a></li>
</ul></li>
<li><a href="#">Manage</a></li>
</ul></li>
<li><a href="#">Profile</a> <br />
<ul><li><a href="#">Login</a></li>
<li><a href="#">Register</a></li>
<li><a href="#">Edit Profile</a></li>
<li><a href="#">My Posts</a></li>
<li><a href="#">Logout</a></li>
</ul></li>
<li><a href="#">Help</a></li>
</ul><br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com3tag:blogger.com,1999:blog-2322739097068009391.post-13719740264529779632014-08-26T16:32:00.003+05:302014-08-26T16:34:49.372+05:30How to implement a self join in hibernateSource : <a href="http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/">http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/</a><br />
<br />
We have a create table in the database.<br />
<br />
CREATE TABLE employee (<br />
employee_id NUMBER(10) NOT NULL,<br />
firstname VARCHAR2(50) NULL DEFAULT NULL,<br />
lastname VARCHAR(50) NULL DEFAULT NULL,<br />
manager_id NUMBER(10) NULL DEFAULT NULL,<br />
PRIMARY KEY ('employee_id'),<br />
CONSTRAINT 'FK_MANAGER' FOREIGN KEY ('manager_id') REFERENCES 'employee' ('employee_id')<br />
);<br />
<br />
Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table’s primary key. Thus for each employee we will store its manager’s id also. Manager will be yet another employee in this table<br />
<br />
We will be using annotations to implement this in hibernate:<br />
<br />
<br />
<pre class="brush:java">@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@Column(name="EMPLOYEE_ID")
@GeneratedValue
private Long employeeId;
@Column(name="FIRSTNAME")
private String firstname;
@Column(name="LASTNAME")
private String lastname;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="manager_id")
private Employee manager;
@OneToMany(mappedBy="manager")
private Set<Employee> subordinates = new HashSet<Employee>();
public Employee() {
}
public Employee(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
// Getter and Setter methods
}
</pre><br />
<br />
Note that in Employee entity class, we defined two new attributes: Employee manager and Set<employee> subordinates. Attribute manager is mapped with @ManyToOne annotation and subordinates is mapped with @OneToMany. Also within @OneToMany attribute we defined mappedBy="manager" making manager as the relationship owner and thus which manages the foreign relationship within table.<br />
<br />
Also the annotation @JoinColumn is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is manager_id.<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-34892368038154168712014-08-25T13:41:00.000+05:302014-08-25T13:42:13.681+05:30How to integrate Spring and HibernateHere are the few tips I have gathered on how to integrate spring and hibernate.<br />
<br />
<p class="heading">Create your bean.xml something like this...</p><div class="collapsingdiv"><pre class="brush:xml"><?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-3.0.xsd">
<bean id="usrMgmtServiceImpl" class="com.usermanagement.service.impl.UserManagementServiceImpl">
<property name="privService" ref="privService"/>
<property name="roleService" ref="roleService"/>
<property name="userService" ref="userService"/>
</bean>
<!-- DB CONFIGURATION BEGINS -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>Connection.properties</value></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${db.driverClassName}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- These are the POJO objects, you have to mention these here... -->
<property name="annotatedClasses">
<list>
<value>com.usermanagement.pojo.User</value>
<value>com.usermanagement.pojo.Role</value>
<value>com.usermanagement.pojo.Privilege</value>
<value>com.usermanagement.pojo.Password</value>
<value>com.usermanagement.pojo.PasswordPolicy</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!--<prop key="hibernate.cache.provider_class">org.hibernate.cache.SingletonEhCacheProvider</prop>-->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<!-- DB CONFIGURATION ENDS -->
<bean id="privService" class="com.usermanagement.service.impl.PrivilegeServiceImpl">
<property name="privDao" ref="privDao"/>
</bean>
<bean id="roleService" class="com.usermanagement.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<bean id="userService" class="com.usermanagement.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="privDao" class="com.usermanagement.dao.impl.PrivilegeDAOImpl" >
<property name="template" ref="template"></property>
</bean>
<bean id="roleDao" class="com.usermanagement.dao.impl.RoleDAOImpl" >
<property name="template" ref="template"></property>
</bean>
<bean id="userDao" class="com.usermanagement.dao.impl.UserDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
</pre></div><br />
The list of jars that you might need are<br />
<ol><li>antlr-2.7.6.jar<br />
<li>asm-1.5.3.jar<br />
<li>axis2-spring-1.6.1.jar<br />
<li>cglib-2.1_3.jar<br />
<li>commons-collections-3.1.jar<br />
<li>commons-dbcp-1.4.jar<br />
<li>commons-logging-1.0.4.jar<br />
<li>commons-pool-1.6.jar<br />
<li>dom4j-1.6.1.jar<br />
<li>hibernate-3.2.0.ga.jar<br />
<li>hibernate-3.2.6.jar<br />
<li>hibernate-annotations-3.4.0.GA.jar<br />
<li>hibernate-commons-annotations-3.1.0.GA.jar<br />
<li>hibernate-core-3.3.0.SP1.jar<br />
<li>hibernate-entitymanager.jar<br />
<li>hibernate-jpa-2.0-api-1.0.0.Final.jar<br />
<li>jta-1.1.jar<br />
<li>log4j-1.2.14.jar<br />
<li>ojdbc14.jar<br />
<li>org.springframework.asm-3.0.0.RELEASE.jar<br />
<li>org.springframework.beans-3.0.0.RELEASE.jar<br />
<li>org.springframework.context-3.0.0.RELEASE.jar<br />
<li>org.springframework.core-3.0.0.RELEASE.jar<br />
<li>org.springframework.expression-3.0.0.RELEASE.jar<br />
<li>org.springframework.jdbc-3.0.0.RELEASE.jar<br />
<li>org.springframework.orm-3.0.0.RELEASE.jar<br />
<li>org.springframework.web.servlet-3.0.1.RELEASE-A.jar<br />
<li>slf4j-api-1.6.1.jar<br />
<li>spring-tx-3.0.0.RELEASE.jar<br />
</ol><br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-6334206753222803782014-07-30T11:36:00.000+05:302014-10-06T15:58:45.365+05:30Two player game program - e.g. TIC TAC TOE...<div dir="ltr" style="text-align: left;" trbidi="on"><div class="heading">This is an abstract State class</div><div class="collapsingdiv"><pre class="brush:java">public abstract class State {
// This method is abstract, the extending class has to give the implementation
// It will return a list of all the possible children from the current state.
public abstract List<State> getChildren();
public abstract String getTurn();
public abstract void setTurn(String turn);
// Find out who is the winner from the current state.
public abstract String getWinner();
// Check if the game has been finished or not.
public abstract boolean isGameOver();
// I have given the implementation specifically for TIC-TAC-TOE.
// You can override this functionality in the extending class according to your game requirements.
//
// This function will give the score of the current state.
// Then you can compare it with its siblings to check which state will be better to move to..
//
public int minimax()
{
if(!getWinner().equals(""))
{
if("X".equalsIgnoreCase(getWinner()))
{
return 1;
}
if("O".equalsIgnoreCase(getWinner()))
{
return -1;
}
if("draw".equalsIgnoreCase(getWinner()))
{
return 0;
}
}
List<State> children = getChildren();
if(getTurn().equals("X"))
{
int maxScore = -100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore > maxScore)
{
maxScore = childScore;
}
}
return maxScore;
}
else
{
int minScore = 100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore < minScore)
{
minScore = childScore;
}
}
return minScore;
}
}
}
</pre></div><br />
Extend the above State class and give some implementations...as follows:<br />
Lets assume the class to be TttState...<br />
We'll override the abstract methods of the parent class State..<br />
<br />
Give a member variable that'll hold the current state of your game...In my case, I have taken it as array..<br />
<br />
<pre class="brush:java">// This variable is going to hold the current state of your game.
// It can be any depending on your game requirements...
private String state[][] = null ;
</pre><br />
Give a copy constructor<br />
<br />
<pre class="brush:java">public TttState(State x)
{
TttState tState = (TttState)x;
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]=tState.state[i][j];
}
}
this.turn = x.getTurn();
}
</pre>Give a default constructor <br />
<pre class="brush:java">public TttState() {
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]="";
}
}
this.turn = "X";
}
</pre>Give a toString implementation, so that you can print the current state <br />
<pre class="brush:java">public String toString()
{
StringBuilder sb = new StringBuilder("");
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
sb.append("-");
}
else
{
sb.append(state[i][j]);
}
sb.append("\t");
}
sb.append("\n");
}
return sb.toString();
}
</pre>Override the method getWinner() as follows <br />
<pre class="brush:java">public String getWinner()
{
// ROW CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[0][1].equalsIgnoreCase("X") && state[0][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[0][1].equalsIgnoreCase("O") && state[0][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[1][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[1][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[2][0].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[2][0].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}
// COLUMN CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[1][0].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][0].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][1].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][1].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][2].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}
// DIAGNONAL CHECKS
if(state[0][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][2].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
int nonBlank = 0;
for(int i=0;i<=2;i++)
{
for(int j=0;j<=2;j++)
{
if(!state[i][j].equals(""))
{
nonBlank++;
}
}
}
if(nonBlank==9)
{
return "draw";
}
return "";
}
</pre>Override the method isGameOver() <br />
<pre class="brush:java">public boolean isGameOver()
{
if(!getWinner().equals("") && !getWinner().equals("draw"))
{
return true;
}
else
{
return false;
}
}
</pre>Override the method getChildren() <br />
<pre class="brush:java">@Override
public List<State> getChildren() {
List<State> children = new ArrayList<State>();
if(turn.equals("X"))
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="X";
String newTurn = "O";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
else
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="O";
String newTurn = "X";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
return children;
}
</pre>Override getTurn and setTurn <br />
<pre class="brush:java">public String getTurn() {
return turn;
}
public void setTurn(String turn) {
this.turn = turn;
}
</pre>Your main program will look something like this: <br />
<pre class="brush:java">public static void main(String args[])
{
TttState x = new TttState();
System.out.println("WINNER : " + x.getWinner());
x.setTurn("X");
Scanner sc = new Scanner(System.in);
while(!x.isGameOver())
{
String xIndex = sc.nextLine();
String yIndex = sc.nextLine();
int xint = Integer.parseInt(xIndex);
int yint = Integer.parseInt(yIndex);
x.getState()[xint][yint]="X";
x.setTurn("O");
int minScore = 100;
List<State> children = x.getChildren();
TttState bestMove = new TttState(x);
for(State child : children)
{
int childScore = child.minimax();
// We are using < because we are always evaluating
// the best move from the options that O player has....
if(childScore < minScore)
{
minScore = childScore;
bestMove = (TttState)child;
bestMove.setTurn("X");
}
}
System.out.print(bestMove);
x = bestMove;
}
System.out.println("GAME OVER...");
}
</pre><br />
<br />
</div>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-52697775014003449802014-07-07T13:01:00.000+05:302014-07-07T13:01:01.581+05:30Things to remember while creating Custom Exception in JavaThings to remember while creating Custom Exception in Java<br />
<br />
1) Don’t' use Exception to control application behaviour. Exception handling is very expensive as it require native calls to copy stacktrace, each time exception is created.<br />
<br />
2) While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception, especially if you know that client is not going to take any reactive action other than logging.<br />
<br />
3) If your custom exception is created by passing another exception, then always contain original Exception as source; use constructor which takes Exception rather than only message String.<br />
<br />
4) Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.<br />
<br />
5) If possible avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself. Most of the time you will realize that all you need is a form of IllegalArgumentException or ParseException or something similar.<br />
<br />
6) While defining custom Exception, one of the most common mistake programmer make is to think that constructor is inherited from java.lang.Exception class, for example they think that their Exception class will automatically inherit default no argument constructor and the one which takes a String message. This is not true. Constructor is not inherited in Java, not even default constructor. It's actually added by compiler rather than inherited from parent class. That's why I have declared two constructor, one with String parameter and other as Throwable parameter :<br />
<br />
<pre class="brush:java">public NoSuchProductException(String message, int productId)
{
super(message);
this.productId = productId;
}
public NoSuchProductException(String message, int productId, Throwable cause)
{
super(message, cause);
this.productId = productId;
}
</pre><br />
This is actually standard way of creating custom Exception in Java. In order to save time, you can even create template of above class in Eclipse IDE.<br />
<br />
7) For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword, name it IncorrectPasswordException.<br />
<br />
There is lot more given on the following link:<br />
<a href="http://javarevisited.blogspot.in/2014/06/how-to-create-custom-exception-in-java.html">http://javarevisited.blogspot.in/2014/06/how-to-create-custom-exception-in-java.html</a><br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com1tag:blogger.com,1999:blog-2322739097068009391.post-53884694842911543822014-07-07T12:50:00.001+05:302018-09-16T16:02:30.746+05:30How to use decorator pattern, when the class to decorate is finalI have an inbuilt class in java - String<br />
Now I have made 3 classes <br />
<ol><li>AddHashCode</li>
<li>ToLowerCase</li>
<li>AddLength</li>
</ol><br />
<br />
I want to create a class, which has toString method overridden while selecting one or more of the above classes.<br />
<br />
For example:<br />
I want a class, which has toString method, which has the features of AddHashCode and ToLowerCase<br />
or<br />
I want a class, which has toString method, which has the features of all of the above classes.<br />
<br />
So, lets do it with Decorator Pattern.<br />
<br />
But the problem with Decorator Pattern is, that the classes you create must implement the String class.....But String class is final..<br />
So I have tweaked the Decorator Design Pattern a bit, though it closely resembles the purpose of Decorator design pattern.<br />
<br />
Create the following three classes<br />
<p class="heading">Class AddHashCode</p><div class="collapsingdiv"><pre class="brush:java">public class AddHashCode {
private String t ;
public AddHashCode(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":" + t.hashCode();
}
}
</pre></div><br />
<p class="heading">Class ToLowerCase</p><div class="collapsingdiv"><pre class="brush:java">public class ToLowerCase {
String ac;
public ToLowerCase(String ac)
{
this.ac = ac;
}
public String toString()
{
return ac.toString().toLowerCase();
}
}
</pre></div><br />
<p class="heading">Class AddLength</p><div class="collapsingdiv"><pre class="brush:java">public class AddLength{
private String t ;
public AddLength(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":"+t.toString().length();
}
}
</pre></div><br />
Use this as follows:<br />
<pre class="brush:java">public class Main {
public static void main(String[] args)
{
// Limitation and difference here will be, that on the LHS, the class used is ToLowerCase
// and cannot be a String as was the case with usual Decorators.
ToLowerCase x = new ToLowerCase
(new AddHashCode
(new String("YOGESH").toString()).toString());
System.out.println(x.toString());
AddHashCode y = new AddHashCode
(new ToLowerCase
(new AddLength(new String("YOGESH").toString())
.toString())
.toString());
System.out.println(y.toString());
}
}
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-23849991846155289052014-03-21T12:11:00.001+05:302014-03-21T12:18:12.208+05:30How to make a dropdown as readonly in htmlI encountered a problem where in it was required to make a drop down readonly.<br />
<br />
While searching over internet i found <a href="http://www.geekgumbo.com/2011/02/12/html-disabled-or-readonly/">THIS</a><br />
But the solution mentioned there, didn't appeal me much. As i had to make server side code changes while saving the value using the hidden field.<br />
<br />
How do we do this? The common thought is to disable the drop down menu. Well, yes, but there's a choice<br />
<br />
When you use disabled, it prevents the user from using the drop down, or form element. You can see the year, but it is grayed out. Your mouse can't select or change it, and you can't tab to it with the keyboard. Disabled is used a lot with checkboxes. Sounds like just what we want, but you unknowingly might have caused yourself a small development problem.<br />
<br />
The problem is "disabled" does just that. Disabled means that in your $_POST or $_GET that element will not show up in your controller. If you want to use the year in your controller, you won't be able to recover it from that form. All you can do it look at the value on the web page.<br />
<br />
What if we want to read the year, prevent the user from changing the year, and recover the year in the form data sent back to the controller. The solution for this is<br />
<br />
Make a replica of your dropdown with a different name and different id.<br />
<br />
Hide your original drop down with <span style="display:none"><br />
This makes the element available in the form, so it will flow to the server side as well.<br />
At the same time, it will give a look and feel of disabled to the user.<br />
<br />
Example :<br />
<br />
<pre class="brush:java"><span style="display:none">
<select style="width:400px;" name="agentName">
<option value="${coltuserprofile.belongsToOcn}">
<c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
</option>
</select>
</span>
<select style="width:400px;" name="agentNameDisplay" disabled="disabled">
<option value="${coltuserprofile.belongsToOcn}">
<c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
</option>
</select>
</pre><br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-71146264771850844922014-03-07T15:46:00.002+05:302014-03-07T16:12:30.298+05:30Exception handling in javaThanks to <a href="https://today.java.net/article/2006/04/04/exception-handling-antipatterns#antipatterns">https://today.java.net/article/2006/04/04/exception-handling-antipatterns#antipatterns</a><br />
<br />
<p class="heading">Basic Exception Concepts</p><div class="collapsingdiv">One of the most important concepts about exception handling to understand is that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.<br />
<br />
Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an "in your face" type of exceptions. A checked exception indicates an expected problem that can occur during normal system operation. Some examples are problems communicating with external systems, and problems with user input. Note that, depending on your code's intended function, "user input" may refer to a user interface, or it may refer to the parameters that another developer passes to your API. Often, the correct response to a checked exception is to try again later, or to prompt the user to modify his input.<br />
<br />
Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code. The most common example is a NullPointerException. There are many core exceptions in the JDK that are checked exceptions but really shouldn't be, such as IllegalAccessException and NoSuchMethodException. An unchecked exception probably shouldn't be retried, and the correct response is usually to do nothing, and let it bubble up out of your method and through the execution stack. This is why it doesn't need to be declared in a throws clause. Eventually, at a high level of execution, the exception should probably be logged (see below).<br />
<br />
Errors are serious problems that are almost certainly not recoverable. Some examples are <b>OutOfMemoryError, LinkageError, and StackOverflowError.</b><br />
</div><br />
<p class="heading">Creating Your Own Exceptions</p><div class="collapsingdiv">Most packages and/or system components should contain one or more custom exception classes. There are two primary use cases for a custom exception. First, your code can simply throw the custom exception when something goes wrong. For example:<br />
<br />
<pre class="brush:java">throw new MyObjectNotFoundException("Couldn't find object id " + id);
</pre><br />
Second, your code can wrap and throw another exception. For example:<br />
<br />
<pre class="brush:java">catch (NoSuchMethodException e)
{
throw new MyServiceException("Couldn't process request", e);
}
</pre><br />
Wrapping an exception can provide extra information to the user by adding your own message (as in the example above), while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions. For instance, look at the Hibernate API. Even though Hibernate makes extensive use of JDBC in its implementation, and most of the operations that it performs can throw SQLException, Hibernate does not expose SQLException anywhere in its API. Instead, it wraps these exceptions inside of various subclasses of HibernateException. Using the approach allows you to change the underlying implementation of your module without modifying its public API.<br />
</div><br />
<h3>Antipatterns</h3><br />
<p class="heading">Log and Throw</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e)
{
LOG.error("Blah", e);
throw e;
}
catch (NoSuchMethodException e)
{
LOG.error("Blah", e);
throw new MyServiceException("Blah", e);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
throw new MyServiceException("Blah", e);
}
</pre>All of the above examples are equally wrong. This is one of the most annoying error-handling antipatterns. Either log the exception, or throw it, but never do both. Logging and throwing results in multiple log messages for a single problem in the code, and makes life hell for the support engineer who is trying to dig through the logs.<br />
</div><br />
<p class="heading">Throwing Exception</p><div class="collapsingdiv"><pre class="brush:java">public void foo() throws Exception { </pre><br />
This is just sloppy, and it completely defeats the purpose of using a checked exception. It tells your callers "something can go wrong in my method." Real useful. Don't do this. Declare the specific checked exceptions that your method can throw. If there are several, you should probably wrap them in your own exception (see "Throwing the Kitchen Sink" below.)<br />
</div><br />
<p class="heading">Throwing the Kitchen Sink</p><div class="collapsingdiv">Example:<br />
<br />
<pre class="brush:java">public void foo() throws MyException,
AnotherException, SomeOtherException, YetAnotherException{
</pre><br />
Throwing multiple checked exceptions from your method is fine, as long as there are different possible courses of action that the caller may want to take, depending on which exception was thrown. If you have multiple checked exceptions that basically mean the same thing to the caller, wrap them in a single checked exception.<br />
</div><br />
<p class="heading">Catching Exception</p><div class="collapsingdiv"><pre class="brush:java">try
{
foo();
}
catch (Exception e)
{
LOG.error("Foo failed", e);
}
</pre><br />
This is generally wrong and sloppy. Catch the specific exceptions that can be thrown. The problem with catching Exception is that if the method you are calling later adds a new checked exception to its method signature, the developer's intent is that you should handle the specific new exception. If your code just catches Exception (or worse, Throwable), you'll probably never know about the change and the fact that your code is now wrong.<br />
</div><br />
<p class="heading">Destructive Wrapping</p><div class="collapsingdiv"><pre class="brush:java">catch (NoSuchMethodException e)
{
throw new MyServiceException("Blah: " + e.getMessage());
}
</pre><br />
This destroys the stack trace of the original exception, and is always wrong.<br />
</div><br />
<p class="heading">Log and Return Null</p><div class="collapsingdiv">Example:<br />
<br />
<pre class="brush:java">catch (NoSuchMethodException e)
{
LOG.error("Blah", e);
return null;
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
return null;
}
</pre><br />
Although not always incorrect, this is usually wrong. Instead of returning null, throw the exception, and let the caller deal with it. You should only return null in a normal (non-exceptional) use case (e.g., "This method returns null if the search string was not found.").<br />
</div><br />
<p class="heading">Catch and Ignore</p><div class="collapsingdiv">Example:<br />
<br />
<pre class="brush:java">catch (NoSuchMethodException e)
{
return null;
}
</pre><br />
This one is insidious. Not only does it return null instead of handling or re-throwing the exception, it totally swallows the exception, losing the information forever.<br />
</div><br />
<p class="heading">Throw from Within Finally</p><div class="collapsingdiv">Example:<br />
<pre class="brush:java">try
{
blah();
}
finally
{
cleanUp();
}
</pre><br />
This is fine, as long as cleanUp() can never throw an exception. In the above example, if blah() throws an exception, and then in the finally block, cleanUp() throws an exception, that second exception will be thrown and the first exception will be lost forever. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it bubble out of the finally block.<br />
<br />
</div><br />
<p class="heading">Multi-Line Log Messages</p><div class="collapsingdiv">Example:<br />
<pre class="brush:java">LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");
</pre><br />
Always try to group together all log messages, regardless of the level, into as few calls as possible. So in the example above, the correct code would look like:<br />
<br />
<pre class="brush:java">LOG.debug("Using cache policy A, using retry policy B");
</pre><br />
Using a multi-line log message with multiple calls to log.debug() may look fine in your test case, but when it shows up in the log file of an app server with 500 threads running in parallel, all spewing information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.<br />
</div><br />
<p class="heading">Unsupported Operation Returning Null</p><div class="collapsingdiv">Example:<br />
<pre class="brush:java">public String foo()
{
// Not supported in this implementation.
return null;
}
</pre><br />
When you're implementing an abstract base class, and you're just providing hooks for subclasses to optionally override, this is fine. However, if this is not the case, you should throw an UnsupportedOperationException instead of returning null. This makes it much more obvious to the caller why things aren't working, instead of her having to figure out why her code is throwing some random NullPointerException<br />
</div><br />
<br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-75735568303275282692014-03-05T14:57:00.001+05:302014-03-05T15:02:21.074+05:30In JSTL/JSP when do I have to use and when can I just say ${myVar}Source : <a href="http://stackoverflow.com/questions/6574776/in-jstl-jsp-when-do-i-have-to-use-cout-value-myvar-and-when-can-i-just">http://stackoverflow.com/questions/6574776/in-jstl-jsp-when-do-i-have-to-use-cout-value-myvar-and-when-can-i-just</a><br />
<br />
<h3>In JSTL/JSP when do I have to use <c:out value="${myVar}"/> and when can I just say ${myVar}</h3><br />
I've been doing this the whole time in my JSP code:<br />
<pre class="brush:java"><c:out value="${myVar}"/>
</pre><br />
Today I just realized for the first time that I seem to be able to use this shorter version just as well:<br />
<pre class="brush:java">${myVar}</pre><br />
It works without <c:out>!<br />
<br />
Perhaps this is because my page is declared like this:<br />
<br />
<pre class="brush:java"><%@ page language="java" contentType="text/html;
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>
</pre><br />
So, my question is, can I replace <c:out> in my code with this shorter version? Is there any reason to keep using <c:out>? Or are there places where I might still need it?<br />
<br />
<b>Solution:</b><br />
<br />
<br />
<c:out> does more than simply outputting the text. It escapes the HTML special chars. <br />
Use it (or ${fn:escapeXml()}) every time you're not absolutely sure that the text doesn't contain any of these characters: ", ', <, >, &. Else, you'll have invalid HTML (in the best case), a broken page, or cross-site scripting attacks (in the worst case).<br />
<br />
I'll give you a simple example so that you understand. <br />
If you develop a forum, and someone posts the following message, and you don't use <c:out> to display this message, you'll have a problem:<br />
<br />
<pre class="brush:java"><script>while (true) alert("you're a loser");</script>
</pre><br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-73270673803954000272014-03-03T15:26:00.000+05:302014-03-03T15:28:08.017+05:30duplicate import try, using auto-import="false"<b>How to use same entity class in two different packages in hibernate?</b><br />
<br />
<br />
Source : <a href="http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/">http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/</a><br />
<br />
<h4>Using Hibernate and JPA you cannot have two classes with the same name (on different packages) mapped. This raise an error at runtime:<br />
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyClass refers to both <br />
</h4><br />
To solve this issue on the Entity annotation of com.intre.MyClass and com.dummy.Class add the property name.<br />
<br />
<pre class="brush:java">package com.intre;
@Entity(name = "com.intre.myclass")
@Table(name = "MyClass")
public class MyClass
package com.dummy;
@Entity(name = "com.dummy.myclass")
@Table(name = "MyClass")
public class MyClass
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-42203961513287108032014-02-26T15:10:00.001+05:302014-02-26T15:10:53.613+05:30SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.We were getting the below error in our project, when trying to invoke a web service.<br />
<br />
<pre>[Server:server-one] 07:29:12,927 ERROR [stderr] (http-/10.99.12.28:8080-13) org.springframework.ws.soap.client.SoapFaultClientException: [ISS.0088.9168] SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.
[Server:server-one] 07:29:12,928 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:384)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
[Server:server-one] 07:29:12,931 ERROR [stderr] (http-/10.99.12.28:8080-13) at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:370)
</pre><br />
<b>Solution:</b><br />
The solution lies in the configuration files used by spring.<br />
Here in our project, the version specified in this file was 1.2 where as the web service was expecting 1.1<br />
<br />
<pre class="brush:xml"><bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_11" />
</property>
</bean>
</pre><br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-30057973795405167382014-02-26T11:46:00.002+05:302014-02-26T11:46:59.605+05:30How to break a list into smaller sublists of equal size<pre class="brush:java">// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
</pre><br />
Usage:<br />
<pre class="brush:java">List<Integer> numbers = Collections.unmodifiableList(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-57736865038187937362014-02-24T16:42:00.002+05:302014-02-24T16:58:34.966+05:30Generate java classes using xjcSource : <a href="http://theopentutorials.com/examples/java/jaxb/generate-java-class-from-xml-schema-using-jaxb-xjc-command/">Generate java class from xml schema using jaxb xjc command</a><br />
<br />
<br />
Before using JAXB to create or access an XML document from Java application, we have to do the following steps:<br />
<br />
1.Binding the schema<br />
* Binding a schema means generating a set of Java classes that represents the schema for the XML document (Schema is not required for simple marshalling and unmarshalling).<br />
<br />
2.Marshal the content tree /Unmarshal the XML document.<br />
* After binding the schema, you can convert Java objects to and from XML document.<br />
In this example we will see how to bind the schema. For that, we use Java Architecture for XML Binding (JAXB) binding compiler tool, xjc, to generate Java classes from XML schema.<br />
<br />
<p class="heading">‘xjc’ Command Line Options</p><div class="collapsingdiv"><b>Usage:</b><br />
<quote><br />
xjc [-options ...] … [-b ] …<br />
If dir is specified, all schema files in it will be compiled.<br />
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.<br />
</quote><br />
<br />
Complete list of options for ‘xjc’ is available in the help option.<br />
<quote><br />
xjc -help<br />
</quote><br />
</div><b>Generate Java classes using ‘xjc’</b><br />
<br />
Follow the steps below to generate a set of Java source files from XML schema.<br />
<ol><li>Create a new Java project folder and name it as “JAXBXJCTool”.</li>
<li>Create a new XSD file and name it as “employee.xsd” and copy the following lines. This is the XML schema in our example which is to be bound to java classes</li>
<p class="heading">Employee.xsd</p><div class="collapsingdiv"><pre class="brush:xml"><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="employee" type="employee"/>
<xs:complexType name="employee">
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="salary" type="xs:double"/>
<xs:element name="designation" type="xs:string" minOccurs="0"/>
<xs:element name="address" type="address" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="id" type="xs:int" use="required"/>
</xs:complexType>
<xs:complexType name="address">
<xs:sequence>
<xs:element name="city" type="xs:string" minOccurs="0"/>
<xs:element name="line1" type="xs:string" minOccurs="0"/>
<xs:element name="line2" type="xs:string" minOccurs="0"/>
<xs:element name="state" type="xs:string" minOccurs="0"/>
<xs:element name="zipcode" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
</pre></div><li>Save the file</li>
<li>Create a new folder ‘src’ inside the project folder.</li>
<li>In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the project folder (use cd command) where it exists in your machine and type the following command</li>
<b><pre>C:\Users\iByteCode\Desktop\JAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd</pre></b>
<li>This will generate set of Java source files with appropriate annotation inside ‘src’ folder</li>
</ol><br />
<br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-78906255503423271292014-02-19T11:23:00.001+05:302014-02-19T11:29:48.523+05:30How to make ajax call in spring frameworkWrite a server side method, with a mapping something as follows:<br />
<br />
<br />
<pre class="brush:java">@RequestMapping("/getKids.html")
public @ResponseBody
String getChildren(@RequestParam(value = "ocn") String ocn,
HttpServletRequest request, HttpServletResponse response)
{
return ocn.toUpperCase();
}
</pre>Here @ResponseBody tells the framework to return value of the method to the browser and not lookup for a view with that name.<br />
You can optionally omit request and response parameters in the signature of the method, if you like to.<br />
<br />
After removal of request and response the method will look like<br />
<br />
<pre class="brush:java">@RequestMapping("/getKids.html")
public @ResponseBody
String getChildren(@RequestParam(value = "ocn") String ocn)
{
return ocn.toUpperCase();
}
</pre><br />
<br />
<br />
Write a javascript method as follows (This uses jquery to fire ajax request)<br />
<br />
<pre class="brush:js">function populateSubAgents(obj)
{
$.ajax({
url: "getKids.html?ocn="+obj.value,
success: function(data) {
$("#subAgentName").html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknown Error.\n' + XMLHttpRequest.responseText);
}
}
});
}
</pre><br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com1tag:blogger.com,1999:blog-2322739097068009391.post-83760415644985105532013-12-19T18:22:00.001+05:302013-12-19T18:22:18.517+05:30The selected file is a system file<p dir=ltr><b>Error</b>:</p>
<p dir=ltr> </p>
<p dir=ltr>The project was not built due to "Internal error - the selected file is a system file that cannot be modified. It will be hidden.". Fix the problem, then try refreshing this project and building it since it may be inconsistent</p>
<p dir=ltr> </p>
<p dir=ltr><b>Resolution</b>:<br></p>
<p dir=ltr>This a problem encountered when the Clear Case plugin is added to the eclipse and then the project is imported. <br>
Solution: <br>
By deleting the ".copyarea.db" in the bin directory of the concerned project would make it work. What is happening here is, when the project is trying to build, this particular file ".copyarea.db" (which is a read only file) stops it from executing. Once deleted physically going to the particular directory and then refreshing the project it would work.</p>
<p dir=ltr> </p>
<p dir=ltr>Link:</p>
<p dir=ltr>http://www.myeclipseide.com/PNphpBB2-printview-t-12987-start-0.html</p>
<p dir=ltr> Solution given by dewanvaibhavgarg@gmail.com</p>
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com1tag:blogger.com,1999:blog-2322739097068009391.post-56805987265225863202013-10-12T13:38:00.001+05:302013-10-12T13:41:07.377+05:30What is the difference between @RequestMapping's param attribute AND @RequestParamSource : <a href="http://www.captaindebug.com/2011/07/accessing-request-parameters-using.html#uds-search-results">http://www.captaindebug.com/2011/07/accessing-request-parameters-using.html#uds-search-results</a><br />
<br />
@RequestMapping is only used to map request URLs to your controller. <br />
The 'params' value is used to narrow the mapping down allowing you to map different param values <br />
(uuids in this case) to different methods. For example:<br />
<br />
<pre class="brush:java">/** This is only called when uuid=6 e.g.: /help/detail?uuid=6 */
@RequestMapping(value = "/help/detail", params={"uuid=6"}
method = RequestMethod.GET)
public String displaySomeHelpDetail(Model model) {
// Do Something
return "view.name"
}
</pre><br />
<pre class="brush:java">/** This is only called when uuid=1234 e.g.: /help/detail?uuid=1234 */
@RequestMapping(value = "/help/detail", params={"uuid=1234"}
method = RequestMethod.GET)
public String displaySomeHelpDetail(Model model) {
// Do Something Else
return "another.view.name"
}
</pre><br />
<br />
Whilst @RequestParam is used to pass request parameters into a method so that you can use them. <br />
For example:<br />
<br />
<pre class="brush:java">@RequestMapping(value = "/help/detail",
method = RequestMethod.GET)
public String displaySomeHelpDetail(@RequestParam("uuid") String uuid, Model model) {
log.info("The uuid = " + uuid);
return "view.name"
}
</pre>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-65558895209909581852013-09-24T16:02:00.002+05:302013-09-24T16:02:50.735+05:30Reading Flat files seperated by | symbolOften I have seen that there are files having lines seperated by a de-limiter |.<br />
I thought of making a class that could easily iterate over each of the line one by one..<br />
<br />
This class PipedString represents a string which has elements seperated by a | symbol.<br />
This is an iterable class<br />
<p class="heading">Create a class PipedString as follows</p><div class="collapsingdiv"><pre class="brush:java">package flatfilereader;
import java.util.Iterator;
public class PipedString implements Iterable<String> {
private String line;
private int index = 0;
@Override
public String toString()
{
return line;
}
public PipedString(String x) {
this.line = x;
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>()
{
private String _currentElement;
String[] symbols=null;
@Override
public boolean hasNext() {
try {
if(symbols==null)
{
symbols = line.split("\\|");
}
_currentElement = symbols[index];
} catch (Exception ex) {
line = null;
}
return (index < symbols.length);
}
@Override
public String next() {
index++;
return _currentElement;
}
@Override
public void remove() {
}
};
}
}
</pre></div><br />
<p class="heading">Now create a Flat File Reader using this PipedString</p><div class="collapsingdiv"><pre class="brush:java">package flatfilereader;
import java.util.*;
import java.io.*;
public class FlatFileReader implements Iterable<PipedString>
{
private BufferedReader _reader;
public FlatFileReader(String filePath) throws Exception
{
_reader = new BufferedReader(new FileReader(filePath));
}
public void Close()
{
try
{
_reader.close();
}
catch (Exception ex) {}
}
public Iterator<PipedString> iterator()
{
return new PipedStringIterator();
}
private class PipedStringIterator implements Iterator<PipedString>
{
private PipedString _currentLine;
public boolean hasNext()
{
try
{
String cl = _reader.readLine();
if(cl==null) return false;
_currentLine = new PipedString(cl);
}
catch (Exception ex)
{
_currentLine = null;
}
return _currentLine != null;
}
@Override
public PipedString next()
{
return _currentLine;
}
public void remove()
{
}
}
}
</pre></div><br />
<p class="heading">How to use this FlatFileReader class</p><div class="collapsingdiv"><pre class="brush:java"> public static void main(String[] s) throws Exception
{
FlatFileReader f= new FlatFileReader("D:/test/x.txt");
for(PipedString pps : f)
{
for(String eachElement : pps)
{
System.out.println(eachElement);
}
}
f.Close();
}
</pre></div><br />
<br />
Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-81781107005384171062013-09-14T10:33:00.000+05:302014-04-27T17:49:26.822+05:30A generic problem solver from State to GoalI thought of making a generic problem solver, which could solve any problem which has an initial state and a final state and a set of possible moves.<br />
<br />
Though my program is not perfect, but still it is able to give some learning and if you guys have suggestions to make it better, please feel free to write in comments.<br />
<br />
I have tried to use Template Design pattern here.. Where an algorithm is implemented in the abstract class with some parts left out to be implemented by the user.<br />
<br />
<p class="heading">Create a State interface</p><div class="collapsingdiv"><pre class="brush:java">package mystate;
import java.util.ArrayList;
import java.util.List;
public abstract class State
{
// Define a state that'll hold reference to predecessor.
public State predecessor = null;
public abstract boolean isGoal();
@Override
public abstract boolean equals(Object xx);
@Override
public abstract int hashCode();
public abstract List<State> getChildren() ;
@Override
public abstract String toString();
public State getPredecessor() {
return this.predecessor;
}
public void setPredecessor(State s) {
this.predecessor = s;
}
public void printResult()
{
List<State> result = new ArrayList<State>();
State c = this;
while(c.getPredecessor() !=null)
{
result.add(c.getPredecessor());
c=c.getPredecessor();
}
for(int i=result.size()-1;i>=0;i--)
{
State curr = result.get(i);
System.out.println(curr);
}
System.out.print(this);
}
}
</pre></div><br />
<br />
Now implement this abstract class and create a custom class that defines the state of your problem.<br />
Please make sure that you override all the methods given in the interface very correctly.<br />
Do make member variables that can signify your state.<br />
For example, let me take an example of 15-squred number puzzle<br />
<br />
<p class="heading">Implement the abstract class and create SlidingState class</p><div class="collapsingdiv"><pre class="brush:java">package mystate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Yogi
*/
public class SlidingState extends State {
int[][] currentState = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12},{0,13,14,15}};
public SlidingState()
{
}
// Provide constructors to initialize the state.
public SlidingState(int[][] state)
{
this.currentState = state;
}
@Override
public int hashCode()
{
return Arrays.deepHashCode(currentState);
}
// Be double sure that you override equals method correctly
// else you'll end up in infinite loop.
@Override
public boolean equals(Object xx)
{
if(xx==null) return false;
if(!(xx instanceof SlidingState))
{
return false;
}
return Arrays.deepEquals(this.currentState, ((SlidingState)xx).currentState);
}
@Override
public boolean isGoal() {
int[][] goalState = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}};
return Arrays.deepEquals(currentState, goalState);
}
@Override
public List<State> getChildren() {
List<State> children = new ArrayList<State>();
// First find where is the 0 in the grid
boolean found0=false;
int i=0;
int j=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(currentState[i][j]==0)
{
found0=true;
break;
}
}
if(found0) break;
}
List<Integer> moves = findMoves(i,j);
for(Integer m : moves)
{
int[][] newPosition = exchange(currentState, m);
State t = new SlidingState(newPosition);
t.setPredecessor(this);
children.add(t);
}
return children;
}
@Override
public String toString()
{
StringBuilder s = new StringBuilder("");
s.append("{\n");
for(int i=0;i<4;i++)
{
s.append("{");
for(int j=0;j<4;j++)
{
s.append(currentState[i][j]);
if(j!=3) s.append(",");
}
s.append("}");
}
s.append("\n}");
return s.toString();
}
private List<Integer> findMoves(int i, int j) {
List<Integer> moves = new ArrayList<Integer>();
try
{
moves.add(currentState[i+1][j]);
}
catch(Throwable t)
{
}
try
{
moves.add(currentState[i][j+1]);
}
catch(Throwable t)
{
}
try
{
moves.add(currentState[i][j-1]);
}
catch(Throwable t)
{
}
try
{
moves.add(currentState[i-1][j]);
}
catch(Throwable t)
{
}
return moves;
}
private int[][] exchange(int[][] currentState, Integer m) {
int i=0;
int j=0;
int mi=0;
int mj=0;
int[][] newPos = new int[4][4];
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
newPos[i][j]=currentState[i][j];
}
}
boolean find0 = false;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(newPos[i][j]==0)
{
find0=true;
break;
}
}
if(find0) break;
}
boolean findm=false;
for(mi=0;mi<4;mi++)
{
for(mj=0;mj<4;mj++)
{
if(newPos[mi][mj]==m.intValue())
{
findm=true;
break;
}
}
if(findm) break;
}
newPos[i][j]=m.intValue();
newPos[mi][mj]=0;
return newPos;
}
}
</pre></div><br />
Create a SolveProblem abstract class as follows<br />
<p class="heading">SolveProblem Abstract class</p><div class="collapsingdiv"><pre class="brush:java">package solution;
import mystate.State;
import java.util.Set;
import java.util.List;
public abstract class SolveProblem {
private java.util.Set<State> visitedStates;
public Set<State> getStateQueue() {
return stateQueue;
}
public void setStateQueue(Set<State> stateQueue) {
this.stateQueue = stateQueue;
}
public java.util.Set<State> getVisitedStates() {
return visitedStates;
}
public void setVisitedStates(java.util.Set<State> visitedStates) {
this.visitedStates = visitedStates;
}
private Set<State> stateQueue;
public abstract State getStateObject();
public SolveProblem()
{
// For visitedState, HashSet did work, because we are never
// retrieving from visitedStates, but checking only contains method.
visitedStates=new java.util.HashSet<State>();
// You have to use LinkedHashSet here, because, retrieval order must
// be same as insertion order... otherwise, it'll go into an infinite
// loop.
stateQueue = new java.util.TreeSet<State>();
}
public void bfs()
{
State currentState = getStateObject();
// Add current state to state Queue.
stateQueue.add(currentState);
do
{
// Get the first Element from Queue.
//Collections.sort(stateQueue);
State firstElementInQueue = stateQueue.iterator().next();//stateQueue.peek();
// If the first Element is the Goal
// We are done.
if(firstElementInQueue.isGoal())
{
firstElementInQueue.printResult();
// There is no recursion here, so simple return would do.
return;
}
else
{
// Add firstElement to visited States
visitedStates.add(firstElementInQueue);
// Get the children of first element
List<State> children = firstElementInQueue.getChildren();
for(State v : children)
{
if(v.isGoal())
{
v.printResult();
return;
}
if(!visitedStates.contains(v))
{
stateQueue.add(v);
}
}
// Remove the first element from state queue.
stateQueue.remove(firstElementInQueue);
}
long sz=stateQueue.size();
if(sz%1000==0)
System.out.println(sz);
// do this till state queue is empty.
}while(!stateQueue.isEmpty());
}
public void dfs(State currentState, java.util.Set<State> vStates)
{
// if we pass vStates as null. i.e. in the beginning.
if(vStates==null) vStates = visitedStates;
// if visisted state contains currentState, then just return.
// This is the wrong branch, and we need not traverse it further.
if(vStates.contains(currentState))
return;
// if it is GOAL
if(currentState.isGoal())
{
// That's it we are done.
currentState.printResult();
System.exit(0);
}
else
{
System.out.println("Number of nodes checked = " + vStates.size());
}
// Add current state to visited states.
vStates.add(currentState);
// Find the set of possible children of current state.
List<State> children = currentState.getChildren();
for(State c : children)
{
// if a children C is not in the visited states
// again call DFS on current child and visited States.
if(!vStates.contains(c))
{
// Make clone of visited states.
java.util.Set<State> clonedVStates = new java.util.HashSet<State>(vStates);
dfs(c, clonedVStates);
}
}
vStates=null;
}
}
</pre></div><br />
Now extend the SolveProblem class and override the abstract method to give your implementation as follows<br />
And use the methods to solve your problem:<br />
<p class="heading">Extend SolveProblem class and use</p><div class="collapsingdiv"><pre class="brush:java">package solution;
import mystate.SlidingState;
import mystate.State;
/**
*
* @author Yogi
*/
public class Solve15Puzzle extends SolveProblem {
public static void main(String[] args)
{
//Get the jvm heap size.
long heapSize = Runtime.getRuntime().totalMemory();
//Print the jvm heap size.
System.out.println("Heap Size = " + heapSize/(1024*1024) + " MB");
SolveProblem n = new Solve15Puzzle();
n.bfs();
}
@Override
public State getStateObject() {
// int[][] currentState = {{8,5,0,6}, {2,1,9,4}, {14,10,7,11},{13,3,15,12}};
int[][] currentState = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12},{0,13,14,15}};
// int[][] currentState = {{1,2,3,4}, {5,6,7,8}, {9,0,10,12},{13,14,11,15}};
// The following problem needs minimum 6 moves to solve. But DFS algo takes around 40 moves...
// int[][] currentState = {{1,2,3,4}, {5,6,11,7}, {9,10,0,8},{13,14,15,12}};
// int[][] currentState = {{1,2,3,4}, {5,6,7,8}, {9,0,10,12},{13,14,11,15}};
// int[][] currentState = {{8,5,0,6}, {2,1,9,4}, {14,10,7,11},{13,3,15,12}};
return new SlidingState(currentState);
}
}
</pre></div>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-28369288186658141362013-09-10T22:05:00.002+05:302014-06-26T16:42:38.650+05:30Real time examples of Design patterns being used by JavaI am very keen to learn what all design patterns are being used by java code.<br />
<br />
So here I am going to list them one by one.. I'll keep on updating this article as and when I learn more about design patterns...<br />
<br />
To begin with.. Lets learn something about strategy design pattern.<br />
<br />
<p class="heading">Strategy Design Pattern Examples</p><div class="collapsingdiv"><ul><li>There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime. <br />
Intent<br />
<li>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.<br />
</ul>You must have seen how we create threads in Java... We make a class implement Runnable and override its run method. And then use that class's object as an argument to Thread class constructor. <pre class="brush:java">class xx implements Runnable
{
@Override
public void run()
{
System.out.println("Running xx thread...");
}
}
class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("mythread");
}
}
public class Main
{
public static void main(String args[])
{
xx r = new xx();
// Encapsulate what varies.. Note that
// Here the behavior of the run method varies...
// That is why it has been moved out of the Thread class..
Thread t = new Thread(r);
// Now that we have overridden the run method of Runnable interface
// and passed the object of class implementing it to the constructor of
// Thread class...
// In this case, the run method of r object will get invoked
// by the start method.
t.start();
Thread s = new MyThread();
// As we have now overriden the method of the Thread
// class itself, the start method will invoke the overridden
// run method.
// Here polymorphysm is attained by inheritance and not by
// encapsulation.. This is a weaker strategy than the first one.
s.start();
}
}
</pre>Well, if you see the definition of run() method in Thread class I think you'll agree to what I have tried to explain above... Here is the definition in Thread class <pre class="brush:java">/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
public void run()
{
if (target != null)
{
target.run();
}
}
</pre>And if you look at the second way of creating a Thread, i.e. extending a Thread class... In that case the start method just invokes the run method... And because we have overridden the run method of Thread class, the default implementation of Thread's run method will not get invoked, instead the implementation that we have given in the child class will get invoked. <pre class="brush:java">/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start()
{
.....
}
</pre>
<pre class="brush:java">Collections.sort(myCollections, myComparator);
</pre>
This is another example of strategy design pattern, which I can think of.. As we are passing the behavior of comparison at run-time.
</div>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0tag:blogger.com,1999:blog-2322739097068009391.post-17522589129153627322013-09-08T19:42:00.001+05:302013-09-08T19:47:05.289+05:30The water jug problemWe have three water jugs, and each can hold 3oz., 5oz., and 8oz. of water, respectively. <br />
Without the possibility of water spilling when poured from one jug to another, and given that the jugs have no calibration, how do we divide the 8oz. of water equally among two jugs?<br />
<br />
<br />
<b>We will define a class named State holding the capacity of A and B jars. <br />
It should be noted that only 2 jars are sufficient to define a state, as water held in third jar can be calculated by subtracting the sum of two from the total.<br />
<p class="heading">Define class State like this...</p><div class="collapsingdiv"><pre class="brush:java">package mystate;
import bfs.threejugproblem.NotSupportedException;
import java.util.ArrayList;
import java.util.List;
public class State
{
int a=0;//3
int b=0;//5
int c=8;//8
public State(int a, int b)
{
this.a=a;
this.b=b;
this.c=8-a-b;
}
public boolean isGoal()
{
return (b==4 && c==4);
}
public boolean equals(Object xx)
{
State x = (State) xx;
if(this.a==x.a && this.b==x.b && this.c==x.c)
{
return true;
}
else
{
return false;
}
}
public int hashCode()
{
return 8;
}
public List<State> getChildren()
{
List<State> children = new ArrayList<State>();
// a -> b
if(a!=0 && b!=5)// if a is not empty
{
if(a+b<=5)
{
children.add(new State(0, a+b));
}
else
{
children.add(new State(a+b-5,5));
}
}
//a->c
if(a!=0 && c!=8)
{
// We are pouring completely from a to c
// a will be 0
// b will be 8-a-c
// c will be a+c
children.add(new State(0, 8-a-c));
}
//b->a
if(b!=0 && a!=3)
{
if(a+b<=3)
{
children.add(new State(a+b, 0));
}
else
{
children.add(new State(3, a+b-3));
}
}
// b->c
if(b!=0 && c!=8)
{
// We are pouring completely from b to c
// a will be 8-b-c
// b will be 0
// c will be b+c
children.add(new State(8-b-c, 0));
}
//c->a
if(c!=0 && a!=3)
{
if(c+a<=3)
{
children.add(new State(c+a, 8-c-a));
}
else
{
// a will be full i.e. 3 liters
// b will be 8-c-a
// c will be c+a-3
children.add(new State(3, 8-c-a));
}
}
// c->b
if(c!=0 && b!=5)
{
if(c+b<=5)
{
children.add(new State(8-c-b , c+b));
}
else
{
children.add(new State(8-c-b, 5));
}
}
return children;
}
@Override
public String toString()
{
return "{"+a+","+b+","+c+"}";
}
}
</pre>
</div>
<p class="heading">Depth First Search Algorithm</p><div class="collapsingdiv"><pre class="brush:java">public class DFSThreeJugProblem
{
public static void main(String[] args)
{
State currentState = new State(0,0);
List<State> visitedStates=new ArrayList<State>();
// Check if the current State has a solution
// given a set of visited States.
dfs(currentState, visitedStates);
}
public static void dfs(State currentState, List<State> vStates)
{
// if it is GOAL
if(currentState.isGoal())
{
// That's it we are done.
for(State v : vStates)
{
System.out.println(v);
System.out.println(currentState);
}
System.exit(0);
}
// if visisted state contains currentState, then just return.
// This is the wrong branch, and we need not traverse it further.
if(vStates.contains(currentState))
return;
// Add current state to visited states.
vStates.add(currentState);
// Make clone of visited states.
List<State> clonedVStates = new ArrayList<State>(vStates);
// Find the set of possible children of current state.
List<State> children = currentState.getChildren();
for(State c : children)
{
// if a children C is not in the visited states
// again call DFS on current child and visited States.
if(!clonedVStates.contains(c))
{
dfs(c, clonedVStates);
}
}
}
}
</pre></div><p class="heading">Breadth First Search algorithm...</p><div class="collapsingdiv"><pre class="brush:java">public class BFSThreeJugProblem
{
private static List<State> visitedStates=new ArrayList<State>();
private static Queue<State> stateQueue = new LinkedList<State>();
public static void main(String[] args) throws NotSupportedException
{
State currentState = new State(0,0);
// Add current state to state Queue.
stateQueue.add(currentState);
do
{
// Get the first Element from Queue.
State firstElementInQueue = stateQueue.peek();
// If the first Element is the Goal
// We are done.
if(firstElementInQueue.isGoal())
{
for(State p : visitedStates)
{
System.out.println(p.toString());
}
// There is no recursion here, so simple return would do.
return;
}
else
{
// Add firstElement to visited States
visitedStates.add(firstElementInQueue);
// Get the children of first element
List<State> children = firstElementInQueue.getChildren();
for(State v : children)
{
// if children has not already been visited.
if(!visitedStates.contains(v))
{
// add the child to state Queue.
stateQueue.add(v);
}
}
// Remove the first element from state queue.
stateQueue.remove(firstElementInQueue);
}
// do this till state queue is empty.
}while(!stateQueue.isEmpty());
}
}
</pre></div>Yogihttp://www.blogger.com/profile/15382350910254695035noreply@blogger.com0