Friday, March 21, 2014

How to make a dropdown as readonly in html

I encountered a problem where in it was required to make a drop down readonly.

While searching over internet i found THIS
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.

How do we do this? The common thought is to disable the drop down menu. Well, yes, but there's a choice

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.

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.

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

Make a replica of your dropdown with a different name and different id.

Hide your original drop down with <span style="display:none">
This makes the element available in the form, so it will flow to the server side as well.
At the same time, it will give a look and feel of disabled to the user.

Example :

<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>


Friday, March 7, 2014

Exception handling in java

Thanks to https://today.java.net/article/2006/04/04/exception-handling-antipatterns#antipatterns

Basic Exception Concepts

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.

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.

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).

Errors are serious problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError.

Creating Your Own Exceptions

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:

throw new MyObjectNotFoundException("Couldn't find    object id " + id);

Second, your code can wrap and throw another exception. For example:

catch (NoSuchMethodException e) 
{  
    throw new MyServiceException("Couldn't process      request", e);
}

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.

Antipatterns


Log and Throw

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);
}
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.

Throwing Exception

public void foo() throws Exception { 

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.)

Throwing the Kitchen Sink

Example:

public void foo() throws MyException,    
AnotherException, SomeOtherException,    YetAnotherException{

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.

Catching Exception

try 
{  
    foo();
} 
catch (Exception e) 
{  
    LOG.error("Foo failed", e);
}

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.

Destructive Wrapping

catch (NoSuchMethodException e) 
{  
    throw new MyServiceException("Blah: " + e.getMessage());
}

This destroys the stack trace of the original exception, and is always wrong.

Log and Return Null

Example:

catch (NoSuchMethodException e) 
{  
    LOG.error("Blah", e);  
    return null;
}
catch (NoSuchMethodException e) 
{  
    e.printStackTrace();  
    return null;
} 

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.").

Catch and Ignore

Example:

catch (NoSuchMethodException e) 
{  
    return null;
}

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.

Throw from Within Finally

Example:
try 
{  
    blah();
} 
finally 
{  
    cleanUp();
}

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.


Multi-Line Log Messages

Example:
LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");

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:

LOG.debug("Using cache policy A, using retry policy B"); 

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.

Unsupported Operation Returning Null

Example:
public String foo() 
{  
    // Not supported in this implementation.  
    return null;
}

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




Wednesday, March 5, 2014

In JSTL/JSP when do I have to use and when can I just say ${myVar}

Source : http://stackoverflow.com/questions/6574776/in-jstl-jsp-when-do-i-have-to-use-cout-value-myvar-and-when-can-i-just

In JSTL/JSP when do I have to use <c:out value="${myVar}"/> and when can I just say ${myVar}


I've been doing this the whole time in my JSP code:
<c:out value="${myVar}"/>

Today I just realized for the first time that I seem to be able to use this shorter version just as well:
${myVar}

It works without <c:out>!

Perhaps this is because my page is declared like this:

<%@ page language="java" contentType="text/html; 
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

So, my question is, can I replace in my code with this shorter version? Is there any reason to keep using ? Or are there places where I might still need it?

Solution:


<c:out> does more than simply outputting the text. It escapes the HTML special chars.
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).

I'll give you a simple example so that you understand.
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:

<script>while (true) alert("you're a loser");</script>

Monday, March 3, 2014

duplicate import try, using auto-import="false"

How to use same entity class in two different packages in hibernate?


Source : http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/

Using Hibernate and JPA you cannot have two classes with the same name (on different packages) mapped. This raise an error at runtime:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyClass refers to both


To solve this issue on the Entity annotation of com.intre.MyClass and com.dummy.Class add the property name.

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

Wednesday, February 26, 2014

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.

We were getting the below error in our project, when trying to invoke a web service.

[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)

Solution:
The solution lies in the configuration files used by spring.
Here in our project, the version specified in this file was 1.2 where as the web service was expecting 1.1

<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>



How to break a list into smaller sublists of equal size

// 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;
}

Usage:
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!)

Monday, February 24, 2014

Generate java classes using xjc

Source : Generate java class from xml schema using jaxb xjc command


Before using JAXB to create or access an XML document from Java application, we have to do the following steps:

1.Binding the schema
* 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).

2.Marshal the content tree /Unmarshal the XML document.
* After binding the schema, you can convert Java objects to and from XML document.
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.

‘xjc’ Command Line Options

Usage:

xjc [-options ...] … [-b ] …
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.


Complete list of options for ‘xjc’ is available in the help option.

xjc -help

Generate Java classes using ‘xjc’

Follow the steps below to generate a set of Java source files from XML schema.
  1. Create a new Java project folder and name it as “JAXBXJCTool”.
  2. 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
  3. Employee.xsd

    <?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>
    
  4. Save the file
  5. Create a new folder ‘src’ inside the project folder.
  6. 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
  7. C:\Users\iByteCode\Desktop\JAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd
  8. This will generate set of Java source files with appropriate annotation inside ‘src’ folder



Wednesday, February 19, 2014

How to make ajax call in spring framework

Write a server side method, with a mapping something as follows:


@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn, 
HttpServletRequest request, HttpServletResponse response) 
{
       return ocn.toUpperCase();   
}
Here @ResponseBody tells the framework to return value of the method to the browser and not lookup for a view with that name.
You can optionally omit request and response parameters in the signature of the method, if you like to.

After removal of request and response the method will look like

@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn) 
{
       return ocn.toUpperCase();   
}



Write a javascript method as follows (This uses jquery to fire ajax request)

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);
      }     
    }
  });   
}

Thursday, December 19, 2013

The selected file is a system file

Error:

 

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

 

Resolution:

This a problem encountered when the Clear Case plugin is added to the eclipse and then the project is imported.
Solution:
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.

 

Link:

http://www.myeclipseide.com/PNphpBB2-printview-t-12987-start-0.html

 Solution given by dewanvaibhavgarg@gmail.com

Saturday, October 12, 2013

What is the difference between @RequestMapping's param attribute AND @RequestParam

Source : http://www.captaindebug.com/2011/07/accessing-request-parameters-using.html#uds-search-results

@RequestMapping is only used to map request URLs to your controller.
The 'params' value is used to narrow the mapping down allowing you to map different param values
(uuids in this case) to different methods. For example:

/** 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" 
}


/** 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" 
}


Whilst @RequestParam is used to pass request parameters into a method so that you can use them.
For example:

@RequestMapping(value = "/help/detail", 
method = RequestMethod.GET)
public String displaySomeHelpDetail(@RequestParam("uuid") String uuid, Model model) {

log.info("The uuid = " + uuid);
return "view.name" 
}

Tuesday, September 24, 2013

Reading Flat files seperated by | symbol

Often I have seen that there are files having lines seperated by a de-limiter |.
I thought of making a class that could easily iterate over each of the line one by one..

This class PipedString represents a string which has elements seperated by a | symbol.
This is an iterable class

Create a class PipedString as follows

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() {
            }
        };
    }
}

Now create a Flat File Reader using this PipedString

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()
        {
        }
    }
}

How to use this FlatFileReader class

    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();
    }


Saturday, September 14, 2013

A generic problem solver from State to Goal

I 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.

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.

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.

Create a State interface

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);
    }
}


Now implement this abstract class and create a custom class that defines the state of your problem.
Please make sure that you override all the methods given in the interface very correctly.
Do make member variables that can signify your state.
For example, let me take an example of 15-squred number puzzle

Implement the abstract class and create SlidingState class

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;        
    }

}

Create a SolveProblem abstract class as follows

SolveProblem Abstract class

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;
    }
}


Now extend the SolveProblem class and override the abstract method to give your implementation as follows
And use the methods to solve your problem:

Extend SolveProblem class and use

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);
    }
}

Tuesday, September 10, 2013

Real time examples of Design patterns being used by Java

I am very keen to learn what all design patterns are being used by java code.

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...

To begin with.. Lets learn something about strategy design pattern.

Strategy Design Pattern Examples

  • 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.
    Intent
  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
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.
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();


    }
}
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
/**
* 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();
    }
}
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.
/**
     * 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()
    {
       ..... 
    }
Collections.sort(myCollections, myComparator);
This is another example of strategy design pattern, which I can think of.. As we are passing the behavior of comparison at run-time.

Sunday, September 8, 2013

The water jug problem

We have three water jugs, and each can hold 3oz., 5oz., and 8oz. of water, respectively.
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?


We will define a class named State holding the capacity of A and B jars.
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.

Define class State like this...

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+"}";
    }
}

Depth First Search Algorithm

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);
            }
        }
    }
}

Breadth First Search algorithm...

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());
    }
}