Monday 6 August 2012

Cookies in Servlet


Cookies are information which is stored in client browser. Cookies are used for information tracking about the client.

3 steps are there to store and process the  cookie :

1. First, server sends a set of cookies to client browser.

2. Then, client stored that cookies in local machine.

3. After client stores that cookie, if client send any more request to server, then that cookie information send with that request. From this information, server identify the client.


Create a cookie :

1. Cookie cookieobj = new cookie("cookieName", "cookieValue");

The name and value should not contain the following,

white space, (, ), [, ], =, /, ,, :, ;, ",@, and ?


2. By setting the age we can maintain the cookie.

cookieObj.setMaxAge(60*60*24);


3. Then need to add that created cookie into response. Then only it will send to client.

response.addCookie(cookieObj);


Accessing cookie in server :

1. We can access all the cookies which is comes from client request. By using getCookies();

request.getCookies()    ->      This will return array of cookies.

Aftet that, we can process the cookie and can access that.

/*
 * getting all cookies which is comes from client request
 */
Cookies[] allCookies = request.getCookies();

for (Cookie cookie in allCookies) {
    String name = cookie.getName();
    String value = cookie.getValue();
}



Deleting cookie:

1. By clearing the age of the cookie, we can clear the cookie.

First, get the appropriate cookie.

Cookies[] allCookies = request.getCookies();

for (Cookie cookie in allCookies) {
    if (cookie.getName.equals("cookieName")) {
        cookie.setMaxAge(0);    // clearing cookies
        response.addCookie(cookie);     // Adding cookie back to client response
    }
}

Wednesday 27 June 2012

Difference between isset and empty in Php


Isset :
    1. isset checks to see if the variable have any value except NULL or not assigned a value.

    2. isset returns true, if that varibale exists and have value other than NULL.

    3. If variable assigned a value like " ", 0, "0" or FALSE are set. So, isset returns true.

Empty :

    1. EMPTY checks to see if a variable is empty.

    2. Empty is interpreted as : " " (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.

Some Examples :

1. $nullVar = NULL;

if ( isset($nullVar)) -- This would be FALSE
if ( empty($nullVar)) -- This is TRUE

2. $singleQuoteVar = '';
   $dblQuoteVar = "";

if ( isset($singlequoteVar)) -- This would be TRUE
if ( empty($singlequoteVar)) -- This is TRUE

if ( isset($dblquoteVar)) -- This would be TRUE
if ( empty($dblquoteVar)) -- This is TRUE

3. $zeroValue = 0;

if ( isset($zeroValue)) -- This would be TRUE
if ( empty($zeroValue)) -- This is TRUE

4. $TrueBoolValue = TRUE == 1;
$FalseBoolValue = FALSE == 0;

if ( isset($TrueBoolValue)) -- This would be TRUE
if ( empty($TrueBoolValue)) -- This is FALSE

if ( isset($FalseBoolValue)) -- This would be TRUE
if ( empty($FalseBoolValue)) -- This is TRUE

5. $arrVar = array():

if ( isset($arrVar)) -- This would be TRUE
if ( empty($arrVar)) -- This is TRUE

Wednesday 30 May 2012

Steps to build debian package


Before go for this, need to know about debian package.

Debian package contains set of files that will install that package where we run this debain in ubuntu linux. Like exe in windows. So, Debian package is used to install particular software in ubuntu linux.

Now, Let start how to build this debian pacakge.

Requirements to build debian packages : Ubuntu System/VM

1. First we need some packages to build debain package in ubuntu. 
Run following command

sudo apt-get install build-essential autoconf automake autotools-dev dh-make debhelper devscripts fakeroot xutils lintian pbuilder

[ For ubuntu linux, we can use apt-get package manager to install any package ]

This command will install all packages specified.

2. Then, create source folder.  [ Folder name should be in lower case ]

Debian pacakage name have some naming convensions,  For Example. My source folder name is clientprojrct-1.0

This contains clientproject_1 folder. it contains all files need to be packed in debian package.

Folder structure  clientproject-1.0  -> clientproject_1

3.  Begin debianization
To build debian package, we need some files [ like control, postinst, postrm etc ] to define debian package.

After create source folder, we need to run this command.

cd clientproject-1.0

dh_make   [ This command will create one debian folder. This folder contains all neccessary files ]

After run this command,this will print

Type of package: single binary, indep binary, multiple binary, library, kernel module, kernel patch or cdbs?
[s/i/m/l/k/n/b]

Give option : s

4. Control file
Probably the most important step is how you edit the control file.

This file will be created after completing step 3, and you can find it in the "debian" folder in the directory containing your source files. It initially looks like this:

   1 Source: x264
   2 Section: unknown
   3 Priority: extra
   4 Maintainer: andrei <webupd8@gmail.com>
   5 Build-Depends: debhelper (>= 7), autotools-dev
   6 Standards-Version: 3.8.1
   7 Homepage: <insert the upstream URL, if relevant>
   8
   9 Package: x264
   10 Architecture: any
   11 Depends: ${shlibs:Depends}, ${misc:Depends}
   12 Description: <insert up to 60 chars description>
   <insert long description, indented with spaces>

For now, enter a hompage (line 7) and a description (line 12) for your package.

Now, a very important step: we must enter the build dependencies on line 5.

For example, Am created one application in java and I packed that application in debian package. To run that application, I need java.
Like this all needed packages, We should include in debian dependencies.

Then, if we need noacrh debian, then need to update "Architecture" as "all".
[ noarch : no architecture. We can install this debian package in both 32 and 64 bit system ]

5. The "copyright" file

In the same "debian" folder, you will also find a "copyright" file which you need to edit. The important things to add to this file are the place you got the package from and the actual copyright notice and license. You must include the complete license, unless it's one of the common free software licenses such as GNU GPL or LGPL, BSD or the Artistic license, when you can just refer to the appropriate file in /usr/share/common-licenses/ directory that exists on every Debian system.

6. The "changelog" file

You can fild this in the same "debian" folder, this file is very important. Here, You need to mention name and date deails.

x264 (0.1+svn20100107-1) unstable; urgency=low

* Initial release (Closes: #nnnn) <nnnn is the bug number of your ITP>

-- andrei <webupd8@gmail.com> Sat, 09 Jan 2010 22:40:24 +0200

7.  The "postinst" file

You can find this in the same "debian" folder. Here we need to mention where packed files are need to copy.

8. The "postrm" file

You can find this in the same "debian" folder. Here we need to mention what are the files are need to remove while uninstall this package.

9. Building the actual .deb package

After defined debian packages, we need to run this command to build debiam.

cd clientproject_1.0 -> clientproject_1

debuild -b     [ This will build debian packgae ]

After run this, you can get debian package.

Tuesday 29 May 2012

Singleton pattern


Singleton in java :

-> Singleton is one of the design pattern in java which is used to control the creation of class's instance. We can ensure only one instance of the class is created.

-> For this, we need to do something as follows,

1. Make class contructor as private, so that outside world can not access this class.
2. Need to create static variable for class instance.
3. Then, Need to create static method to return instance of singleton class. If class's instatnce is empty, then create new instance and return that instance. Otherwise return already created instance.
4. Make access method synchronized to prevent threading problems.


Example Code :
package javaexamples;

import java.util.Date;

public class SingletoneObjectDemo {

    private static SingletoneObjectDemo singletoneObj = null;

    private  SingletoneObjectDemo() {

    }

    public static synchronized SingletoneObjectDemo getInstance() {
        if (singletoneObj ==null) {
            singletoneObj = new SingletoneObjectDemo();
        }
        return singletoneObj;
    }

    protected void displayDate() {
        System.out.println("Today date is : " +(new Date()).toString());
    }
}


package javaexamples;

public class SingletoneObjImp {
    public static void main(String args[]) {
        SingletoneObjectDemo singletoneObj = SingletoneObjectDemo.getInstance();
        singletoneObj.displayDate();
    }
}

Friday 25 May 2012

User Defined Exception


1. Java provides an extensive set of in-build exceptions. But some cases we may need our own exception to handle some application specific error.

What is the neccessary to create our own exception?

1. The problem and Exception used may not have good relation.

2. If any unwanted condition or error occurs related to our Application, then we can throw our own application exception from any where.
[ While getting error in Helper classes, then we can not able to send that error directly to client.
That place, we can throw exception and send back to client ].


While defining an user defined exception, we need to take care of following,

1. The user defined exception class should extend from Exception class.
2. The toString() method should be overridden in user defined exception class inorder to provide meaningful information about the exception.


For Example,

public class UserDefinedException extends Exception {

    private String status;

    public UserDefinedException(String status) {
        this.status = status;
    }

    public String toString() {
        return "UserDefinedException : " + status;
    }

    public static void main(String args[]) {
        String str = null;
        try {
            checkInput(str);
        } catch (UserDefinedException ex) {
            System.out.println("Exception occured : " +ex);
        }
    }

    private static void checkInput(String input) throws UserDefinedException {
        if (input == null) {
            throw new UserDefinedException("Input is null");
        }
    }
}

In UserDefinedException class, We defined our own exception class.

In main method, we are checking whether the input is null, If its null then throwing 'UserDefinedException'.

If exception throws from called function, then need to catch that exception in caling function. [ Compiler will tell this ].


Difference between 'throw' and 'throws' :

throws :

1. It is used by the designer of a method to claim the exception. Claiming is nothing but informing the programmer about the potential problems that may arise while using the method.

2. The other way is to use as an alternative to try-catch block which is not a robust way.

throw :

1. "throw" is used by the programmer to throw an exception object explicitly to the system. Mostly used with user-defined exceptions.

Tuesday 22 May 2012

Break Statement in Java


Break statement is one of the several control statements Java provide to control the flow of the program. As the name says, Break Statement is generally used to break the loop of switch statement.

Please note that Java does not provide Go To statement like other programming languages e.g. C, C++.

Break statement has two forms labeled and unlabeled.

Unlabeled Break statement

This form of break statement is used to jump out of the loop when specific condition occurs. This form of break statement is also used in switch statement.

For example,

    for(int var = 0; var < 5 ; var++)
    {
            System.out.println(“Var is : “ + var);
   
            if(var == 3)
                    break;
    }

In above break statement example, control will jump out of loop when var becomes 3.

Labeled Break Statement

The unlabeled version of the break statement is used when we want to jump out of a single loop or single case in switch statement. Labeled version of the break statement is used when we want to jump out of nested or multiple loops.

For example,

    Outer:
    for(int var1 = 0; var1 < 5 ; var1++)
    {
             for(int var2 = 1; var2 < 5; var2++)
            {
                    System.out.println(“var1:” + var1 + “, var2:” + var2);
   
                    if(var1 == 3) {
                        break Outer;
                    }
   
            }
    }

Monday 23 April 2012

How to create javadoc for Java Application?



To create java documentation, we need to write documentation command while writting code itself.

Documentation command look like this,
/**
 *
 * Description of Packagae / Class / Method / Variables
 */

If we wrote like this, then we can easily generate Java Api for our Application.

Example:

package javaexamples;


/**
 *
 * @author uma
 */
/**
 *
 * This class implements usage of toString in java.
 * If we override this toString(), then when ever we print this class's object,
 * It will display all information about that object
 * what ever we defined in this toString() method
 */
public class Student {


    /**
     * id is an unique key to identify Student
     */
    private int id;
    /**
     * name of the Student
     */
    private String name;


    /**
     * Student constructor initialize id and name of the Student
     */
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }


    /**
     * The toString() will display Student class 's object information
     */
    public String toString() {
        return "Id :" + id + " Name :" + name;
    }
}



To create Javadoc, need to run this commmand or use 'Generate javadoc' option in netbeans.

javadoc [ option ] package_name 

[ To know about all options, use javadoc command. It will list all options ]

From above example,

javadoc -private javaexamples

This will give complete javadoc in html file. Once, we open this index.html in browser, It will show all details.



Where we can use NULL in mysql?


Where we can use NULL in mysql?

Normally, In java, null means nothing. Like that, In mysql, We can use NULL.

While try to insert null in mysql table, then we should not use single quotes while insert null in table. If we use single quote for null, then I will take that as a String.

If we add null, then it automatically added NULL in table.


Example,

create table sample(id integer(20) default NULL, name varchar(60) default NULL);

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(20)     | YES  |     | NULL    |       |
| name  | varchar(60) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

insert into sample values(1, null);
1 row in set (0.02 sec)

select * from sample;

+------+------+
| id   | name |
+------+------+
|    1 | NULL |
+------+------+

insert into sample values(NULL, 'Uma');
1 row in set (0.02 sec)

select * from sample;

+------+------+
| id   | name |
+------+------+
|    1 | NULL |
| NULL | Uma  |
+------+------+

insert into sample values(3, 'Vidhya');
1 row in set (0.02 sec)

select * from sample;

+------+--------+
| id   | name   |
+------+--------+
|    1 | NULL   |
| NULL | Uma    |
|    3 | Vidhya |
+------+--------+


-> We can check NULL as follows,

select * from sample where name is Not NULL;

+------+--------+
| id   | name   |
+------+--------+
| NULL | Uma    |
|    3 | Vidhya |
+------+--------+


select * from sample where name is NULL;
+------+------+
| id   | name |
+------+------+
|    1 | NULL |
+------+------+



More Info :

http://dev.mysql.com/doc/refman/5.0/en/problems-with-null.html

http://stackoverflow.com/questions/3059805/difference-between-mysql-is-not-null-and


Tuesday 3 January 2012

Flex basics


-> we can use two languages to write Flex applications: MXML and ActionScript.

-> MXML is an XML markup language that you use to lay out user interface components.

-> Like HTML, MXML provides tags that define user interfaces. MXML will seem very familiar if you have worked with HTML.

-> MXML is more structured than HTML, and it provides a much richer tag set.

-> One of the biggest differences between MXML and HTML is that MXML-defined applications are compiled into SWF files and rendered by Adobe® Flash® Player or Adobe® AIR™, which provides a richer and more dynamic user interface than page-based HTML applications.


Simple Flex Application :

<?xml version="1.0"?>
<!-- mxml\HellowWorld.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Panel title="My Application" 
        paddingTop="10" 
        paddingBottom="10"
        paddingLeft="10" 
        paddingRight="10"
    >
        <mx:Label text="Hello World!" fontWeight="bold" fontSize="24"/>
    </mx:Panel>
</mx:Application>


Why using UTF-8 in encoding format :

-> UTF-8 provides a unique number for every character in a file, and it is platform-, program-, and language-independent.


<mx:Application> tag :

-> It  represents a Application container.

-> A container is a user-interface component that contains other components and has built-in layout rules for positioning its child components.

-> By default, an Application container lays out its children vertically from top to bottom


The MXML properties :

-> We can configure initial state of an component using mxml properties. And We can change this properties using Actionscript at run time.


Relationship of MXML tags to Actionscript classes :

-> Adobe implemented Flex as an ActionScript class library. That class library contains components (containers and controls), manager classes, data-service classes, and classes for all other features.

-> MXML tags correspond to ActionScript classes or properties of classes. Flex parses MXML tags and compiles a SWF file that contains the corresponding ActionScript objects.

For example,

<mx:Button label="Submit"/>

-> When you declare a control using an MXML tag, you create an instance object of that class. This MXML statement creates a Button object, and initializes the label property of the Button object to the string "Submit".