Thursday, March 19, 2015

STRUTS2 CUSTOM VALIDATORS DEMO CODE EXAMPLE

GreaterThanZeroValidator.java

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class GreaterThanZeroValidator extends FieldValidatorSupport {

    @Override
    public void validate(Object object) throws ValidationException {

String fieldName = getFieldName();
Integer fieldValue = (Integer) getFieldValue(fieldName, object);

if (fieldValue != null && fieldValue <=0 ) {
   addFieldError(fieldName, object);
}  
    }
    
}

Validators.xml (also put all default validator in this file)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator Definition 1.0//EN"
        "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">

<validators>
    <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
    <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
    <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
    <validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
    <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
    <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
    <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
    <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
    <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
    <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
    <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
    <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
    <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
    <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
    <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
    <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>

    <validator name="greaterThanZero" class="com.validator.GreaterThanZeroValidator" />

</validators>

ABCAction-validation.xml
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">

<validators>

<field name="pkgData.validityPeriod" >
<field-validator type="greaterThanZero" short-circuit="true">
<message>${getText("error.greaterthanzero", {getText("pkg.validityperiod")})}</message>         </field-validator>
<field>

ABCAction.java

public class ABCAction extends ActionSupport implements   ServletRequestAware{

private static final long serialVersionUID = 1L;
private static final String MODULE  = PkgCTRL.class.getSimpleName();
private static final String PACKAGE = " Package ";

private PkgData pkgData = new PkgData();
.......
.......
.......
.......

}

LIBS (keep the required libs only)

validators.xml file location (means it should come in classpath)

helpful link : 

http://struts.apache.org/docs/validation.html#Validation-RegisteringValidators
(read above link content fully with patience )

Tuesday, March 10, 2015

CSS to center aling text of last and cecond last TD of all rows in a table

td:nth-last-child(-n+2) {       
             text-align: center;

}

CSS to center aling text of last and first TD of all rows in a table

        tr>td:last-child {                       
            text-align: center;
        }
       
        tr>td:first-child {                       
            text-align: center;
        }

Monday, March 9, 2015

JAVA CODE TO GET ALL THE DETAIL OF JVM AND O.S

import java.util.*;
class JavaProps {
public static void main(String[] args) {
Properties p = System.getProperties();
p.setProperty("TestKey", "TestValue");
p.list(System.out);
}

}

COMPILE AND RUN

D:\TestWork\JavaCode>javac JavaProps.java

D:\TestWork\JavaCode>java -Draj=sonofking JavaProps

-- listing properties --
raj=sonofking
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=C:\Program Files\Java\jre8\bin
java.vm.version=25.0-b70
java.vm.vendor=Oracle Corporation
java.vendor.url=http://java.oracle.com/
path.separator=;
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg=sun.io
user.script=
user.country=IN
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=Service Pack 1
java.vm.specification.name=Java Virtual Machine Specification
user.dir=D:\TestWork\JavaCode
java.runtime.version=1.8.0-b132
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs=C:\Program Files\Java\jre8\lib\endorsed
os.arch=amd64
java.io.tmpdir=C:\Users\KIRPAL~1.RAJ\AppData\Local\T...
line.separator=

java.vm.specification.vendor=Oracle Corporation
user.variant=
os.name=Windows 7
sun.jnu.encoding=Cp1252
java.library.path=C:\windows\system32;C:\windows\Sun\Ja...
java.specification.name=Java Platform API Specification
java.class.version=52.0
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
os.version=6.1
user.home=C:\Users\kirpalsinh.raj
TestKey=TestValue
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
java.specification.version=1.8
file.encoding=Cp1252
user.name=kirpalsinh.raj
java.class.path=.
java.vm.specification.version=1.8
sun.arch.data.model=64
java.home=C:\Program Files\Java\jre8
sun.java.command=JavaProps
java.specification.vendor=Oracle Corporation
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode
java.version=1.8.0
java.ext.dirs=C:\Program Files\Java\jre8\lib\ext;C:...
sun.boot.class.path=C:\Program Files\Java\jre8\lib\resour...
sun.stderr.encoding=cp437
java.vendor=Oracle Corporation
file.separator=\
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.stdout.encoding=cp437
sun.desktop=windows
sun.cpu.isalist=amd64

Valid declarations for main() method


1) static public void main(String[] args)
2) public static void main(String... x)
3) static public void main(String bang_a_gong[])

Note: One can overload the main method but cannot override it.

Sunday, March 8, 2015

Java Threads key points to Remember

1) Thread do not come out of a waiting pool just because a lock has been released.

2) Thread must own the lock on the object that wait() is being invoked on. 

3) notifyAll() notifies all the threads waiting on a particular locked object,
    not all threads waiting on any object.

4) when synchronized instance methods are called on the same instance, they block each 
    other.   

5) synchronized static methods in the same class block each other, regardless of which      
    instance was used  to call the methods.

6) synchronized instance methods called on different instances do not block each other

7) The join() must be placed in a try/catch block.

8) wait(), notify(), notifyAll() must be call from within the synchronized area

9) A thread is done being a thread when its target run() method completes.

10) A thread can call the start() method only once in its lifetime. If start() is called
      more than once on a Thread object, it will throw a RuntimeException

11) sleep(), join() and wait() method throws InterruptedException

12) join(), setPriority(), wait(), notify() and notifyAll() are final method.

13) sleep() and yield() are static methods.

14) thread states are new, runnable, running, waiting/block/sleeping, dead

15) yield() method is supposed to do is make the currently running thread back to runnable 
      to allow other threads of  the same priority to get their turn.

16) A yield() won't ever cause a thread to go to the waiting/sleeping/ blocking state.

17) If possible then the synchronized code should be kept minimum.

18) A static synchronized method and a non-static synchronized method will not block each 
      other, ever.

19) Threads calling static synchronized methods in the same class will always block each 
      other—they all lock on the same Class instance.

20) Threads calling non-static synchronized methods in the same class will only block each 
      other if they're invoked using the same instance.

What will Happens when a Thread Can't Get the Lock on the required Object ?

When a thread tries to enter into a synchronized method and if the lock is already taken by another thread , then the thread trying to get the lock will be blocked on the object's lock. 
and the thread goes into a kind of pool for that particular object and sits there until the lock is released and the thread CAN again become runnable/running thread when the lock released on the object. but if there are many thread waiting for the objects lock then we cant say which thread will get a chance to occupy the lock on  the object

Tuesday, March 3, 2015

About wait() notify() notifyAll() sleep() yield() setPriority()

wait() method call puts the current running thread into the waiting list/pool of the OBJECT it is working. the threads waiting list/pool is separate for each OBJECT(not thread object but the object/instance it is working for) . the waiting thread release the of the object it is working on.
and the thread calling the wait() method must hold lock on the object(Intance of any class).
the waiting thread will be back into runnable state when any another thread working on the same object(Intance of any class) calls notify()/notifyAll() method.
wait() method must be call from the synchronized context.

notify() method call brings only one thread back into runnable state from the waiting state and that is not gauranteed which thread will be 
notified. notify() method must be call from the synchronized context.
the thread calling the notify() method must hold lock on the object(Intance of class).

notifyAll() method call brings all the waiting thread for the particular object's lock into the runnable state and JVM will bring
any thread from the runnable to running state. notifyAll() method must be call from the synchronized context.
the thread calling the notifyAll() method must hold lock on the object.

sleep() method call puts the current running thread into sleeping state for the specified number of milli seconds
but the sleeping thread doesnt release the lock on the object it is working.

yield() method call puts the current running thread in the runnable state and give chance to another thread to run.
but it is not gauranteed that the same thread will not come back in running state.
The thread calls the yield() method will go into runnable state but it is possible that the same will be bring back
into running state by the JVM.

join() 
when one(FLOWER) thread calls a join method on another(FRUIT) thread then the current running(FLOWER) thread will wait for the
(FRUIT)thread it has joined finish its execution.

setPriority() method call set the priority for the current method calling thread. and the thread priority range is 1(min) to 10(max). (5 is norm).
if any thread has a parent thread then it will get the priority same as its parent.
the the priority range 1 to 10 can vary from JVM to JVM. but never higher or lower than 1 to 10.



KEY METHODS FOR THREAD

Object Class

wait() (final method)
notify() (final method)
notifyAll() (final method)

Thread Class

start();
sleep(); (static method)
yield() (static method)
join() (final method)
setPriority() (final method)

Runnable Interface

run()


scheduleAtFixedRate vs scheduleWithFixedDelay

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
 long initialDelay,
 long period,
 TimeUnit unit);   
   
      Creates and executes a periodic action that becomes enabled first
      after the given initial delay, and subsequently with the given
      period; that is executions will commence after initialDelay then initialDelay+period, then
      initialDelay + 2 * period, and so on. If any execution of the task
      encounters an exception, subsequent executions are suppressed.
      Otherwise, the task will only terminate via cancellation or
      termination of the executor.  If any execution of this task
      takes longer than its period, then subsequent executions
      may start late, but will not concurrently execute.
     
Argument Parameters   
      1)command : the task to execute
      2)initialDelay : the time to delay first execution
      3)period : the period between successive executions
      4)unit : the time unit of the initialDelay and period parameters
  
Return Value
      ScheduledFuture : representing pending completion of the task, and whose  get() method will 
      throw an exception upon cancellation

 Exceptions Throws
      1) RejectedExecutionException: if the task cannot be scheduled for execution
      2) NullPointerException : if command is null
      3) IllegalArgumentException : if period less than or equal to zero
 
  
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
    long initialDelay,
    long delay,
    TimeUnit unit);  
   
      Creates and executes a periodic action that becomes enabled first
      after the given initial delay, and subsequently with the
      given delay between the termination of one execution and the
      commencement of the next.  If any execution of the task
      encounters an exception, subsequent executions are suppressed.
      Otherwise, the task will only terminate via cancellation or
      termination of the executor.

Argument Parameters
      1)command : the task to execute
      2)initialDelay : the time to delay first execution
      3)delay : the delay between the termination of one execution and the commencement of the nex  
      4)unit : the time unit of the initialDelay and delay parameters
 
Return Value  
     ScheduledFuture : representing pending completion of the task, and whose  get() method will 
     throw an exception upon cancellation
 
Exceptions Throws  
      1) RejectedExecutionException : if the task cannot bescheduled for execution
      2) NullPointerException : if command is null
      3) IllegalArgumentException : if delay less than or equal to zero
     

     
   

Monday, March 2, 2015

JAVA CODE TO DELTE DIRECTORY AND ITS SUB DIRECTORY AND FILES

private static void deleteFile(File file) {
try {
if(file==null){
return;
}
if(file.exists()) {
if(file.isDirectory()){
File[] childFiles = file.listFiles();
if(childFiles!=null && childFiles.length>0){
for (File childFile : childFiles) {
deleteFile(childFile);
}

}
file.delete();
}else{
file.delete();
}
}
}catch(NullPointerException e) {
System.out.println("Problem while Deleting folder, reason : " + e.getMessage());
}catch(SecurityException e) {
System.out.println("Problem while Deleting folder, reason : " + e.getMessage());
}catch(Exception e){
System.out.println("Problem while Deleting folder, reason : " + e.getMessage());
}
}

About Thread blocking

1)
Thread calling non-static synchronized method block each other when they works on the same instance of the respective class.
when they works on different object of the class then they do not block each other.

2)
Thread calling static synchronized method block each other because they work on the class level not on the instance level. because it is 
static synchronized method it is common among all the instances of the class.

3)
Thread calling static synchronized method and non-static synchronized method do not block each other because both are different level method.
static method is the class level method which is common for all instances and non-static method work as per instance of the class.

4)
In case of the synchronized block thread block each other if they works on the same object. Thread working on
different object will not effect each other they won't block each other.

Care:
Access to non-static fields should be done from the non-static synchronized method and
access to static fields should be done from the static synchronized methods

Java Thread's join() method

Thread's join() method

join() is a non static method, it has three forms one without any argument and one join(long millis) with the long value as a parameter
the time to wait in milliseconds. and the third is with the two parameter join (long millis, int nanos) it takes one more parameter value it represents the nano seconds value. 
means if we use this method then it will wait for the total time millis+nanos seconds.

join() method cause the current running thread to wait until the thread which calles join() on get finished.

Example
class MainThread{
public static void main(String[] box){
Thread th = new Thread();
th.join();
or
th.join(2000);
}
}

Here in this example the current running thread is the main thread. it will wait to go in runnable state until the th thread get finished.
and
same way in case of the th.join(2000), the main thread will wait  2000milli before go into runnable state or we can say main thread will join the th thread for 2000milliseconds
then it will go into the runnable state without worrying about the th thread's state.


Keep Visiting
Write your comment


Java Thread's yield() method

Thread's yield() method

It is a static method. yield() method takes the currently running thread to back to the runnable state
so the other equal's priority thread will get a chance to run. but it is not guaranteed that
the same thread will not get in execution back. it can come back in the running state.

yield() method doesn't take the thread into wait/sleep/blocking state.
it just takes the current running thread into runnable state. just for giving chance to other threads in
the Runnable pool.


Keep Visiting 
Give your comment 

JAVA THREAD PRIORITY

A thread gets a default priority that is the priority of the thread of execution that creates it.

public class MainThread {
public static void main (String [] box) {
Thread th = new Thread();
}
}
the thread referenced by th will have the same priority as the main thread.

One can also set priority using the .setPriority() method.

The thread priority value must be in range 1 to 10.

Thread priority range is also depends on the JVM some JVM takes only values between 1 to 5.

JVM never changes the thread priority.

Any thread's default priority is 5.

There are three constants in the Thread class for the thread priority.
Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRIORITY (10)

If user sets  1o 10 priorities for ten different threads and if the JVM doesnt support 1 to 10 priorities but 
it support 1 to 5 priority then some of the thread among the 10 will have duplicate priorities.


Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...