20 October 2010

1 Memory DeAllocation-Garbage Collection in Java

Memory DeAllocation or Garbage Collection in Java

A major difficulty in dynamic memory allocation in C/C++ was that the programmer is responsible for de-allocating the dynamic memory at the right time. Even though experienced programmers can do this very well, beginners and average programmers often missed the statements for de-allocated which led to memory-leak in many systems.
An object that is not referred by any reference variable will be removed from the memory by the garbage collector, this process is known as Garbage Collection
Garbage Collection is Automatically done by JVM, the Automatic Garbage Collection of Java de-allocates the dynamic memory automatically when this memory is no more used by the program. This relieves the programmer from the overhead of memory de-allocation.
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends.
Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use.
Primitive types are not objects and they cannot be assigned null.
Read More...

0 Memory Allocation in Java

Memory Allocation in Java


        All local variables are stored in a stack. local variables are de-allocated in a last in first out order as soon as the method terminates.
All dynamically allocated arrays and objects are stored in heap. They need not be de-allocated in any specific order. They can be garbage collected (removed from the memory) as and when their use is over.

Garbage Collection in Java
       An object that is not referred by any reference variable will be removed from the memory by the garbage collector. Garbage Collection is automatic.
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends.
Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use.
Read More...

0 What is Method Overloading in Java?

Method Overloading in Java

Two or more methods in a Java class can have the same name, if their argument lists are different, this feature is known as Method Overloading.
Argument list could differ in
  • No of parameters
  • Data type of parameters
  • Sequence of parameters
void print(int i){
    System.out.println(i);
}
void print(double d){
    System.out.println(d);
}
void print(char c){
    System.out.println(c);
}

Method Overloading in Java is Static Polymorphism
Calls to overloaded methods will be resolved during compile time, In otherwords, when the overloaded methods are invoked, JVM will choose the appropriate method based on the arguments used for invocation. For example, if the print method is invoked with an int argument, the overloaded print method that accepts an int parameter will be chosen by the JVM.

Example of Different implementation of Method Overloading in Java
void add (int a, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)

Methods differing only in return type
Methods differing only in return type will not be treated as overloaded methods, it will be compilation error. For Example, the below given methods will give compilation error.
void print(int i){
    System.out.println(i);
}
int print(int i)){
    System.out.println(i);
    return i;
}

Overloading the Constructors
Just like other methods, constructors also can be overloaded.

public class Student{
    public Student(){
        mark = 100;
    }
    public Student(int rollNo, double mark){
        this.rollNo = rollNo;
        this.mark = mark;
    }
}
Read More...

0 How to Invoke methods in a Java class?

Invoking methods in a class


The following statement creates a new "Student" object and assigns its reference to "student".
Student student = new Student();

All the public members of the object can be accessed with the help of the reference.
Student student = new Student();
student.setRollNo(20);
System.out.println(student.getRollNo());
 The reference can be treated as the name of an object.
For using a Student object, a programmer need not know the internal implementation details of the class. One needs to know only the public methods to use a Student object. Abstraction is achieved by hiding the irrelevant implementation details and exposing the relevant interface details.
Read More...

0 How to Create Objects in Java?

Creating Objects in Java

In Java, all objects are created dynamically. The operator "new" is used for dynamic memory allocation.

The following statement creates an object of the class Student
new Student()
The above statement returns a reference to the newly created object. Creation of objects and arrays are very similar in Java.
The following statement creates a reference to the class "Student".
Student student;
The reference "student" can be used for referring to any object of type "Student".
//Declare a reference to class "Student"
Student student;
//Create a new Student object
//Make student refer to the new object
Student student = new Student();
Read More...

0 Multidimensional Arrays in Java

Multidimensional Arrays in Java


  • Multidimensional arrays are arrays of arrays.
  • To declare a multidimensional array variable, specify each additional index using another set of square brackets.

int [][] x;
//x is a reference to an array of int arrays
x = new int[3][4];
/*Create 3 new int arrays, each having 4 elements
x[0] refers to the first int array, x[1] to the second etc
x[0][0] is the first element of the first array
x.length will be 3
x[0].length, x[1].length and x[2].length will be 4 */
Read More...

0 What is Reference variables in Java?

Reference variables in Java


Reference variables are used in Java to store the references of the objects created by the operator new
Any one of the following syntax can be used to create a reference to an int array.
int x[];
int [] x;

The reference x can be used for referring to any int array.
//Declare a reference to an int array
int [] x;
//Create a new int array and make x refer to it
x = new int[5];

The following statement also creates a new int array and assigns its reference to x
int [] x = new int[5];
 In simple terms, reference can be seen as the name of the array. Arrays can be created only using dynamic memory allocation in Java. The memory is allocated dynamically using the keyword new.

A reference type can be assigned ‘null’ to show that it is not referring to any object. ‘null’ is a keyword in Java
int [] x = null;
Read More...

19 October 2010

0 Arrays in Java

array in Java


In Java, all arrays are created dynamically. The operator "new" is used for dynamic memory allocation.
The following statement creates an array of 5 integers.

new int[5]

The above statement returns a reference to the newly created array. References in Java are very similar to pointers in C

Initializing an array in Java
An array can be initialized while it is created as follows

int [] x = {1, 2, 3, 4};
char [] c = {‘a’, ‘b’, ‘c’};

The length of an array

Unlike C, Java checks the boundary of an array while accessing an element in it
Java will not allow the programmer to exceed its boundary
If x is a reference to an array, x.length will give you the length of the array
The for loops can be set up as follows

for(int i = 0; i < x.length; ++i){ x[i] = 5; }
Read More...

0 What is Methods in Java?

Methods in Java


Methods in Java is nothing but functions (As in C) the syntax of writing methods in Java is similar to that of functions in C.
Unlike C, all methods in Java should be written inside a class.
Unlike C, there is no default return type for a Java method.
In C language, a function whose return type is not specified is assumed to return an int. In Java there is no default return type for a method. Specifying the return type of a method is mandatory in Java.
Read More...

0 What are the Operators in Java?

Operators in Java


Operators in Java are very similar to operators in C or other such languages
  • Assignment Operators
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
Read More...

0 Typecasting of primitive data types in Java

Typecasting of primitive data types in Java


Variable of smaller capacity can be assigned to another variable of bigger capacity without any explicit typecasting
int i = 10;
double d;
d = i;

Whenever a larger type is converted to a smaller type, the typecast operator has to be explicitly specified. This prevents accidental corruption of data.
double d = 10;
int i;
i = (int) d;
Read More...

0 What is Variables in Java?

Variables in Java


Declaring and using primitive data types is Java similar to that of C.
int flag;
int maxCount=100;

Unlike C, in Java, variables can be declared anywhere in the program.
int index = 10;
System.out.println(“Program starts here”);
int j = 20;
for (int index=0; index <maxCount; index++) {
int z = index * 10;
}

Best Practice while dealing with Java Variables: Declare a variable in program only when required. Do not declare variables upfront like in C.

Local Variables in Java
In Java, if a local variable is used without initializing it, the compiler will show an error

class Sample{
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}

Instance variables
Instance variables are declared in a class, but outside a method. They are also called member or field variables. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed. Visible in all methods and constructors of the defining class, should generally be declared private, but may be given greater visibility.

Class/static variables
Class/static variables are declared with the static keyword in a class, but outside a method. There is only one copy per class, regardless of how many objects are created from it. They are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.

Reference variables in Java
Reference variables are used in Java to store the references of the objects created by the operator "new"
Any one of the following syntax can be used to create a reference to an int array
int x[];
int [] x;
Read More...

0 What is Phishing in Network Security?

Phishing

Some unreliable site gets your information (passwords, bank account details, etc) without your knowledge.
Mostly phishing is done by, sending emails to the users, which will be claimed to be sent by your bank or some other reliable sites.
Most of the Phishing websites can easily be filtered using Phishing Filters.
Phishing Filters are available in Internet Explorer 7.0 and Mozilla FireFox.
To enable Phishing Filters option, click Tools, then Phishing Filter. With this option enabled, if any Phishing site is found, IE and Mozilla displays a warning icon in the status bar which means that the site may be unsafe.
Read More...

17 October 2010

0 What is ServletContext in Java?

ServletContext

        The servlet's view of the web application within which the servglet is running is defined by the ServletContext. It also allows access to resources available for it. Within a web server a ServletContext is routed at a specific path.

ServletContext Scope

        There will be one instance of the ServletContext interface associated with each web application deployed into a container.
In cases where the container is distributed over many virtual machines, there is one instance per web server per virtual machine.
Servlet that exists in a container that were not deployed as part of a web application are implicitly part of the default web application and are contained by the default ServletContext. In a distributed container,the default ServletContext is non-distributable and must only exist on one virtual machine.

ServletContext Attributes

A servlet can bind an object into the context by name.
Any object bound to a context is available to any other servlet which is part of the same application.
Following are the methods of ServletContext which allow access to this functionalty.
  • setAttribute()
  • getAttribute()
  • getAttributeNames()
  • removeAttribute()
Read More...

0 What is Requirements Engineering

Requirements Engineering

“Requirements Engineering involves all life-cycle activities devoted to identification of user requirements, analysis of the requirements to derive additional requirements, documentation of the requirements as a specification, and validation of the documented requirements against user needs, as well as processes that support these activities.”
        -DoD(Department of Defense). Software Technology Strategy.

Why Requirements Engineering?
    40 - 60 percent of known defects found in a project are errors made during requirements stage. Many software development organizations struggle to gather, document, and manage their product requirements. Most of the surveys done indicates that, incomplete and changing requirements with lack of user input and their involvement, are the major reasons why IT projects fail to deliver on schedule, within budget.

    In a software industry, no one can bear the consequences of ineffective requirements engineering. The cost of inaccurate, misunderstood, and not signed off requirements affects everyone in the industry in terms of time, money and opportunities lost. The result will be of total chaos in terms of frustration, confusion, mistrust, higher cost, lack of quality, overtime, over budget, a general lack of understanding and incapability to handle issues. The interests of all the known stakeholders in a software system, coincide more in requirement engineering phase than in other phases. This leads to exciting products, happy developers and delighted customer, if requirements are handled well, else it can become the source of frustration, friction and misunderstanding that can undermine product's business value and quality. As requirements is the base for both software development and project management activities, all stakeholders should follow an effective requirements engineering process.
Read More...

0 Servlet Cookie API in Java

Servlet Cookie API in Java

HttpServletInterface.getCookie() method is used to retrieve an array of cookies from the request object.
The cookie is the data sent as a part of the request object by the client.
The client sends only the cookie name and cookie value.

Cookie Constructor of Servlet Cookie API
Cookie(java.lang.String name, java.lang.String value) - Constructs a cookie with a specified name and value.

Methods of Servlet Cookie API
  • java.lang.Object clone(): Overrides the standard java.lang.Object.clone method to return a copy of this cookie.
  • java.lang.String getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
  • java.lang.String getDomain(): Returns the domain name set for this cookie.
  • Int getMaxAge() : Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
  • java.lang.String getName() : Returns the name of the cookie.
  • java.lang.String getPath()
  • java.lang.String getValue
  • int getVersion()
  • void setComment(java.lang.String purpose)
  • void setDomain(java.lang.String pattern)
  • void setMaxAge(int expiry)
  • void setValue(java.lang.String newValue)
  • void setVersion (int version)
API to add cookie in the Responce header
HttpServletResponse
Method:- void addCookie(Cookie cookie)

API to Read cookie from the client
HttpServletRequest
Method:- Cookies[] getCookies()
Read More...

0 What is Cookie?

Cookies

   Cookies are some plain text files mainly used for session tracking. A Cookiie is an object created ny server which contains the state information and will be sent to the client browser and will be accepted and stored by browser (Provided Cookies are not disabled at the browser). In otherwords,

Cookies in Java
The class Cookie in the package javax.servlet.http can be used to create a cookie. This java class Cookie has a constructor that takes two string objects as parameters- name and value.

Cookie as a Session tracking Mechanism
Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported by all servlet containers. The servlet container sends a cookie to the client. The client will then return the cookie on each subsequent request to the server unambiguously associating the request with a session. The name of the session tracking cookie must be JSESSIONID.

Cookie is a threat to privacy?
A cookie is an object that a server creates and places on the client when the client connects to it. A cookie contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online bookstore. A cookie can save the recent item you visited on that site and other information. So, each time he or she visits the online bookstore, it will be displaying recent item you have visited.
The names and values of cookies are stored on the client machine. Some of the information that is saved includes the cookie’s:
  • Name
  • Value
  • Expiration date
  • path
Advantages of Cookies
  • Cookies are the simplest and most effective of all session tracking mechanisms
  • As cookies are plain text files, they are never interpreted or executed and cannot be used to insert viruses
Disadvantages of Cookies
  • Some browsers doesn't support cookies.
  • Cookies cannot be stored on the client side if the browser has disabled the cookies. So, cookies cannot be used as a session tracking mechanism in such cases.
  • Cookies presents a significant threat to privacy.
Read More...

0 HTTP Session Tracking Java

Importance of Session Tracking


HTTP protocol is Stateless protocol
 In HTTP protocol, Web servers and web browsers will transfer hypertext and images (sometimes files like swf etc also).
When a client (Web browser) makes a request for a page or a file, the web server locates it and send back the requested file. Once the web server sends the requested file back to the web browser, there ends the connection. No session or state is maintained between the client and server, Otherwise it would increase the overheads of keeping a lot of sessions alive between the client and the server that would pose a serious performance issue. While this model scores from a performance viewpoint, it becomes a severe constraint when designing applications for the Web.

Importance of Session Tracking
Consider a client browser downloads a page from a server, and then subsequently clicks on a hyperlink on the page to connect to another related page as part of the workflow of an application. In this case, the server has no way of knowing that it is the same client who now wants to access another related page as part of the work-flow of the same application. User-specific data on the first page is something that the server will not be able to relate to the subsequent page, because as far as the server is concerned, it is a fresh hit even though the same user or client has made a hit to another subsequent page as part of the workflow of the application. The server is therefore, not able to maintain state (user or client specific data between accesses by the same client to different pages of an application.

This problem can be overcome if a session is kept alive between a client and a server. For example, consider a typical scenario of a client application connecting to a database server. Once the client connects to a database, a session is established between the client and the database server. The client can invoke a stored procedure as part of its application logic. The call to the stored procedure can return data to the client that can be conditionally evaluated and different branches of execution can be initiated as part of continuing with the same application.

The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. To build effective Web applications, it is imperative that a series of different requests from a particular client can be associated with each other. Many strategies for session tracking have evolved over time, but all are difficult or troublesome for the programmer to use directly. State maintenance and session tracking became serious bottlenecks for designing effective Web-based applications. The cookie evolved as a solution to the problem of state maintenance and session tracking.
Read More...

0 Why HTTP protocol is Stateless protocol

HTTP protocol is Stateless protocol

In HTTP protocol, Web servers and web browsers will transfer hypertext and images (sometimes files like swf etc also).
When a client (Web browser) makes a request for a page or a file, the web server locates it and send back the requested file. Once the web server sends the requested file back to the web browser, there ends the connection.
No session or state is maintained between the client and server, Otherwise it would increase the overheads of keeping a lot of sessions alive between the client and the server that would pose a serious performance issue. While this model scores from a performance viewpoint, it becomes a severe constraint when designing applications for the Web which needs session tracking.
Read More...

0 How to Access HTTP Request Header in Java?

Accessing Request Header in Java


In Java, HTTP request headers can be accessed by the following methods of the HttpServletRequest interface.
  • getHeaderNames
  • getHeader
  • getHeaders
     To access the value of a header associated with a given name getHeader() is used. In case there are multiple values associated with a given name getHeaders() is used such as cachecontrol header. getHeaders() returns an enumeration of the string object associate with a given header name. If getHeader() is used to access the header having multiple values then the first value will be returned.
Read More...

0 What is Http Request Header?

Http Request Header


The Http Request Header contains the client side information which may be useful for the web server to generate responce. Http Request headers are very much different from the Form data. Request Headers are directly sent by the browser. Request headers comes immediately after POST or GET request line.
The Http Request object includes the following headers: Host, Accept-Encoding, Accept, Cookie, Host, Referrer, User-Agent,Connection etc.

Accessing Request Header in Java

In Java, HTTP request headers can be accessed by the following methods of the HttpServletRequest interface.
  • getHeaderNames
  • getHeader
  • getHeaders
Read More...

12 October 2010

0 init service destroy methods of Servlet

The init() method is executed only once.
The service() method is executed against each request made by the client.
The destroy() method is executed only once when the tomcat server is shut down.
Read More...

1 What is GenericServlet?

GenericServlet


GenericServlet is a class which can be used for easy servlet programming than using Servlet interface.
Most often a web programmer will be intersted only in the service method of Servlet interface. But For implementing the Servlet interface, the programmer has to implement all the methods of it.

      The class GenericServlet of javax.servlet package implements the servlet interface. And GenericServlet implements the init() and destroy() methods. The service() method is left as an abstract method for the servlet programmer to implement. So, for creating a servlet, it is easy to extend the GenericServlet class than to implement the Servlet interface.
Read More...

0 Request Handling using Servlet

Request Handling using Servlet


The servlet can handle the request only after proper initialization. The request handling phase is carried out by the service method of the servlet life cycle. The service method of the Servlet takes ServletRequest and ServletRespose as the parameters. HTTPRequest object holds information about the request, client and the form data. Servlet then create a response to the request by using the provided object of type ServletResponse. For a HTTP request, the request and response objects are of type HttpServletRequest and HttpServletResponse respectively.

    Most of the containers will create only one instance of a Servlet. The same instance is used for servicing all the client request. For each client request, the container executes the service method in a thread. So for multiple client requests, only multiple threads are created and not multiple objects. This model requires lesser memory and lesser cpu time compared to the multiple object model.

    The Servlet need not to be alive throughout. It can be active in a container for milliseconds or as long as the container is up or any amount of time in between. Before unloading the servlet from the memory it may be required to release the resource or save the persistence state. To do this the servlet container provides the destroy method which is called by the server before removing the servlet from the memory. But before calling the servlet destroy() method servlet container waits for the threads that are running in the service to either complete, or exceed a server defined time limit. Once the destroy is called no further requests can be processed by that instance of the servlet. In order to process new requests servlet container needs to create a new instance of the servlet's class. Once the destroy method finishes, the servlet container releases the servlet. And is collected by the garbage collector.
Read More...

0 Adavntages of Servlets over CGI

Adavntages of Servlets over CGI

  • Servlets are much faster than CGI scripts.
  • Standard API's of Servlet is supported by many container vendors.
  • Servlet have all the advantages of the Java language.
  • Servlet can access the large set of APIs available for the Java platform.
Read More...

2 What is a Servlet Container in Java?

Servlet Container


      A standalone Java program is directly invoked by the end user and starts its execution from the main method. But in case of a servlet, the client makes a http request to the Web-Server in order to execute the servlet. For the servlet to execute it has to be loaded into the memory, receive the client request and respond back to the client. These responsibilities are carried out by a service known as the Servlet container.

Services provided by Servlet Container

Network Service
The Servlet Container along with a web server or application server, provides the necessary network services so that the request and response can be communicated over the network between the client and the server.

Coding/decoding
The container decodes MIME (Multipurpose Internet Mailing Extensions) based requests and then passes on the request object to the servlet. Similarly formats the response generated by the servlet into MIME based responses so that the client browser understands the output generated by the servlet.

LifeCycle Management
It manages the lifecycle of the servlet.

Servlet Container can either be a part of the host web server or installed as an add-on component to a Web Server.
       Servlet Container can also be built into Application Servers. HTTP protocol is supported by all the vendors for requests and response. But along with HTTP they may support other request/response based protocols such as HTTPS (HTTP over SSL).
Read More...

0 What is Servlet in JEE Java?

Servlets


       Servlets are Java codes which is used to generate dynamic webpages. Servlets are programs written in Java code and will be executed in a webserver. That’s why named as servlet similar to applet which is executed at the Browser (client end). Servlets are used for generating the dynamic pages. Servlets are not meant for any specific client server protocol . But, as it is mostly used by the HTTP protocol, word “Servlet” refers to HTTPServlet. Servlet was introduced by the Sun Microsystems as an alternative to CGI. The output of a servlet can be a HTML/XML/Text or any other format as well.
Read More...

11 October 2010

0 What are JEE containers?

The following are the JEE containers.

Application client container
Application client container is the one which is responsible for managing the application client components. Both application client and its container resides at the client machine and are executed on the client end. Example of application container is JVM.

Applet container
Applet container is the container to manage the execution of applets. Examples of an applet container include Web browser and applet viewer.

Enterprise JavaBeans (EJB) container
Enterprise JavaBeans (EJB) container is used to manage the execution of EJB component of the J2EE application. Both the EJBs and its container run on the J2EE server. J2EE server provides the EJB container, and an example of J2EE server is WebLogic.

Web container
Web container is used to manage the execution of the Servlets and the JSP. Both the Web components and its container run on the J2EE server. An example of a web container is Tomcat.


Responsibilities of JEE containers
  • Life cycle Management- Creating and deleting components
  • Persistence- Saving information in the components
  • Naming- Recording the name of a server component and locating it for the client.
  • Deployment- Placing components in the server
  • Messaging- Exchanging information between components.
Read More...

2 What is JEE Architecture?

JEE Architecture

JEE follows the distributed multi-tiered application approach which means the entire application may not reside at a single location, but distributed. And the applications is divided into various tiers. J2ee application is composed of various components which can be created by the different developers and then assembled together. These components can be installed on different machines across various tiers. And the distribution of application components across the solely different tiers depends upon the functionality it performs.

JEE Architecture Diagrom

J2ee application tiers are as follows
  • Client Tier (Web Browser or any other kinds of clients)
  • Web tier
  • Business Tier
  • Enterprise Information tier (Database or sometimes XMLs or flatfiles)

Various JEE Components

Components are self contained piece of software that are reusable across applications and are configurable external to the source code.
J2EE components are of three types : client component, web component and business component. The client components interact with the user, the web components interact with the web browsers using the HTTP protocol, and the business components interact with the application server and execute the business logic.


Client component of JEE architecture

Client components is of two types : web client and application client.
  • A web client, generally a browser, sends a request to the server and renders the webpage sent back by the server. However, it may not perform any complex tasks such as querying a database or performing any complicated business tasks and hence is also referred to as thin client. The complex tasks are performed on the server. For displaying web pages with applets, the web clients may require Java plug-ins and security policy files for executing the applets.
  • An application client is a standalone application that doesn’t run in browsers. It can access components in the business tier directly. Note that web clients that require access to a servlet running in the Web tier can open an HTTP connection with the servlet.

Web component of JEE architecture

Web components for java are Servlets and JavaServer Pages (JSP). A servlet receives HTTP requests from the client, processes them, and returns the output. It can also generate dynamic responses. Similar to servlets, JSP also create dynamic web pages. JSP pages are converted into servlets and executed within a servlet container. They are used to display the results processed by a servlet.


Business component of JEE architecture

Business components implement the business logic or the functional process logic that defines the business rules and constraints. For example business process such as withdrawing amount from the bank. Business components are of three types : session beans, entity beans, and message-driven beans. Session beans represent a session with a client. Being a transient object, they lose their data on completion of the session. On the other hand, entity beans are persistent objects and so retain data even after the session. They represent a row of data in a database table. Message-driven beans are for receiving the receiving Java Message Service (JMS) messages asynchronously.
Read More...

07 October 2010

0 Url Rewriting using for Session Tracking

Session Tracking by Url Rewriting


The below given is the core idea of Session Tracking using URL Rewriting in JAVA
  • Client appends some extra data on the end of each URL that identifies the session
  • Server associates that identifier with data it has stored about that session
E.g. http://host/filePath/fileName.html;jsessionid=1234

Advantages of Session Tracking by Url Rewriting
  • URL Rewriting can be used when working with the browsers that don’t support cookies.
  • URL Rewriting can be used when the user has disabled the cookies.
  • URL Rewriting also supports anonymous session tracking.

Disadvantages of Session Tracking by Url Rewriting.
  • Url Rewriting has Security risk : Session id appears in the URL , it can be easily seen by other users: Users may copy and paste those link without knowing attached session id which compromises the security.
  • Server log files may record the Referer header which may record the session id in the log.
  • Must encode all URLs that refer to your own site.
  • All pages must be dynamically generated.
  • Fails for bookmarks and links from other sites.
Read More...

0 What is constructor in Java

What is constructor in Java?

A constructor is a special method that is called to create a new object. It is not mandatory to write a constructor for the class. Constructor can be treated as a readily available, implicit method in every class.

If a user defined constructor is available, it is called just after the memory is allocated for the object.

If no user defined constructor is provided for a class, the implicit constructor initializes the member variables to its default values.

Numeric data types are set to 0,
Char data types are set to null character(‘\0’),
Boolean data types are set to false,
Reference variables are set to null

      The user defined constructor is usually used to initialize the data members of the objects to some specific values, other than the default values. A constructor method will have the same name as that of the class. A constructor method will not have any return type, not even void.

Just like other methods, constructors also can be overloaded.

The constructor without any parameter is called a default constructor.
Read More...

0 How to add Comments in Java

How to add Comments in Java

In java, two kinds of commenting options are available, single line comments and multiline comments.

A single line comment in Java will start with //

A multi line comment starts with a /* and ends with a */

Single Line Comments in Java
// This is a single line comment in Java

Multi-Line Comments in Java
/* This is a multi line
comment
in Java */
Read More...

0 Primitive Data Types in Java

Integer Data Types in JAVA

byte- 1 byte
short- 2 bytes
int- 4 bytes
long- 8 bytes

Floating Data Types in JAVA

float- 4 bytes
double- 8 bytes

Textual Data Types in JAVA

char- 2 bytes
The char data type in Java is 2 bytes because it uses UNICODE character set to support internationalization.

Logical Data Types in JAVA

boolean- 1 byte (true/false)

All numeric data types are signed
The size of data types remain the same on all platforms

UNICODE is a character set which covers all known scripts and language in the world.

Declaring and using primitive data types is Java similar to that of C.
int iCount;
int flag=100;

Unlike C, in Java variables can be declared anywhere in the program. and the best practice is Declare a variable in program only when required. Do not declare variables upfront like in C.

In Java, if a local variable is used without initializing it, the compiler will show an error.
Read More...

06 October 2010

0 What is JVM-Java Virtual Machine?

A virtual machine which will execute java byte code (.class file) is called Java Virtual Machine or the JVM. In other words, the compiled java code -the java byte code (.class file) is in the machine language format of a machine known as the Java Virtual Machine or the JVM. We always needs a JVM to execute the byte code. JVM is not a real machine, it is just a virtual machine; implemented in software.

JVM is platform dependent, Java Code is platform independent.

JVM is platform dependant; that is, there is one JVM for Windows, another one for UNIX, yet another one for Mac etc. All JVMs accept the same input, the byte code. Hence java code is platform independent- "write somewhere, run anywhere". Its JVM which interprets the byte code into the machine language format of the platform on which it is running.
     The same byte code can be run on any platform, if the JVM for that platform is available.
The JVMs for all platforms are available free (http://java.sun.com/) and hence we say that the byte code runs in all platforms.
Read More...

0 What is Java Compiler?

The java compiler is the program which compiles a .java file into byte code (.class files).

       As you all know, the source code of Java will be stored in a text file with extension .java, the Java compiler compiles the .java file into byte code which will be in a file with extension .class

       Byte Code is NOT in the machine language format of the hardware platform on which the code is compiled, that means the hardware processor cannot understand the byte code (Languages like C compiles the program into the machine language format of the hardware platform on which it is running). Instead, the byte code is in the machine language format of a machine known as the Java Virtual Machine or the JVM. That means you always need a JVM to execute the byte code.

       JVM is not a real machine, it is just a virtual machine; implemented in software.
Read More...

05 October 2010

0 What is UML(Unified Modeling Language)?

Unified Modeling Language (UML) is a set of diagrams which pictorially represent object oriented design.
UML is mostly used by software engineers to communicate design.
In OO Design Pictures are easier to understand than textual explanation.
UML Class diagram is a technique to represent classes and their relationships pictorially.

Some notations in UML
  • ‘+’ before a member (method or behavior) indicates ‘public’
  • ‘-’ before a member (method or behavior) indicates ‘private’
Read More...

0 What is Inheritance in Java OOP?

Inheritance is the feature by which one class can acquires the properties and functionality of another class.

           Inheritance is important as it supports the concept of hierarchical classification. Inheritance provides the idea of re-usability of code and each sub class defines only those features that are unique to it.
Read More...

0 What is Polymorphism in Java OOP?

Polymorphism is a feature that allows one interface to be used for a general class of actions. An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface.

        In Java, Polymorphism can be easily explained as the Method Overloading. In fact, Method Overloading is a way to achieve polymorphism.

      Method Overloading the practice of using same method name to denote several different operations.
In the case of Method Overloading any number of functions can have the same name as long as they differ in any one of the following
  • Type of arguments
  • Number of arguments
Read More...

0 What is Abstraction in Java OOP?

The one who is driving a car need not know how the car engine works.
Consider the case of Stack, programmer need to know just how to invoke the push method and pop method to make the Stack object work. But internally, Stack can be implemented using an array or a linked list, programmer need not know this to use the Stack object.

Thus Abstraction is the process of exposing only the relevant details and ignoring (hiding) the irrelevant details (Don't get confused with "datahiding" of the "Encapsulation").
Abstraction simplifes the understanding and using of any complex system.
Another example, user does not have to understand the internal implementation of a software object to use it.
Read More...

4 Difference between Class and object in Java?

Difference between Class and object in Java

"Student" is a class. And "Jenna" is an object of the class "Student". And "John" is another object of the class "Student".
A Class is template for an object, a user-defined datatype that contains the variables and methods in it.

           A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features).
That is, Class is a blue print used to create objects. In other words, each object is an instance of a class.
One class can have multiple number of instances. (There can be Number of instances of the class "Student", like "Jenna", "John" etc).

A class is a blue print, in which its mentioning what all variables it (it means an object of that class) will have, what all methods it will have.
Read More...

0 What is Encapsulation in Java OOP

The Encapsulation, an object-oriented concept can be correlated with either data hiding or data bundling.

In an object-oriented concept, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:
  1. A mechanism for restricting access to some of the object's components (Access restriction to the variables of an object using the "private", "protected", "public" etc).
  2.  A mechanism that facilitates the bundling of data with the methods(functions) operating on that data (Think about an object with some private variables and some public getter and setter methods).

The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus information hiding is defined as a separate notion by those who prefer the second definition.
    Consider the case of Java, we can implement various levels of access restrictions using "private", "protected" or "public", So Encapsulation is always not about data hiding.
Encapsulation is the process of binding code and data together in the form of a capsule.

Java Example for Encapsulation
Consider a class Stack, the data could be stored in an array which will be private.
  • The methods push and pop will be public.
  • A program cannot access the array directly from outside the class.
  • A program can access the array indirectly through the push and pop methods.
          In other words, Encapsulation can be defined as the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The data is not accessible to the outside world and only those functions that are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. The insulation of the data from the direct access by the program is called data hiding.
         In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (i.e. Object is a capsule encapsulating data and behavior). All communication to it is through messages (i.e function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface.
Read More...

0 What is a Class in Java?

A Class is a blue print used to create objects.
A Class is a software template that defines the methods and variables to be included in a particular kind of Object.
Examples - Automobiles, Bank Account, Customer

A class contains state and behavior.

State (Variables)
State is the variables defined inside the class.
State (Member Variables) will not be exposed to external world.

Behavior (Methods)
Behavior of a class is the methods (Functions) defined inside the class.
Behavior is exhibited by the class to external world.
Behavior of a class will be exposed to external world (Exposure can be controlled by access specifiers like private, protected, public etc).

An object is an instance of a class.
Read More...

0 What are the Limitations of Structured Programming?

In structured programming, focus is on the algorithm and importance is given to the procedure (logic) and not to the data on which these procedures operate.
The entire problem was divided into a number of smaller units Functions or Procedures.
All these units need to work on a data item to produce the result.
The data need to be global,Global data makes the code complex.
As the code size grows, maintaining code becomes difficult, sometimes impossible.
Read More...

0 What is Java?

Java is a very powerful Object Oriented programming language developed by Sun Micro systems.
Java is widely used for developing web applications, as it is open source.
Java is a platform independent language, that is "code it somewhere, run it anywhere".
Java was developed initially for consumer devices
But, now it is a popular platform to develop web based enterprise applications.
Read More...

23 August 2010

0 JAVA installation and Set Up

Installation and Set Up of JAVA in Windows and UNIX machines

Before we begin JAVA installation, some points on JAVA installation

• For executing Java Programs Java 2 SDK Version 1.4 or higher Version needs to be installed.
• Java 2 SDK Can be downloaded freely from http://java.sun.com
• IDEs for JAVA are Eclipse and Netbeans, and Eclipse can be downloaded freely and doesnot require installation

Setting Environment variables for Java
We need to set some Environmental variables.
• Environmental variable is a variable that describes the operating environment of the process
• Common environment variables describe the home directory, command search path etc.

Environment variables used by JVM

JAVA_HOME
This environment variable is pointing to the Java Installation directory. This environment variable is used to derive all other environment variables used by JVM

In Windows:
set JAVA_HOME=C:\ProgramFiles\JAVA\jdk1.4.3

In UNIX:
export JAVA_HOME=/var/usr/java

CLASSPATH

Path variable is used by OS to locate executable files
In Windows:
set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar

In UNIX:
set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.

Do the Environmental variable settings by typing the given commands in the Command Prompt and Type ‘javac’. It will display all the options of using javac as shown in the diagram. If it says bad command or file name then check the path setting.

Alternate way to set CLASSPATH
In Windows:
set PATH=%PATH%;%JAVA_HOME%\bin

In UNIX:
set PATH=$PATH:$JAVA_HOME/bin
• This approach helps in managing multiple versions of Java – Changing JAVA_HOME will reflect on CLASSPATH and PATH as well
Read More...

0 How to set Environment variables for Java

How to set Environment variables for Java?


• Environmental variable is a variable that describes the operating environment of the process
• Common environment variables describe the home directory, command search path etc.

Environment variables used by JVM

JAVA_HOME
This environment variable is pointing to the Java Installation directory. This environment variable is used to derive all other environment variables used by JVM
In Windows:
set JAVA_HOME=C:\ProgramFiles\JAVA\jdk1.4.3

In UNIX:
export JAVA_HOME=/var/usr/java

CLASSPATH
Path variable is used by OS to locate executable files
In Windows:
set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar

In UNIX:
set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.

Do the Environmental variable settings by typing the given commands in the Command Prompt and Type ‘javac’. It will display all the options of using javac as shown in the diagram. If it says bad command or file name then check the path setting.

Alternate way to set CLASSPATH
In Windows:
set PATH=%PATH%;%JAVA_HOME%\bin

In UNIX:
set PATH=$PATH:$JAVA_HOME/bin
• This approach helps in managing multiple versions of Java – Changing JAVA_HOME will reflect on CLASSPATH and PATH as well.
Read More...

0 How to get data from session Java

How to Extract data from session in Java?

Get the session

request.getSession

Extract data from session

session.getAttribute
• Do typecast and check for null
• If you cast to a generic type, use @SuppressWarnings
Read More...

0 Challenges in Session Tracking Java

support for distributed Web applications

Load balancing used to send different requests to different machines. Sessions should still work even if different hosts are hit.

support for persistent sessions

Session data written to disk and reloaded when server is restarted(as long as browser stays open).
• Tomcat 5 supports this
Read More...

22 August 2010

0 CRUD operations in MySQL Database

CRUD operations

CRUD is the acronym for Create, Read, Update and Delete. Create, Read, Update and Delete (CRUD) are the 4 basic functions of a Database or persistent storage. CRUD refers to all of the major functions that need to be implemented in a RDBMS.
Each letter in the CRUD can be mapped to a standard SQL statement:

Create        INSERT
Read        SELECT
Update        UPDATE
Delete        DELETE

CRUD operations in MySQL Database

Insert Data Into MySQL Database Table

The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Select Data From MySQL Database Table

The SELECT statement is used to select data from a database.

Syntax

SELECT column_name(s)
FROM table_name

Update Data In MySQL Database Table

The UPDATE statement is used to update existing records in a table.

Syntax

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Delete Data from MySQL Database Table

The DELETE FROM statement is used to delete records from a database table.

Syntax

DELETE FROM table_name
WHERE some_column = some_value
Read More...

20 June 2010

0 How to Remove navBar (Navigation Bar) from Blogger blog

        Did you ever notice a bar on the top of your blog as shown above? This is called the 'Navigation Bar' also known as 'Navbar'. Did you ever feel this NavBar of the blogger very irritating? Did you ever think of "How do I hide the NavBar of my Blog"
        Every blogspot blog by default recieves a Navigation Bar on the top, with buttons for switching to the next blog, searching yor blog and more. Some bloggers may find the Navigation Bar useful, But most of the bloggers may feel it irritating. If you feel that disabling the navigation bar would improve the layout of your blog then You may want to disable it.
        Blogspot is not giving you any options for hiding or disabling the so called 'NavBar', there is no menu entry to disable it, But you can still hide it.

Disabling the Blogger NavBar: Detailed Steps

Dashboard--> Layout--> Edit HTML
In the edit HTML text field, find the style defenitions( which is enclosed in { } brackets).
Then paste the below given code somewhere near other style defenitions.
#navbar-iframe {
height:0px;
visibility:hidden;
display: none !important
}
In this method, we are not particular about the position of the code pasting. Kindly refer the screen shot shown below.

In my personal experience this is a perfect hack. After these changes click on the save template button, reresh the page. If there is no navigation bar in the screen, then the Hack is perfect. Check out with all the leading browsers (atleast Internet explorer, Mozilla firefox, Safari and Google chrome).

Explanations

<style>...</style> encloses stylesheet instructions that define a page's layout. The actual layout instruction is now targeting the element of the ID navbar IFrame, which you define to not display. The !important tells the browser to override other layout defenitions for this element, if exists.

Exceptions

If there is still the navigation bar exists(hopefully it won't happen), perhaps Google has since adjusted the way their page design displays the navigation bar. If so you may need to read the HTML source code of you blog and adjust your stylesheet instructions accordingly.

Not For Newbies

The blogger navigation bar is also disabled when using FTP to transfer the blog pages to your own domain, because the navigation bar includes many elements that work only in the context of a blogger hosted blog.
However,FTP publishing(Dashboard-->Settings-->Publishing) comes with its own set of disadvantages, so a move must be carefully planned.
Please make a note that in order to switch to FTP uploading , Your blog must be public and use a classic template.
You can set your blog to be public via Dashboard-->Settings-->Permission
You can set your template to classic via Dashboard-->Settings-->Edit HTML
Read More...

18 June 2010

0 Session Tracking in Java Tutorial

• Session objects live on the server
• Sessions automatically associated with client via cookies or URL-rewriting
– Use request.getSession to get session
• Behind the scenes, the system looks at cookie or URL extra info and sees if it matches the key to some previously stored session object. If so, it returns that object. If not, it creates a new one, assigns a cookie or URL info as its key, and returns that new session object.
• Hashtable-like mechanism lets you store arbitrary objects inside session
– setAttribute stores values
– getAttribute retrieves values
• Access the session object
– Call request.getSession to get HttpSession object
• This is a hashtable associated with the user
• Look up information associated with a session.
– Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check whether the result is null.
• Store information in a session.
– Use setAttribute with a key and a value.
• Discard session data.
– Call removeAttribute discards a specific value.
– Call invalidate to discard an entire session
Read More...

0 Disadvantages of Session Tracking using Hidden Form Fields

Disadvantages of Session Tracking using Hidden Form Fields

  • Lots of tedious processing
  • All pages must be the result of form submissions

Read More...

0 Session Tracking using Hidden Form Fields

Below given is the core idea of Session Tracking using Hidden Form Fields

<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

Advantages of Session Tracking using Hidden Form Fields

Works even if cookies are disabled or unsupported

Disadvantages of Session Tracking using Hidden Form Fields

  • Lots of tedious processing
  • All pages must be the result of form submissions

Read More...

0 Disadvantages of Session Tracking using URL Rewriting

Disadvantages of Session Tracking using URL Rewriting

  • Must encode all URLs that refer to your own site
  • All pages must be dynamically generated
  • Fails for bookmarks and links from other sites

Read More...

0 Session Tracking using URL Rewriting in JAVA

The below given is the core idea of Session Tracking using URL Rewriting in JAVA

  • Client appends some extra data on the end of each URL that identifies the session
  • Server associates that identifier with data it has stored about that session

E.g. http://host/filePath/fileName.html;jsessionid=1234

Advantages of Session Tracking using URL Rewriting

Works even if cookies are disabled or unsupported

Disadvantages of Session Tracking using URL Rewriting

  • Must encode all URLs that refer to your own site
  • All pages must be dynamically generated
  • Fails for bookmarks and links from other sites

Read More...

1 What are HttpSession Methods in JAVA

getAttribute

– Extracts a previously stored value from a session object. Returns null if no value is associated with given name.

setAttribute

– Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener.

removeAttribute

– Removes values associated with name.

getAttributeNames

– Returns names of all attributes in the session.

getId

– Returns the unique identifier.

isNew

– Determines if session is new to client (not to page)

getCreationTime

– Returns time at which session was first created

getLastAccessedTime

– Returns time at which session was last sent from client

getMaxInactiveInterval, setMaxInactiveInterval

– Gets or sets the amount of time session should go without access before being invalidated

invalidate

– Invalidates current session

Read More...

0 What is the Importance of Session Tracking

  • When clients at on-line store add item to their shopping cart, how does server know what’s already in cart?
  • When clients decide to proceed to checkout, how can server determine which previously created cart is theirs?

There comes the importance of Session Tracking. The following are the various Session Tracking methodologies.
  • Cookies
  • URL-Rewriting
  • Hidden Form Fields
Read More...

17 June 2010

0 What is CRUD Operations in Database

CRUD is the acronym for Create, Read, Update and Delete. Create, Read, Update and Delete (CRUD) are the 4 basic functions of a Database or persistent storage. CRUD refers to all of the major functions that need to be implemented in a RDBMS.
Each letter in the CRUD can be mapped to a standard SQL statement:

Create        INSERT
Read        SELECT
Update        UPDATE
Delete        DELETE
Read More...

0 Rails versus Java web frameworks

        There are many other web application frameworks other than Rails. Apache Cocoon, Apache Struts, AppFuse, Google Web Toolkit, Grails, Hamlets, Spring Framework, Tapestry are frameworks just to name a few. This blog post compares Rails framework with these other Java frameworks.

Vastly reduced code footprint – Field results place productivity increases over modern Java methodologies (e.g., J2EE, Struts, etc.) in the 10-fold range.

Minimal configuration – Rails applications require a few lines of specification to identify each database connection you will use, as well as a line of configuration for each different type of routing you will use (typically 3-4 lines for an entire application). Both of these are necessary in any environment. By contrast, rather than the 20 or so lines required in a Railes application, typical medium-scale Java applications require thousands of lines of XML configuration, many of which are stronglycoupled across application layers.

IDE automation not required – Much of the productivity improvement in Java comes from the widespread use of tools to automate code writing and change. In comparison, Rails productivity improvement is based on the ease of programming it offers.

Read More...

0 Ruby on Rails as an Agile Framework

        Here we will discuss about the characteristics of Rails framework that make it most suitable for Agile methodologies.

Scaffolding – Most database backed Web applications must provide a user interface to do CRUD operations – Create, Read, Update, and Delete – for nearly every major table in the system. Building these user interfaces should be automated, not repeated. Rails eliminates some of the CRUD operation repetitions through scaffolding. With Rails, you can build a full scaffold application from scratch in just a few simple operations.

Convention over Configuration – A developer needs to specify only the unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called sales by default. It is only if one deviates from this convention, such as calling the table "products_sold", that one needs to write code regarding these specific deviations from conventions. Also the well formed set of conventions alleviates the need of detailed configuration files providing mapping between objects and tables etc.

Don't Repeat Yourself (DRY) – Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.

Portable programming skills – Managers will appreciate the fact that Rails minimizes configuration and encourages standardization. This feature enables programming skills to be more portable.

Rapid feedback loop – In Rails, you get nearly-instant feedback as you code. Hence results of the changes made can be immediately seen, improving the overall client experience. Changes can be made promptly as well.

Easy migration with vendor neutral implementation – Command pattern has been applied in Ruby to enable migrations using the ActiveRecord migration facility. Database schemas can be defined in a database-vendor neutral way.

Meta Programming – The most useful application of dynamic features, such as adding methods to objects, is meta programming. Such features allow developers to create a library that adapts to the environment. An example application of this is swapping proxies to easily change protocols from SOAP to XMLRPC.

Read More...

2 Architecture of Ruby on Rails Framework

Architecture of Rails framework is illustrated in the above given figure.

Rails architecture consists of 2 major elements:

  • Active Record
  • Action Pack

Active Record is an Object Relational Mapping (ORM) layer, which handles the Model element of the MVC application. This layer exposes the data table rows as model objects to the rest of the application.

Action Pack handles the View and Controller elements of the MVC application. Action Pack consists of two parts viz. Action View and Action Controller which handle View and Controller of the MVC application respectively.

Each of the architectural element in the picture above is elaborated below:

User Component – Rails web applications are accessed by browsers using various protocol interfaces such as HTTP, ATOM, RSS or consumed as Web Services using SOAP.

Web Server – The developed Rails application resides on a Web Server, which handles requests from the user component and forwards them to the Dispatcher.

Dispatcher – Dispatcher invokes appropriate controller based on the current user request.

Controller – Controller processes the user request, and invokes appropriate action. The action collaborates with appropriate model objects and prepares the response. If the request was from a browser, the response will be rendered through Action View component. Else, an appropriate response is relayed by either the Action Webservices or the Action Mailer component.

Read More...

16 June 2010

0 Overview of Ruby on Rails RoR

Ruby on Rails – the Framework

Ruby on Rails is an open source web application development and persistence framework that supports agile development and sustained productivity. It is a common observation that web application development using Rails framework is at least 10 times faster compared to other frameworks.

Rails framework was extracted from working applications that were written in Ruby. This means that Rails code base was practical, proven and well tested before it took shape as a framework.

Rails framework includes everything needed to create database backed web applications according to the Model-View-Control (MVC) pattern of separation.

This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags.

The model contains the "smart" domain objects (such as Account, Product, Person, Post) that hold all the business logic and know how to persist themselves to a database.

The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view.

Following are the typical set of tasks that one needs to perform to build a bare bones database backed web application using Rails:

  1. Create a new Rails project using the utility script provided as part of the framework. Doing this creates a directory structure for the new project which is common across all the Rails projects.
  2. Create necessary database with associated tables. Each of these tables maps to a model class.
  3. Generate a scaffold specifying the model and controller names to the scaffolding utility. This step needs to be repeated for all the different models that are needed for the project.
    The above process generates views for CRUD (Create, Read, Update and Delete) and list actions, wired to corresponding controller classes. Data fields associated with these actions are automatically picked up from the database tables created in the previous step.
  4. A barebones application that can show the core application data with capability to add, modify, view and delete is now ready!

Over and above the barebones application created above, sophistications can be added easily. Each of these additional sophistications is also a piece of cake if we follow the conventions of Rails framework. For example, the table name associated with each model class name follows a convention that the table name will be a plural of the model class name. Such conventions over configurations make the amount of code very less, and hence make the amount of work to be done by the programmer very less, eventually resulting in increased productivity. Another principle followed in Rails paradigm is called DRY (Don’t Repeat Yourself) that aims at eliminating code redundancy.

Rails framework has the following salient features:

  • User friendly
  • Agile
  • Rapid prototyping capability
  • Built in testing capabilities
  • Easy to maintain
  • Scalable
  • On par performance with other frameworks
  • Support for Webservices
  • Support for emails
  • Support for AJAX
  • Support for development , testing and production environments
Read More...

0 Features and Advantages of Rails Framework

Rails framework has the following salient features:

  • User friendly
  • Agile
  • Rapid prototyping capability
  • Built in testing capabilities
  • Easy to maintain
  • Scalable
  • On par performance with other frameworks
  • Support for Webservices
  • Support for emails
  • Support for AJAX
  • Support for development , testing and production environments
Read More...

1 Features of Ruby on Rails RoR

Ruby – the programming language

Ruby is an object oriented language that is interpreted. It has syntax similar to Perl and semantics similar to Smalltalk. Ruby itself was developed in C. Rails web application framework is developed on Ruby.

Salient features of Ruby language are:

  • Pure OOP
  • Support for Reflection – can query Ruby objects about themselves
  • Duck Typing – Ruby “ducks” the issue of typing, letting the type of a variable be determined by its value.
Read More...

0 DRY in Ruby On Rails- Don't Repeat Yourself

DRY- Don't Repeat Yourself is the principle of Ruby On Rails (RoR). Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.

  • Reusing data
    e.g. no need to declare table field names – can be read from database
  • Metaprogramming
    dynamically created methods
  • Less code – more work on each line of code
    e.g. specific keywords like find_all to query database
Read More...

15 June 2010

0 What is DRY- Don't Repeat Yourself

DRY- Don't Repeat Yourself is the principle of Ruby On Rails (RoR). Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.

  • Reusing data
    e.g. no need to declare table field names – can be read from database
  • Metaprogramming
    dynamically created methods
  • Less code – more work on each line of code
    e.g. specific keywords like find_all to query database
Read More...

1 Advantages of Ruby On Rails - RoR

The following are the advantages of Ruby On Rails (RoR).

  • Less code by avoiding redundancy and following Rails conventions.
  • Increased productivity and, ideally, decreased development times.
  • Rails is written in Ruby – Ruby is a very easy to understand and work.
  • Extensive standard library.
  • Easily ported among Linux, Windows and Macintosh environments.
  • Well suited for Agile development.
  • Growing Ruby On Rails users community (Mailing list, Wiki, IRC & bug tracking)
Read More...

0 Disadvantages of Ruby On Rails -Rails ver. 1.2

What is not there in Rails ver. 1.2?

  • No Asynchronous communication
  • Distributed transactions are not supported
  • Poor ORM support for legacy schemas

Read More...

0 What is RoR or Ruby on Rails ?

Ruby on Rails - often called RoR, or just Rails, is an open source web application development framework. It was written using Ruby programming language. The web applications developed using this framework closely follow the Model-View-Controller (MVC) architecture. Rails framework strives for simplicity and allows real-world applications to be developed in less amount of code compared to other frameworks and with a minimum of configuration. It aims at increasing the speed and ease with which database-driven web applications can be created. Skeleton code frameworks (scaffolds) can be created in a jiffy.

  • Ruby is an Object-Oriented programming language.
  • Rails is an open source Ruby framework for developing database-driven web applications.
  • Ruby on Rails (RoR) is open source web application framework written in the Ruby programming language and using the Rails framework with MVC design pattern.
  • It aims to increase the speed and ease with which database-driven web sites can be created and offers skeleton code frameworks.
  • Emphasis is on simplicity and elegance.
  • RoR principles include Don't repeat yourself (DRY) and Convention over Configuration.
  • Focus on developer productivity and getting the job done – fast!

Ruby – the programming language

Ruby is an object oriented language that is interpreted. It has syntax similar to Perl and semantics similar to Smalltalk. Ruby itself was developed in C. Rails web application framework is developed on Ruby.

References:
http://www.rubyonrail.org

Read More...

0 JAVA- A Comparison between Static Polymorphism and Dynamic Polymorphism

Static Polymorphism And Dynamic Polymorphism in JAVA

Static Polymorphism in JAVA is also known as Function Overloading in JAVA. Dynamic Polymorphism in JAVA is also known as Function Overriding in JAVA. Let us compare Function Overloading and Function Overriding in JAVA. Here it goes,the difference between Function Overloading and Function Overriding in JAVA

Static Polymorphism Dynamic Polymorphism
Function Overloading
– within same class more than one method having same name but differing in signature
Function Overriding
– keeping the signature and return type same, method in the base class is redefined in the derived class
Resolved during compilation time Resolved during run time
Return type is not part of method signature Which method to be invoked is decided by the object that the reference points to and not by the type of the reference
Read More...

0 Compare Static Polymorphism and Dynamic Polymorphism in JAVA

Static Polymorphism And Dynamic Polymorphism in JAVA

Static Polymorphism in JAVA is also known as Function Overloading in JAVA. Dynamic Polymorphism in JAVA is also known as Function Overriding in JAVA. Let us compare Function Overloading and Function Overriding in JAVA. Here it goes,the difference between Function Overloading and Function Overriding in JAVA

Static Polymorphism Dynamic Polymorphism
Function Overloading
– within same class more than one method having same name but differing in signature
Function Overriding
– keeping the signature and return type same, method in the base class is redefined in the derived class
Resolved during compilation time Resolved during run time
Return type is not part of method signature Which method to be invoked is decided by the object that the reference points to and not by the type of the reference
Read More...

0 How to make a field auto incremental in DB2 ?

How to make a field auto incremental in DB2?

The following query example will show you how to set the primary key field as Auto-increment field in DB2
create table WCSADM.itemlist
(
   ITEMLIST_INDEX         Integer          GENERATED ALWAYS AS IDENTITY,
   RESULTCODE      VARCHAR(254),
   ADDLINFO      VARCHAR (254)
)
Read More...

14 June 2010

3 DB Migration from Oracle 8.0.5 to Oracle 10g

I have a DB of 10G size in Oracle 8.0.5 We need to migrate this (structure will remain as is) to Oracle 10g.
What is the easiest method to do this, will export taken in Oracle 8.0.5 work with import of Oracle 10g. Is there any other easy way?

        There are verious ways to migrate data from Oracle 8.0.5 to Oracle 10.2.*. Details are mentioned below,
Using Export/ Import:
1. Export Full Oralce 8.0.5 database using 8.0.5 EXP utility.
2. Take a cold backup of 8.0.5 database.
3. Apply Oracle 10g related operating system patches to server.
4. Install Oracle 10g Software.
5. Create Oracle 10g instance.
6. Create DATA and INDEX tablespaces with same name as Oracle 8.0.5 database.
7. Import Full database in new Oralce 10g instance using 10.2.* IMP utility.
8. Recompile all invalid objects.

Using File System:
1. Take a cold backup of 8.0.5 database
2. Apply Oracle 10g related operating system patches to server.
3. Install Oracle 10g Software.
4. Create Oracle 10g instance.
5. Detach file system of Oracle 8.0.5 database and attach it to new Oracle 10g database.
6. Run database upgrade scripts manually on the new 10g database.
7. Recompile all inavalid objects.

You can also use Oracle Database Upgrade Assistance tool. This is a GUI based tool provided by oracle for upgrading database to higher version.
Read More...

1 How to Load Data from Oracle to Access

Question:
How can I Load data from Oracle tables to MS access database.
Or How can I Load data from Oracle tables to an excel sheet and then to MS access database?
SSIS (SQL Server Integration Services) option would be simpler and efficient.
Read More...