Friday, September 25, 2015

Remembering JSP Actions

JSP  mainly has 4 Types of actions

useBean
   Jsp usebean is used to associate a variable with an instance of a class . An example  is :

 <jsp:useBean id="today" class="java.util.Date"/>


setProperty and getProperty

    These actions are used to set or get property values from the variables defined using useBean  an Example :

 <jsp:useBean id="employee" class="testpackage.Employee"/>
<jsp:setProperty name="employee" property="firstName" value="someName"/>
First Name: <jsp:getProperty name="employee" property="firstName"/>


JSP Include and Forward 

    Jsp Include is used to include another resource dynamically . This should be a JSP page .
Difference between a JSP include and an Include directive is that , the JSP include adds the resource to the page in runtime while the other does in the time of translation .

  JSP forward forwards the current page to a different resource

Remembering JSP's

Lets look at some old JSP  terminologies

   
 
 
  JSP's are servlets
  
     All Jsps get translated to servlets during runtime. The servlet class name is normally decided by the servlet container . All these servlet classes extends implements jspPage interface .  When requested for the first time ,webserver compiles JSP page to the class and on subsequent requests it doesn't re compiles unless changes has been observed in the JSP Page .

JSPInit() and JSPDestroy()
   
          You can override JSPInit and JSPDestroy() methods in the JSP declaration tags. Doing this allows you the handle to the init() and destroy() functions of the jsp servlet.

JSP mappings in web.xml

         JSP's are mapped in web.xml's  to a particular url pattern . Init Parameter is also defined here.

Implicit Objects
     
      There are set of implicit objects in JSP pages which you can use without declaring it explicitly .
They are :

  request - servletRequest
  response - servletResponse
  out - PrintWriter (JspWriter)
  session - HTTPSession
  application -  ServletContext
  config - ServletConfig
  pageContext - pageContext
  page - JspPage
  exception - Throwable


Scopes of Variables in JSP 
   
           In Jsp a variable can be stored in 4 Scopes page, request , session and applicationScope
page - only for the page, request - ServletRequest , session - HttpSession  , application - ServletContext . The setAttribute method in PageContext has the following signature:

public abstract void setAttribute(java.lang.String name,
        java.lang.Object value, int scope)
         The value of scope can be one of the following static final ints in PageContext: PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE.

JSP Include Directive
   
  <%@include file ="url" />   is known as include directive in JSP pages. These are used to keep the code separated and have a modular architecture . When we do a jsp page include, it replaces the directive with the contents of the url page.


Scriptlets , Expressions and Directives

  The scriplets are "<%"  which shows beginning of the java code in JSP page .
   "<%=" are Expressions which calls a method and returns the value to output stream of JSP
  "<%! "  are directives which mark starting of a method definitions in the JSP page

Wednesday, August 5, 2015

Pending Interuppts in Java

     Interupts can be kept pending till the first Sleep call . A thread can continue to execute even if it is interrupted and throws an InterupttedException on the call of sleep method :


 Have a look at a sample code:

   Public class TestInteruppt{
     public static void main(String args[]){
    Thread.currentThread.interrupt();
try{
   Thread.sleep(30);
}catch(InterruptedException E){
 System.out.println(" This is a Pending Interupt");
 }

 }
 }

Difference between Thread.interrupted() and isInterrupted


       Thread.interrupted() is a final static method which is defined in the base thread class  and isInteruptted is a non static method in the thread class. Both returns the interrupt status of the thread.  One is called on the object of the thread to get the status since the interrupted() method is static this is called by Thread.interrupted().
      Thread.interrupted() returns true if the thread has interrupt flag set and resets the interrupt flag. while isInterrupted() method is a check for the flag and doesnt resets the flag
   

Thursday, July 23, 2015

Validating an XML with DTD in Java

      In this example i will show you how to validate an incoming xml . To validate an XML you have two options . One is to use XSD and second one is to use DTD's . I will explain you about XSD and why its is better compared to DTD's in a different post . In this post i will try to explain you about DTD's  and how will we validate a XML document.

 DTD's are non-xml documents which defines characteristics of an incoming xml . DTD's can be a separate document or can be included in the same XML . Lets look at a sample DTD defined XML

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE students [
   <!ELEMENT students (student+)><!-- any Number of students -->
   <!ELEMENT student (studentid, name)><!-- student can have only two elements -->
   <!ATTLIST student department CDATA #REQUIRED> <!-- department is required -->
   <!ELEMENT studentid (#PCDATA)><!-- studentId is parsable String -->
   <!ELEMENT name (#PCDATA)>
  ]>
  <students>
  <student department="computers">
     <studentid>1234</studentid>
     <name>Bran</name>
  </student>
  <student> <!--  Gives a parser Exception as department is required. -->
     <studentid>1234</studentid>
     <name>Bran</name>
  </student>
  </students>

   The DOCTYPE element is the DTD , It defines how the XML is expected to be . Lets look closely at what  this DTD means

1. The root element is students.
2. Students tag can contain one or many elements of student type. (+ indicates one or more , * indicates zero or more)
3. Student type contains two elements studentid and name.
4. Department is Required.
5. StudentId and Name should be a parsable Data .  PCDATA means parsed character data

More details on writing DTD's is found here .

Lets look how we write a java code to validate the XML . While doing a domBuilder parse , we have to set the factory to be validating true. In case you have to handle the validation errors with custom logic then you have to use the setErrorHandler method (of builder)  and pass a custom ErrorHandler Class




public class DTDValidator {

 public static void main(String[] args) throws SAXException,ParserConfigurationException,IOException {
 
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  domFactory.setValidating(true);
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("src\\com\\learning\\xml\\student.xml");
        //builder.setErrorHandler(<Custom Implementation Of Error Handler );
  System.out.println("Successfully Parsed");
      }
}





Tuesday, July 21, 2015

XML vs HTML

   I will take this blog post to point you what all are the key differences between an XML and HTML  and what all are the rules driving both of them .

1. XML is case sensitive while HTML is not.
    <BR> and <br> are two different tags for xml but html consider both as one.

2. Close tags are not mandatory for HTML .
    HTML parser is not so strict and it will not complain you if you have missed a closing tag. It understands from the context. However XML is strict with respect to closing tags.

3. An Attribute without a value is valid for HTML  but not for an XML
   <table name="table1" visible>  is a valid HTML but not a valid XML . To be a valid xml this should be  <table name="table1" visible="true">

4. Attribute values should be given inside a "double quote" for XML, However HTML doesnt stick to this rule <table name="table1" visible=true> is a valid HTML.


Hope it helps . Happy coding :) 

How to create a drop shadow effect in android



          Recently on working on a project, My client requested me to add a shadow to an custom action bar layout.This was something i have never done before  so i decided to look for it. With my experience in CSS i was expecting a drop shadow to be enabled. But interestingly android doesnt have such a feature.
  But you can do a workaround. Here is how i do it.

1. Define a custom drawable  named it as shadow_drawable.xml ( inside res/drawable folder)


<shape xmlns:android="http://schemas.android.com/apk/res/android">


<gradient android:startColor="@color/background_material_dark"
          android:endColor="@color/background_material_light"
          android:angle="250">
</gradient>
</shape>

And yes here is your shadow drawable. You could use it in your app always ( May be in another app too) if you can copy paste  :)

Lets look at how do we implement it.
I added it to a linear layout to have a drop shadow. So under the layout i added the following code.

<View     android:layout_below="@+id/some_layout_item"
          android:layout_width="fill_parent"
          android:layout_height="7dip"
         android:background="@drawable/shadow_drawable">
</View>


  And thats it. Your drop shadow is now ready .  Adding a demo picture .

Happy coding  :)






Monday, July 20, 2015

ArrayList vs Vector in java

Most of the developers are still not sure if they have to use a Vector or an ArrayList. As from my experience we cannot state a general statement that option A is better than option B. But here i outline some important things to check before choosing either of them.

1 . Vector is synchronized , While ArrayList is not. Which means that all operations done on a Vector is thread safe by default and you don't have to provide any explicit synchronization . So i would prefer Vector over ArrayList when i am working with threads. But this has a negetive side . Vector has synchronization code which makes it bit less performing in normal cases where thread safety is not a concern
 
2 . The size of a ArrayList increases 50% , While Vector it doubles as the data goes out of bounds . You have to understand the pattern in which the data grows to consider which is better. Remember Vector has an option to set the increment value .

3. Retrieving elements from a particular position is of the O(1) , in both ArrayList and Vector . However both suffers a penalty of O(n) to insert an element to the middle mainly because one have to shift all n-i element to insert an element at ith Position.



Hope you will look into these points from now on .  Happy coding :)

Wednesday, July 15, 2015

Inner Classes-2(Local Classes)

         In java you could define a class inside a code block/Method. This kind of classes are known as Local classes .       Lets look at an Example :
   
public class HelloWorld{
    public int studentId;
 
 public  void method(){
    int loop=0;
    final int CONSTANT=10;
    System.out.println("Main Execution begins , Student id is :" +studentId);
    class  LocalClass{
     public void printStudentId(){
      System.out.println("Inside Inner class, Student id is :" +studentId); // Remember that if studentId is also present in local class
                                                                         // this will print the local class variable student id , in such cases  use Student.this.studentId
                                                                         
            System.out.println("Inside Inner class, CONSTANT is :" +CONSTANT); // only final local variables can be accessed.
            
             System.out.println("Inside Inner class, loop is :" +loop); // errors out , loop is not final
   }
   }
   LocalClass local = new LocalClass();
   local.printStudentId();
   }
   
   
   public static void main(String args[]){
       HelloWorld hello = new HelloWorld();
       hello.method();
   }
   
   }

Some points to remember:
 1. A local class can access variables inside outer class (instance variables of outer class)
 2. A local class cannot be instatiated/visible outside the code block/method.
 3. A local class cannot access non final local variables as they both have different scopes , Local variables get destroyed on method exit . But final local variables are accessible inside local classes. Final variables are copied to the code stack internally before the inner class instance is created and can be used inside.

Tuesday, July 14, 2015

Java Inner Classes -1 (Member classes)


In Java we can define nested classes . Nested classes only make sense if the class which is nested is only used by outer class. A class which is defined inside another class is known as Inner class.  If you look at JDK code, we could see nested classes present in HashMap code.  This nested class is Map.Entry .  As we all know Entry class only make sense to a Hashmap class .
  Now lets look at different ways of doing it :
 
  1. Member class :
 
      A member class acts as a non static member of outer class.  Lets look at an example :

 
class Outer{ 
      //code
      class Inner{
        //code
            }
       }

 
  How do we use this inner class ?  Lets look at that now :
 
// Working example

 public Class OuterClass {
 
private int data = 20;
class InnerClass {
 public void printMessage(){
    System.out.println(" Data is :" +data);
}
}
public static void main(String args[]){
         
 OuterClass out = new OuterClass();
 OuterClass.InnerClass in = out.new InnerClass(); // Look for syntax
 in.printMessage();
 }
 }

Some good points :

1. Inner class can access both private and public members of outer class .
2. Inner class cannot be instatiated alone. it is always attached to an outer class instance.
3. Java compiler creates two class files, One  OuterClass.class and second one OuterClass#InnerClass class file for the inner class.

Hello Lamda

                                     
                                       From the beginning of java 8 release, We are hearing about something called lamda . Here i try to explain all that one should know about this mysterious thing called lamda which is one of the feature introduced in Java 8. For a functional programmer ( who uses different programming languages than java) , lamda expressions is something which they can relate to . A traditional object oriented java programmer will not expect such a feature to get introduced in Java. I will try to explain how lamda differs from object orientedness of java.
    Lets look at a case where we have to execute a piece of code multiple times . An example may be an ActionListener on a button click


// Defined using Inner classes



button.setOnAction(new EventHandler<ActionEvent>() {

   public void handle(ActionEvent event) {

      System.out.println("Thanks for clicking!");

   }

});



     Here , The handle method is executed multiple times on each button click . This is an example of a code which is executed multiple times in an application . Same can be applied to a
Comparator which is passed to a Collections.sort method for sorting.  The compare method inside the defined comparator is called multiple times.Uptill now these kind of codes were passed as an object where a method is defined inside it . From now onwards we could pass it as a block of code, Which is to be executed .  This is more or less what lamda expressions are

  Lets look at it in detail.  Let me take the example of a String Comparator which does the comparison by length .  I will write the old way of doing it
 

   ArrayList<Strings> sortingNeeded = new ArrayList<String>();

   sortingNeeded.add("looooooongOne");

   sortingNeeded.add("shortOne");

  

   Collections.sort(sortingNeeded, LengthComparator);

  

   // LengthComparator code is defined as :

  

   class LengthComparator implements Comparator<String> {

   public int compare(String first, String second) {

      return Integer.compare(first.length(), second.length());

   }

}

Lets now do it the Lamda way :

    ArrayList<Strings> sortingNeeded = new ArrayList<String>();

   sortingNeeded.add("looooooongOne");

   sortingNeeded.add("shortOne");

   // The block of code which needed to be executed here  is : Integer.compare(first.length(), second.length()) , 
//But since java is strongly typed, We have to provide the type of arguments as 
// well, So the code comes to be :

  

   Collections.sort(sortingNeeded, (String first, String second)-> Integer.compare(first.length(), second.length()) );



Whaat ?  isnt ?   Yes ,You have just seen one form of lambda expressions in Java: "parameters, the -> arrow, and an expression". . If the code carries out a computation that doesn’t fit in a single expression, write it exactly like you would have written a method: enclosed in {} and with explicit return statements. For example,



(String first, String second) -> {

   if (first.length() < second.length()) return -1;

   else if (first.length() > second.length()) return 1;

   else return 0;

}



Now you may be asking what if we have return  values , how do we specify the type of the return value . The answer is that you can never provide the return type , its always inferred from the context.

 Also if the type of the arguments can be inferred , You could avoid that too ,

  Comparator<String> comp = ( first,  second)-> Integer.compare(first.length(), second.length());

    here the type of first and second can be inferred from the context that it will be strings as the lamda function is assigned to a variable which is of the type string comparator. Hence we can avoid the type.

What if there is no argument type?
 yes , ()-> System.out.println("Hello")  is a valid  lamda expression .


 You are not at all expected to be clear about lamda expressions with this post . There will be a lot of questions , Where is this code executed ? What if an exception occurs  ? Where exactly do you use the lamda expressions . All this and much more on coming topics. Stay tuned.  Happy Coding :)