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

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
* Runnable run object, then that
* Runnable object's run method is called;
* otherwise, this method does nothing and returns.
*


* Subclasses of Thread 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 run method of this thread.
*


* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* start method) and the other thread (which executes its
* run method).
*


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

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 getChildren()
{
List children = new ArrayList();
// 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 visitedStates=new ArrayList();
// Check if the current State has a solution
// given a set of visited States.
dfs(currentState, visitedStates);
}
public static void dfs(State currentState, List 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 clonedVStates = new ArrayList(vStates);
// Find the set of possible children of current state.
List 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 visitedStates=new ArrayList();
private static Queue stateQueue = new LinkedList();
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 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());
}
}

Example of Decorator Pattern – LowerCaseInputStream

Create a LowerCaseInputStream class as follows

public class LowerCaseInputStream extends FilterInputStream 
{

    public LowerCaseInputStream(InputStream in) {
        super(in);
    }
    
    @Override
    public int read() throws IOException
    {
        int c = super.read();
        if(c==-1)
            return c;
        else
            return Character.toLowerCase(c);
    }
    @Override
    public int read(byte b[], int offset, int len) throws IOException
    {
        int result = super.read(b, offset, len);
        for (int i = offset; i < offset+result; i++) 
        {
            b[i] = (byte)Character.toLowerCase((char)b[i]);
        }      
        return result;
    }
    
}

Use LowerCaseInputStream as follows

public static void main(String[] args) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("D:\Yogesh.txt");
        BufferedInputStream bufin = new BufferedInputStream(fis);
        InputStream in = new LowerCaseInputStream(bufin);
        int c;
        try
        {
            while((c=in.read())!=-1)
            {
                System.out.print((char)c);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
            
    }

Find it really interesting? You can read more about Decorator pattern in Head First Design Pattern book.

Problem using c:set of jstl

The problem was that i was not able to set the value of a variable defined in a scriptlet.


Root cause: The tag lib i was using was perhaps of an older version.

Older version:


Newer version:


Please do post more information if you have more knowledge about this problem.

How to put a time restriction on a method in java?

I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.

If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.

Now, how do I do this?

You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You’d have to adapt this to your needs.

Make a class MyTask implements Callable

package testapp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class MyTask implements Callable {

private String name;
private long sleepTime;

public MyTask(String name, long sleepTime) {
this.name = name;
this.sleepTime = sleepTime;
}

public Void call() throws Exception {
System.out.println("Starting task " + name);
Thread.sleep(sleepTime);
System.out.println("Finished task " + name);
return null;
}
}

Use this as is done here

public class ExecutorServiceTest {

public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Collection<Callable> tasks = new ArrayList<Callable>();
tasks.add(new MyTask("Task1", 10000));
tasks.add(new MyTask("Task2", 2000));
System.out.println(new java.util.Date());
List<Future> taskFutures = service.invokeAll(tasks, 2L, TimeUnit.SECONDS);
for (Future future : taskFutures) {
System.out.println("Done: " + future.isDone());
System.out.println("Cancelled: " + future.isCancelled());
}
System.out.println(new java.util.Date());

System.out.println("END");

}
}

Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object

I was getting the following error in the logs of the tomcat, when I try to start the tomcat server.

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

Things I tried but didn’t work
=========================
1) I used class finder to find that which jar contains this class java.lang.Object, and it was rt.jar.
I added rt.jar in the classpath. But of no use.
2) I made a Environment variable CATALINA_HOME, JAVA_HOME, but didn’t help.
3) I tried rebooting the machine every time, after I set the paths specified in step 2.
4) Uninstalling and re-installing the tomcat didn’t help.

ROOT CAUSE AND SOLUTION:
=========================
During installation of tomcat, the default jre directory that was coming on the installation screens of tomcat didn’t had rt.jar
I realized this when I checked the jre folder.

Then I decided to uninstall and re-install tomcat and while re-installation I took care while specifying the jre folder. And the new jre folder had rt.jar

This solution made it work. 🙂

I m happy 🙂

The prefix “jaxb” for element “jaxb:globalBindings” is not bound.

I’m using xjc to compile XML Schema into JAXB objects and the
compiling is fine unless I try to define jaxb bindings. For instance,
if I try adding this code in the schema:




bindingStyle="modelGroupBinding"
choiceContentProperty="true" >


<jaxb:javaType name="short"
xmlType="xs:long"
printMethod="javax.xml.bind.DatatypeConverter.printShort"
parseMethod="javax.xml.bind.DatatypeConverter.parseShort"/>



xjc complains with:
[ERROR] The prefix “jaxb” for element “jaxb:globalBindings” is not
bound.

SOLUTION
========

Missing namespace declaration. There should be something like this:
xmlns:jaxb=”URI”
Just look for the other namespace definitions (i.e. xmlns:s) and
add the above attribute to the end.

Source : http://www.velocityreviews.com/forums/t137983-problem-in-xjc-with-recognizing-jaxb-prefix.html

xsd:date maps to java.util.Calendar

My schema has an element of type xs:date, which jaxb maps to a java.util.Calendar. If I create a Calendar object with Calendar.getInstance(), it marshalls to “2003-11-24-05:00”.

How can I get it to marshall to just “2003-11-24”?

SOLUTION:
Write a converter class (see MyConverter below) and added an annotation/appinfo to the xml schema, also shown below.

public class MyConverter
{
static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
static public String printCalendar(Calendar c)
{
return df.format(c.getTime());
}

static public Calendar parseCalendar(String c) throws ParseException
{
Date d = df.parse(c);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal;
}
}




<jaxb:globalBindings
<jaxb:javaType name="java.util.Calendar" xmlType="xsd:date"
printMethod="MyConverter.printCalendar"
parseMethod="MyConverter.parseCalendar"
/>



...

Source : https://forums.oracle.com/forums/thread.jspa?threadID=1624090

Basic fundas about using float or double

Think again if you are going to use float or double for amount/currency field.

Reason behind this is

Floats have a fixed number of total bits of precision, which must be shared among the integer and fractional parts. If you use more of those bits to store a larger integer portion (123456 vs. just 12), that leaves fewer for the fractional portion (.4 vs. .45678).

Also, you should be aware that since float and double are base-2 formats, rather than base-10, many values that can be represented with a small, finite number of digits in base-10 cannot be stored in a double or float. For instance, it is impossible to store exactly 1/10 (0.1) in a double or float, just as it’s impossible to store 1/3 (0.333…) exactly in a finite number of digits in base-10.

Demonstration code:

    public static void main(String args[]) {  
double d = 1997500.43;
String s = "1997500.43";
float f = (float) d;
System.out.println(f);//1997500.4

float f3 = Float.parseFloat(s);
System.out.println(f3);//1997500.4

float f4 = Double.valueOf(s).floatValue();
System.out.println(f4);//1997500.4

float f5 = new Double(s).floatValue();
System.out.println(f5);//1997500.4

float xFloat;
Double x = new Double("63.8644951");
xFloat = x.floatValue();
System.out.println(xFloat);// 63.864494

float xFloat2;
Double x2 = new Double("3333263.8644951");
xFloat2 = x2.floatValue();
System.out.println(xFloat2);// 3333263.8
}

Detailed information about floats and doubles is available at : http://www.coderanch.com/t/564234/java/java/Precision-loss-String-Float-double