Tuesday, 25 June 2013

Primitive Data Type

Intro

The amount of value that can hold by a variable is know as data types. There are two main types in programming language. 

1. Primitive Data Type.
2. User Defined Data Type.

Here some introduction about Java language primitive data type. Java programming language supports 8 primitive data types. A primitive type is named by a reserved keyword. Primitive values do not share state with other primitive values.

byte

The byte data type is an 8-bit signed two’s complement (http://en.wikipedia.org/wiki/Two's_complement) integer. The byte data type can be useful for saving memory in large arrays.

byte Range ::: minimum value : -128 , maximum value : 127
Default Value : 0

short

The short data type is a 16-bit signed two’s complement (http://en.wikipedia.org/wiki/Two's_complement) integer. You can use a short to save memory in large arrays. 

short Range ::: minimum value : -32,768, maximum value : 32,767
Default Value : 0

int 

The int data type is a 32-bit signed two’s complement integer. It has a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647.

int Range ::: minimum value : -2,147,483,648, maximum value : 2,147,483,647
Default Value : 0

long

The long data type is a 64-bit signed two’s complement (http://en.wikipedia.org/wiki/Two's_complement) integer.

long Range ::: minimum value : -9,223,372,036,854,775,808, maximum value :
9,223,372,036,854,775,807
Default Value : 0L

float 

The float data type is a single-precision (http://en.wikipedia.org/wiki/Single_precision_floatingpoint_
format) 32-bit IEEE 754 (http://en.wikipedia.org/wiki/IEEE_754-2008) floating point.

Default Value : 0.0f

double

The double data type is a double-precision (http://en.wikipedia.org/wiki/Double_precision_floatingpoint_
format) 64-bit IEEE 754 (http://en.wikipedia.org/wiki/IEEE_754-2008) floating point

Default Value : 0.0f

boolean

The boolean data type has only two possible values: true and false.

Default Value : 0.0d

char

The char data type is a single 16-bit Unicode character (http://en.wikipedia.org/wiki/Unicode).
char Range ::: minimum value : ‘\u0000', maximum value : ‘\uffff’

Default Value : ‘\u0000’

Friday, 21 June 2013

Java Class Loader

Intro

  • Java class loader is part of Java Runtime Environment(JRE) that dynamically loads java class into Java Virtual Memory(JVM).
  • JRE doesn't need to know about files and file system, because classloader take care of this.
  • Java platform uses Delegation model for loading class.
  • The classloader is responsible for locating libraries, reading their content and loading the classes contained within the libraries.
  • Each Java Class must be loaded by class loader.
  • When JVM started three class loaders are used.
    • Bootstrap Class Loader.
    • Extension Class Loader.
    • System Class Loader.

Bootstrap Class Loader


  • The bootstrap classloader loads the runtime classes from rt.jar files and others.
  • Runtime classes can be located in the <JAVA_HOME>/jre/lib folder.
  • It is virtual machine built in class loader.
  • It doesn't have parent class loader, but it may server as parent of class loader.

Extension Class Loader.

  • The extension class loader loads the libraries in the extension folder.
  • Extension folder located in <JAVA_HOME>/lib/ext or any other directory specified in the java.ext.dirs System  Property.
  • It is implemented by the sun.misc.Launcher$ExtClassLoader

System Class Loader 

  • Loads the class include the JAR files specified by the system property java.class.path.
  • If a JAR file on the class path has a manifest with attribute Class-Path, JAR files specified by the Class-Path attribute will be also searched.
  • By default java.class.path property's values is .(dot) the current directory.

  • It can be changed using command line option -classpath or -cp or setting CLASSPATH environment variable .
  • The command line option overrides setting of the CLASSPATH environment variable.

XSS - Cross Site Scripting

  • Cross Site Scripting, better know as XSS, a subset of HTML injection.
  • XSS is most prevalent and pernicious security issue.
  • XSS flaws occur whenever  on web application takes data that originated from user and sends it to browser without validating.
  • XSS allows attackers to execute script in  the victim's browser, which can hijack user sessions, deface website, insert hostile content, conduct phishing attacks, and take over the user's browser using scripting malware.
  • The malicious script is usually JavaScript, but any scripting language the supported by victim's browser is potential target for this attack.
  • There are three types in XSS.

Three types of XSS

  • Reflected.
  • Stored.
  • DOM Injection.

Reflected ???

  • Reflected XSS is easiest to exploit.
  • A page will be reflect user supplied data directly back to the user.

Stored

  • Stored XSS takes hostile data and store it in a file, a database, or other backend system and then at a later stage displays the data to user , unfiltered.
  • This is extremely dangerous in systems such as CMS, blogs, or forums where a large numbers users will sees input from other individuals.

DOM Injection

  • With DOM based XSS attacks, the site's JavaScript code and variables are manipulated rather then HTML element.


  • XSS attack can be blend or hybrid of all three types.
  • Non standard or un expected browser behaviors  can introduce subtle attack vectors.
  • XSS also potentially reachable through any components that the browser uses.


Thursday, 20 June 2013

Web.xml or Deployment Descriptor

  • Central configuration file of all web applications.
  • Defines servlets, servlet filters.

From Servlet Spec

  • The DD conveys the elements and configuration information of a web application between Application Developers, Application assemblers and Deployers.
  • The following type of configuration and deployment information are required to be supported by a web application DD for all servlet container.
    • ServletContext Init Parameters
    • Session configuration
    • Servlet declaration
    • Servlet mappings.
    • Application LifeCycle Listener class.
    • Filter definition and filter mappings
    • MIME type mappings
    • Welcome file list
    • Error page
    • Locale and Encoding mappings
    • Security Configurations, including login-config, security-constraint, security-role, security-role-ref, run-as.


web-app  Element

  • Web-app is the root deployment descriptor for a web application.
  • The element has a required attribute version to specify to which version of the schema the deployment descriptor conforms.

description Element

  • This element is to provide text describing the parent element.
  • This element occurs under other multiple elements.
  • This element has optional attribute xml:lang to indicate which language is used in description.
  • The default value of the attribute is English("en")

display-name Element

  • This element contains short name that intended to be displayed by tools.
  • The element has optional attribute xml:lang to indicate language.

icon Element

  • The icon contains small-icon and large-icon element that specifies the filename for small and large GIF and JPEG images used to represent the parent element in GUI tool.

distributable Element

  • The distributable element indicates that this Web application is programmed appropriately to deployed in distributed servlet container.

context-param Element

  • The context-param contains the declaration of the Web application's servlet context initialization parameters.

filter Element

  • The filter declares a filter in Web application.
  • The filter is either mapped to servlet or URL pattern in the filter-mapping element, using the filter-name value to reference.
  • Filter can access the initialization parameter declared in DD at runtime via FilterConfig Interface.
  • The filter-name is logical name for filter, it must be unique within the web application. It must not be empty.
  • The filter-class is fully qualified class name of the filter.
  • The init-param element contains name value pair as an initialization parameter of this filter.
  • The optional async-supported element, when specified, indicates that the filter supports asynchronous request processing.

filter-mapping Element

  • The filter-mapping is used by the container to decide which filter to apply to a request in what order.
  • The value of the filter-name must be one of the filter declaration in DD.
  • The matching request can be URL pattern or servlet-name.

listener-class Element

  • The listener indicates the deployment properties for the application bean.
  • The sub element listener-class declares that a class in application must be registered as web application listener bean.

servlet  Element

  • The servlet element is used to declare a servlet.
  • It contains declarative data of servlet.
  • The servlet-name element contains canonical name of the servlet, each servlet name is unique within the application. The servlet-name must not be empty.
  • The servlet-class contains fully qualified class name.
  • The run-as element specifies the identity to be used for the execution of a command.
  • The element load-on-startup indicates that this servlet should be loaded on startup of the web application. The element content must be integer indicating the order in which servlet should be load. If the value is negative ,  or the element is not present, the container is free to load servlet whenever to choose. If the value is positive or 0, the container must load and initialize servlet as the application is deployed. The container must guarantee the servlet marked lower integers are loaded before servlet marked as higher integers. The container may choose the order of loading of servlet with load-on-startup value.


mulitpart-config

  • If the servlet supports file upload and processing of mime-multipart request, the configuration for the same can be provided by multipart-config element, this element can be used to specify location where the file can be stored, maximum size of the file, maximum request size and size threshold.
  •  

servelet-mapping

  • Defines mapping between servlet and URL pattern.

session-config

  • The element defines session configuration for this web application.
  • The session-timeout sub element specifies timeout interval for all session created in this web application.
  • The specified timeout can be whole number of minutes.
  • If the timeout is 0 or less, the default behavior of session never time out.

mime-mapping

  • It defines mapping between extension and mime type. The extension element contains a string description an extension, such as txt.

welcome-file-list

  • Contains ordered list of welcome files. The sub element welcome-file contains name of the file. Default welcome is index.html

error-page Element

  • Error page element contains mapping between error code or an extension type to the path of resource in the web application. The sup element extension type contains fully qualified class name of a Java extension type. The sub element location element contains the location of the resource in the web application relative of the web application.


What is Servlet ?

What is Servlet ?

  • Servlet is Java technology based web component, managed by web container, that generates dynamic content.
  • It is platform-independent component.
  • Java classes that are compiled to platform-neutral byte code that can be loaded into and run by java technology enabled web server.
  • Containers, sometime called servlet engines, are Web Server extensions that provide servlet functionality.
  • Servlet interact with web client via request/response paradigm implemented by the servlet container.

What is a Servlet Container ?

  • Servlet container is part of Web Server or Application Server that provides network services over which request/response are sent.
  • Decodes MIME based requests.
  • Formats MIME based responses.
  • A Servlet Container also contain and manages servlet through their lifecycle.
  • A servlet container can be built into Web server or installed as an add-on component to web server via that Server's native extension API
  • SC can also be built into or possible installed into web based application server.
  • All SC must support HTTP as a protocol for request and response.
  • Also addition request/response based protocol such as HTTPS can be supported.
  • The require version of the HTTP specification that container must implement HTTP 1.0 and HTTP 1.1.

HTTP


HTTP

  • Most web application run on HTTP.
  • HTTP is a stateless series of client/server message exchange protocol.
  • Normally client is web browser, server is web server/application server.
  • The client initiates communication by requesting a specific resource.
  • The resource may be a HTML file, or dynamically generated output.
  • HTTP originally designed for requesting and serving static HTML documents.
  • HTTP is an application layer protocol 

  • One of cons of HTTP is, it is stateless protocol. It doesn't maintain the state between multiple request from same client. Server don't know whether the next request is come from same user/client.
  • The server has the client's address, but it will only be used to return current requested document.
  • If we try to build a web application with complicated use case, the above won't help.
  • Simple example is a secure web application must authenticate it users. To do this, the request in which client send username and password must associate with all other request coming from that client during the user session.
  • HTTP is also a text based. Mating text based technology to a strongly type based such as Java creates significant amount of data-binding work.

Saturday, 15 June 2013

Annotation

  • Annotation, a form of metadata, provide data about program that is not part of the code. Or an annotation is simply to associate information with the annotated program element.
  • They have no direct effect on the operation of the code they annotate.
  •  

Uses of Annotations

  • Information for the compiler : Annotation can be used by the compiler to detect errors and suppress warnings.
  • Compile-time and deployment time processing : Software tools can process annotation information to generate code, XML files and so forth.
  • Runtime Processing : some annotation are available to be examined at runtime.


  • Annotation will look like the following.

@Annoteexample
  • '@' indicates to the compiler what follows is an annotation.
  • Annotation can contains element-value pair.

@Author{
Name="B";
Date="5/20/2013"
}
Class my class{...}

@SuppresWarnings(value="unchecked" )
Void myMethod(){}

@SuppresWarnings("unchecked" )
Void myMethod(){}

  •  If the annotation has no element, then parentheses cab be omitted.
  • It is possible multiple annotation on the same declarations.

@Author(name ="B")
@Ebook
Class myclass {...}

  • The annotation can be one of the type defined in the java.lang or java.lang.annotation packages.
  • There are three kind of annotations, normal annotation, marker annotation and single-element annotation.


Where Annotation can be used

  • Annotation can be applied to declaration : declaration of classes, method, fields, enums, interface, annotation types, formal parameters, constructors, local variables and other program elements.
  • Annotation can be used in enum constants, such annotation placed immediately before the enum constant.
  • It is compile-time error if a declaration is annotated with more than one annotation for a given annotation type.

Declaring a Annotation Type

  • The Annotation Type definition looks similar to an interface definition where the keyword interface is preceded by the sign @.
  • Annotation Type is form of interface.
  • They can define default value.

Syntax

@interface ClassPreamble{
String Author();
String date();
Int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy default "N/A";
String[] reviwers();
}

Usage

@ClassPremble(
Author = "A";
Date = "5/21/2013",
currentRevision = 6;
lastModified ="5/15/2013",
lastModifiedBy ="G",
Reviwers = {"F","A","E"}
)
  • To make this information in @ClassPreamble appears in Javadoc-generated documentation, you must annotate @ClassPreamble with the @Documented annotation.

// import this to use @Documented
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
// Annotation element definitions
  
}


Predefined Annotation Types

  • The predefined annotation type defined in java.lang are @Deprecated, @Override, and @SuppressWarnings

@Deprecated

  • The above annotation indicates that the marked element is deprecated and no longer be used.
  • The generates a warning whenever the program uses a method, class, or field with deprecated annotation.
  • When an element is deprecated it should be documented using java-docs.

@Override

  • This annotation informs compiler that the element is meant to override an element declared in superclass.
  • While it is not require to use when overriding a method, it helps prevent errors.

@SuppressWarnings
 
  • It tells the compiler suppress specific warnings that it would otherwise generate.

e.g.
@SuppressWarning("deprecation")
Void decreatedMethod(){..}

  • In above example, we use deprecated method, but compile omits the warning.
  • To suppress multiple warning we can use like below.

@SupressWarnings( {"unchecked", "deprecated"})

@SafeVarargs

  • This annotation when applied to method or constructor, assert that the code doesn't perform any un-safe operation on varargs params.
  • When this annotation is used the unchecked warning relate to varargs are suppressed

@Functionalnterface (Java 8.0)

  • Indicates that the type of declaration is intended to functional interface.


Annotation that apply to other Annotations

  • Annotation that apply  to other annotations are meta-annotations.
  • There are several meta-annotation defined in java.lang.annoation.

@Retention
 
  • This annotation specifies how the marked annotation is stored.

RetentionPolicy.SOURCE : retained only at source level and ignored by compiler.
RetentionPolicy.CLASS : retained by compiler at compile time and ignore by JVM
RetentionPolicy.RUNTIME : retained by JVM.

@Documented

  • This annotation indicates that type are to be documented by javadoc or other tools.

@Target


  • It marks another annotation to restrict what kind Java elements the annotation that can be applied to.