Tuesday, August 9, 2011

Command Line Input with Java

I learned first programming language(C and C++) using command line input and output; and it was really interesting. Then after I started Java, and because java was high level programming language, I was quite involved creating forms and performing input and output operations using GUI fields which used to be a quite easy way to do. But unfortunately, I did not notice to implement the command line input and output and if you are also not aware or may have forgotten, then here I am going to point out the methods to accomplish this.(Note: there may be many alternatives for that)
We note here that System.in gets the stream from primary input devices such as keyboard.

1) Using Scanner Object

// prompt the user to enter their name
System.out.print("Enter your name: ");

// get their input
Scanner scanner = new Scanner(System.in);

// there are several ways to get the input, this is
// just one approach
String username = scanner.nextLine();
//Display name
System.out.println("Your Name is:"+username);

2) Using BufferedReader Object

// prompt the user to enter their name
System.out.print("Enter your name: ");

// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// read the username from the command-line; need to use try/catch with the
// readLine() method
String userName = br.readLine();

//Display Name
System.out.println("Your Name is:"+userName);

The above mentioned code is quite straightforward and its your choice which method to use.
Thanks for your effort to read my article.

Here are some useful methods we can directly use in applications:
   // to get string
   public static String getString() throws IOException
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      return s;

    // to get a character
   public static char getChar() throws IOException
      String s = getString();
      return s.charAt(0);

    //to get integer
   public static int getInt() throws IOException
      String s = getString();
      return Integer.parseInt(s);

Saturday, July 30, 2011

Declarative Authentication in Java Server Pages

Some programmer prefers authentication through programming to declarative authentication, that all depends upon choice. I also used programed authentication before when I did my Bachelor's projects. I still remember the authentication part was tedious job since we need to write a bunch of code for authentication and the checking of session variable for authenticated user is also not interesting.

So, I was thinking whether there exists some sort of mechanism so that we do not need to do all these redundant things, I mean there should be some server management which will do all those authentication part of user.

I later realized I was not wrong. We can implement the declarative authentication without any much effort; just setting some declaration in server and the application part. This article will focus on how we can achieve these things.

1) Java should be installed. New ubuntu versions have built in java with OS; so we do not need to install it. If it is not installed anyway, just install it by selecting from Synaptic package manager.

2) There should be tomcat server installed.(The preferred tomcat version is tomcat 6 which is also supported by netbeans 6.9)
Installation of Tomcat
i)Download the apache tomcat compressed installer file in .tar.gz form and extracted it.
ii) Copy it to /usr/local location.
iii) Run the command to start the server(you must be inside the tomcat directory)
sudo sh bin/startup.sh
Now server is running.

3) The mysql server should be installed.
MySql Startup
i)type sudo apt-get install mysql-server in the terminal.
ii) installation may take longer time. while installing, you must create the user for mysql.
iii) after installation is complete, type sudo mysql -u username -p from terminal to run mysql server locally. Provide password for mysql.
iv) Now you are ready to execute the mysql commands.
3) Apart from creating the other several tables for you application, the authentication part need two compulsory tables to be created. You can give any names while creating and this information is placed in the server settings.
Structure of authentication tables:
tableUser: columnUserName, columnUserCred
tableUserRole: columnRoleName

I have used the following sql query to create those tables:
CREATE TABLE customers(name VARCHAR(100), password VARCHAR(100))
CREATE TABLE customer_roles(name VARCHAR(100),role_name VARCHAR(100))

4) Now we manage some settings in the server.xml file which is located in the conf folder of tomcat installation directory.

&lt!-- It is commented out--&gt
&lt!-- &ltRealm className = "org.apache.catalina.realm.UserDatabaseRealm"
&lt!-- Add these lines --&gt
&ltRealm className="org.apache.catalina.realm.JDBCRealm" debug="99"
driverName="com.mysql.jdbc.Driver" connectionURL=
password=00977" userTable= "customers" userNameCol="name"
userCredCol="password" userRoleTable="customer_roles"

5) Now, restart the tomcat server and most of the work is done. The remaining part is to create and define the users with roles. Store those information in the above mentioned tables created for authentication.

6) Now we define the login page and the error page in case authentication fails. We set this information in the web.xml file in the application.


7) Now we select the pages which need right to access the pages. This information is also set inside the web.xml file as follows:


Here the page customer.jsp is arbitrary page which is accessed by users with roles user and manager. Other users do not have right to access this page.

Some Description:
This process is not so easy; I could not do it successfully in one time. I tried it many times until I get success. There are some minor problems may occur which can be fixed by seeing the error. Like there should be one compulsory user with manager role which is responsible for tomcat related settings. If you have not set that user, you even can not start the tomcat server.

Now, when user tries to access the page customer.jsp, then since it access right for specific users only, the you get a form for login the you go into the page. If authentication is okay and the role matches, only the page can be accessed by the user. Otherwise server redirects the user to the error page.

request.getRemoteUser() gets the previously logged in user. So, it can be saved in any servlet for later user such as to get other user related information of that user from the database or to check whether user has logged in or not, if logged in, which user has logged in etc.

Thursday, July 28, 2011

Sending Email in Java

It is not so complicated to create your own email sending application using Java by using the JavaMail API. To send an email, we need SMTP server and its credentials. Since I faced a lot of problems regarding the sending of an email and finally I got the working code. Yes, may be the modified source code may also work which may ultimately be simpler than this.

In this article, my focus will be on the problem solution, so I have used the SMTP server of google. Google is very good because it is providing a lot facilities to its users like if you have google account you have everything!

Now we start creating a sample application which is responsible for sending an email. To achieve this, we need the following properties to be set:
1) SMTP server
2) Server credentials
3) Port Number

We need to create Session object for which we need Properties object where we can set the properties we require and Authenticator object for authentication which needs the server credentials.

A sample program which is working for jdk 1.6 is presented here:

import javax.mail.PasswordAuthentication;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

* This class is responsible for sending emails.
* @author krishna
public class EmailSender {

//gmail SMTP server
private String SMTPServer = "smtp.gmail.com";
//SMTP server username, in our case, it is the sender also
private String from = "abc";
//SMTP password
private String password = "xyz";

* Constructor
public EmailSender() {
* Sends a message email
* @param to To address
* @param subject Subject
* @param content message content
* @return result:true or false
* @throws MessagingException
public boolean SendMail(String to, String subject, String content)
throws MessagingException {

try {

//Create Session
Properties props = new Properties();
props.put("mail.smtp.host", this.SMTPServer);
//Port 465 is SSL port for gmail smtp server
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);

//Create Message
Message message = new MimeMessage(session);

//Set Addresses
Address fromAddress = new InternetAddress("this.from);
Address toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);

} catch (Exception ex) {
return true;

I think the above mentioned code works fine for you too. The only change you need is change the SMTP server credentials and google users can use their email id and password as credential. This user name will be from email address too. We can call the SendMail method of EmailSender object. The SendMail method takes the email address to whom we are going to send the message, subject text and content text.

This covers the basic of email sending which only consists of sending text messages only; but we can do a lot of extensions on this like attaching files, text rendering etc.

Thanks for reading this !

Sunday, July 17, 2011

Layers in Java

Possibilities of Using Layers: The layers of a panel can be used to create more better interactive systems. We can use the glass-panes and layers to show some extra information on the top of other controls while blocking mouse events on the controls. We can create interactive tutorials and manuals with animations in the middle of some process. Similarly, layered panes are also used for selected object highlighting, focusing or showing detail information in pop up like window.

The dragging and dropping can be made more user friendly by use of layered panes for showing the thumbnail of dragged component on the mouse pointer. Since we do not need more than one layer for this, so glass pane is sufficient to accomplish this task.

How to use Layers:
Glass Pane:For glass pane, we create component for glass pane and then set this component as glass pane.
CustomGlassPane glassPane=new CustomGlassPane();
While creating glass panes, we generally need to disable input events inside the glass pane. So, we need to implement disable the listeners in the glass pane component. Initially glass pane component is invisible, so when required we make the glass pane visible.

Layered Panes:For layered panes, we define the layered component and then set this component as layered pane as follows:
LayeredComponent component=new LayeredComponent();
JlayeredPane layeredPane=getRootPane().getLayeredPane();

The depth defines where in the z-order the layer to be displayed. We need to define the layout of the layered pane because there will not be any default layout for this.

Glass Pane Limitations:
We can not create multiple glass panes because sometimes we may require multiple glass panes to be implemented to achieve our goal.
(ii) Glass pane always cover the entire frame, so if we need to cover only part of the frame, then its not possible.

Layered Panes Limitations:
The layered panes remove the trade offs of glass pane because we can have multiple layers and layers can be set for each child container on the frame. However, we need to create our own layout for the layered component. Although we can use OverlayLayout but that is very simple to meet our requirements. The main disadvantage of layered panes is the complexity of implementation; so many designers prefer to select layout manager to fulfill the requirement of depth-wise positioning of components.

Animation in Java

--> We can implement animation by creating a timer, and when we need animation for a particular object, then we start the timer and inside timer, there is some animation related processing which gets executed to show the object differently on different time interval. The small changes in the object between the two time intervals gives the feeling of smooth animation.
We create a timer and when we need the animation, the timer is started, and the a block of code for animation executes which changes the look and position of object on the timer interval. After the animation is completed, we can reset the look or position of the object. The stopping condition of animation would be when timer is stopped or when some required state is reached by the object through animation.
We create a class for animation which does the task of animation as follows:

private class Animator implements ActionListener{
public void actionPerformed(ActionEvent e){//Do Animation}

And inside the object, we created a timer as follows:
private Timer animationTimer=new Timer(delay,new Animator());
//To start animation
//To Stop animation
Thus, the value of delay can be changed according to our requirement what type of animation we are needing. The animator class should be accessible to the object to be animated to get state of the object. Suppose we want to create an animation with changing the position of an object, then the animator class should get the current position of the object, calculates the new position and sets the new position as current position. This process is repeated with some delay defined in timer, thus gives the feeling of smoothly moving object.

UNDO-REDO Mechanism

UNDO-REDO mechanism works based upon Command Design Pattern that is we define a set of commands that can be executed and un-executed. Actually, execution does some task and it may contain several steps. The un-execution performs in opposite way to take to a state before execution was called.

While doing an action, command for that action is executed and since this action can be undone so, the command is put in the list of undo commands. When an undo command is executed, the task should be unexecuted and this task can be redone, so it is put in the list of redo commands. One thing to note here is, after we undo and then perform a task, then we can not redo, so in such case, the redo command lists are cleared.

To implement undo-redo, we first of all need to create the commands which are capable of executing and unexecuting the commands. To simplify, we define an interface which has the methods execute() and unexecute():

public interface Icommand{
/* Executes */
public void execute();
/* Unexecutes */
public void unExecute();


Then we define the actual command implementing this interface. The actual tasks performed by the command are defined inside the implemented command. This is done as follows:

public class AddButtonCommand implements ICommand {
public void execute(){//Define here}

public void unExecute(){//Define here}

After we define the required commands, we define a manager class which stores the history of the undo and redo commands and manages them. A sample manager class looks like this:

public class UndoredoManager {
//Undo commands list
private Stack undoList=null;
//Redo commands list
private Stack redoList=null;
public void undo(){//execute undo command}
public void redo(){//Execute redo command}
public void addCommand(ICommand command){//new command}

The above undo-redo manager class keeps track of the command list of undo and redo, and executes the command upon request. The list management through stack is appropriate for undo and redo because recently added undo command is used while redoing.

Painting in Java

To perform painting in any component, we need to override the paint methods of the component. The painting process calls three overridable methods: paintComponent(Graphics g), paintChildren(Graphics g) and paintBorder(Graphics).

We generally override paintComponent method for painting the components. Since the painting in swing is carried out by Event Dispatcher Thread, there should be
some queuing mechanism to handle the requests. The event queue actually contains the queues of painting requests and the painting requests managed by RepaintManager by calling the paint method of the component to paint. In the first part, paintComponent method is called which paints own contents, and calls paintBorder which paints the border of the component and finally paints the children it contains by calling paintChildren method.

We can override paint(Graphics) too but we have to manage many other things like border of the control and child components the control contains. We use the Graphics object to paint on the component which is provided at the time of painting. For 2 dimensional painting, we generally cast the Graphics object into Graphics 2D object which can perform better for 2D painting. Since we render only part of the component, while other parts, we wanted to remain as it is. In that situation, we call the parent's paintComponent method and do our painting task so that there would not be undesired painting effects. We do not need to dispose the Graphics object because this object is referenced by other painting methods too. In some cases, we need to change the properties of Graphics object which is specific to a painting only, in such a scenario, we copy the Graphics object and do the painting , and after finishing the painting , we dispose the copy of Graphics object.

Double Buffering:
Double buffering is an indirect process of rendering in which the actual rendering
operations are not performed on the image displayed on the screen, rather an off-screen image(called back buffer) is used to create a rendered image and that image is copied to the screen. This process is repeated and the final result is the smoother display of the images on the screen.

Tuesday, July 12, 2011

Value of PI(Monte Carlo Method)

The value of PI is fixed, it is defined in terms of accuracy by estimating depending upon our requirement of accuracy. So, the value of PI should be very accurate for astronomic calculations for planets while we may not need such accuracy for general purpose calculation like to calculate the surface area of football.

There are several methods to calculate the value of PI, but this time, I am quite impressed by the Monte Carlo Method which is clearly explained by my friend Nobal Niraula in his technical blog. So, I am gonna implement that method in java and I have written a sample java code for that.

float PI = 0;long hit = 0;long count = 0;
long throws=100000;/*Set how accurate value you need*/
Random random = new Random();
while (count <= throws) {
/* X coordinate*/
float x = random.nextFloat();
/* Y coordinate */
float y = random.nextFloat();
/*Check whether the point lies inside the arc*/
if (Math.sqrt(x * x + y * y) <= 1) {
/*Calculate the value of PI*/
PI = 4 * (float) hit / count;

The calculation process is rather simple. We assume an inscribed circle inside a unit square, and then generate random number uniformly to get the x and y co-ordinates of the point lying inside the square. We count the number of points which are inside the inscribed circle. For calculation simplicity, we choose only 1/4th of the square and calculation will be as follows:
so, PI=4*(points_in_circle)/(points_in_square)

In the above implementation, hit is the count of points in the circle and count is the points in the square. The accuracy is determined by throws; the higher the value we set probably the most accurate value in the cost of execution time.

Wednesday, June 22, 2011

Observable and Observers

We need to accept some conventions while developing an application and out of them, MVC is an accepted pattern by many developers because it makes the code easy to understand by isolating the controller portion of the code from view and model.

It is easy to imaging in MVC way, but while implementing we need to face some challenges like:
1) The controller and model are sometimes so tied, it is very difficult or complex to isolate the model from controller.
2) The communication among model,view and controller may not be straightforward.

Here, I will focus the communication part and how java is achieving this in an efficient way. Suppose, we are going to implement notification between two classes Receiver, Sender where Receiver object receives the notification sent by Sender. To implement this, we need to:
i) extend class Observable in Sender class.
ii) implement the Observer interface in Receiver class

The Sender class will be like this:

class Sender extends Observable{
private void doSomeTask(){
//Notify here

The class Receiver will look like this:

class Receiver implements Observer{
//Create observable object
Sender sender;
public Receiver(){
//add the observer object
public void update(Observable observable, Object object){
//check the observable class
//do some job here

The overriden method update of receiver class gets the notification from the observer. The update method takes the Observable object and the object sent from the Obvervable.

i) We can completely separate Model from Controller.
ii) Replaces creation of event handler which is lengthy process and requires more steps.

The one disadvantage is the observable class should be subclass of Observable and since inheritance in java does not allow multiple inheritance. So, if observable class needs to have more than one super class, it is not feasible, we need to change the implementation.

Saturday, February 12, 2011

Difference between framework and API

Yes, I think, for first time, it sounds baffling since many programmers may not care about the differences they just go on using frameworks and API's and becomes happy with the facilities provided by them for faster development of the software. Certainly, you may not notice because these are the stuffs which contains class libraries intended to interface with our applications(framework: higher level, API:lower level).

But, lets think these terms once and try to find out some differences between them.

1) Size

One dominant difference is the size. The framework resides higher levels which is oriented to the application tasks and so it is suitable for application development in higher level. But API is small and contains methods, libraries for specific purpose, and it does not cover all the stuffs required to develop an application, so we may need multiple APIs.

2) Level
The frameworks internally use APIs to work e.g. .NET framework uses the Win32 API to communicate with windows operating system. Thus, we can say API resides in the framework. The frameworks, because they resides higher level, make the user easier to develop the application without worrying about internal details of platform or machine configuration. The frameworks manage these things. But it is not complete, sometimes we need to change the settings in our own way, then it is necessary to program in API level where we can do lower level tasks for complex applications. So, for general applications, it is good to select framework, but for specific application, framework may not be boon, so go for API level programming.

The frameworks generally hides the API level methods and classes by wrapping it with framework higher level methods. Thus, frameworks support fast development of scalable applications. Frameworks generally cover all the things that require to develop an application from starting level to deployment level like compiling, managing source code, testing, support for IDE and deployment.

3) Examples
Frameworks: .NET framework, Ruby on Rails, Spring

Thats all.....

Sunday, January 30, 2011

The 'final' keyword always confusing!!!

Nowadays, I am doing some stuffs in java, so, I am quite close to java. It is 12:56 AM, last day of Jan i.e Jan 31st!. I was about to go to bed to sleep, but I got something which is quite confusing for many programmers the keyword 'final'. Here are the points which will clearify you to some extent:

1) The final keyword can be used for classes, methods, variables, and arguments. (more confused!) wait I will clarify you.
2) First, let the final variables, the variables declared as final can be instantiated only ONCE!

3) Lets think about methods, lets guess what may be special if we make the methods final, it is related to inheritance. Those methods declared as final can not be overridden.

4) The arguments declared as final also can be initialized only once. (I have not checked it... so , don't believe until you check it out)

5) The final classes are certainly similar to sealed classes i.e the classes can not be inherited.

(I am going to elaborate this one when I have time to write sample code using final keyword for different cases and test the result. )

Thursday, January 20, 2011

Difference between abstract class and interace

It is my problem, I always forget the when to use interface and abstract classes. I used to develop so large applications, but I seem to be unaware of when is the time to use interface. Here are some notes to be clear about interface and abstract classes:

Creation of abstract classes:
1) The abstract class should have abstract keyword before the class name e.g.
public abstract class Animal
public void eat()
//method description
public void sleep(int miliseconds)
//do implementation
public abstract void makeNoise();
2) There should be at least one abstract method in the abstract class which is to be defined in the subclass. There are other methods also and we can implement those methods inside the abstract class. The subclass may implement the abstract classes according to their need.
Note: we can not create instances of abstract classes. Actually, it is not appropriate to give provision of creating instances of abstract classes because it contains unimplemented abstract methods and JVM will confused what to do if those methods were called by the instances.

Creation of Interfaces
1) The keyword interface is used to declare interfaces. The interfaces are created similar ways as classes are created.
public interface Player
public String name();
public int numberToken();
public void takeTurn(Pile pile, int maxOnATurn);
Note: the interface methods are public and abstract. So, we can omit the public and abstract keywords also i.e. the below code is equivalent to above code:
public interface Player
public abstract String Name();
int numberToken();
abstract takeTurn(Pile pile, int maxOnATurn);
2) The method implementation is not allowed. The implementation is carried out in implementing class.
Note: there is no meaning of creating private members in interface because they are inaccessible in the implementing class. And it is compulsory for the implementing class to implement all the methods in the interface.

The implementation is carried out in the following way
class lazyPlayer implements Player
public string name()
//implement here
public int numberToken()
public void takeTurn(Pile pile, int maxOnATurn)


From above, we got the main differences on how the abstract classes and interfaces are created.

Abstract Class and Interface

1) Abstract class is similar to class except we cant create instances, but interface is just the declaration of methods which to be implemented by implementing class.

2) Since, Java does not support multiple inheritance, but we can implement multiple interfaces.

3) We select abstract class in case when we need to define only a few methods in subclass (specialisation) while using all other methods defined by superclass. But, in interface, we can't use any method from interface because no methods are implemented in interface, we need to implement in the implementing class.

I will add more notes here if I get something new regarding interface and abstract class.
Your Comments are Welcome!!!

Wednesday, January 19, 2011

Java Coding Conventions

It is difficult to remember all the rules for coding in any language. Since, it is good to follow certain coding standards so that it is easy to maintain the source code because the code would be understandable.
So, I have presented sample example which tries to cover almost all the rules for coding standards:

* %W% %E% Firstname Lastname
* Copyright (c) 1993-1996 Sun Microsystems, Inc. All Rights Reserved.
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
package java.blah;
import java.blah.blahdy.BlahBlah;
* Class description goes here.
* @version 1.10 04 Oct 1996
* @author Firstname Lastname
public class Blah extends SomeClass {
/* A class implementation comment can go here. */
/** classVar1 documentation comment */
public static int classVar1;
* classVar2 documentation comment that happens to be
* more than one line long
private static Object classVar2;
/** instanceVar1 documentation comment */
public Object instanceVar1;
/** instanceVar2 documentation comment */
protected int instanceVar2;
/** instanceVar3 documentation comment */
private Object[] instanceVar3;
* ...method Blah documentation comment...
public Blah() {
// ...implementation goes here...
* ...method doSomething documentation comment...
public void doSomething() {
// ...implementation goes here...
* ...method doSomethingElse documentation comment...
* @param someParam description
public void doSomethingElse(Object someParam) {
// ...implementation goes here...

Documentation on comments

Are you a Java programmer? yes, then the below snippet of code would fully illustrate how documentation comments are created and the required parameters for that.

* Graphics is the abstract base class for all graphics contexts
* which allow an application to draw onto components realized on
* various devices or onto off-screen images.
* A Graphics object encapsulates the state information needed
* for the various rendering operations that Java supports. This
* state information includes:

  • The Component to draw on
  • A translation origin for rendering and clipping coordinates
  • The current clip
  • The current color
  • The current font
  • The current logical pixel operation function (XOR or Paint)
  • The current XOR alternation color
    * (see setXORMode)


* Coordinates are infinitely thin and lie between the pixels of the
* output device.
* Operations which draw the outline of a figure operate by traversing
* along the infinitely thin path with a pixel-sized pen that hangs
* down and to the right of the anchor point on the path.
* Operations which fill a figure operate by filling the interior
* of the infinitely thin path.
* Operations which render horizontal text render the ascending
* portion of the characters entirely above the baseline coordinate.

* Some important points to consider are that drawing a figure that
* covers a given rectangle will occupy one extra row of pixels on
* the right and bottom edges compared to filling a figure that is
* bounded by that same rectangle.
* Also, drawing a horizontal line along the same y coordinate as
* the baseline of a line of text will draw the line entirely below
* the text except for any descenders.
* Both of these properties are due to the pen hanging down and to
* the right from the path that it traverses.

* All coordinates which appear as arguments to the methods of this
* Graphics object are considered relative to the translation origin
* of this Graphics object prior to the invocation of the method.
* All rendering operations modify only pixels which lie within the
* area bounded by both the current clip of the graphics context
* and the extents of the Component used to create the Graphics object.

@author Sami Shaio
* @author Arthur van Hoff

@version %I%, %G%

@since 1.0
public abstract class Graphics {

* Draws as much of the specified image as is currently available
* with its northwest corner at the specified coordinate (x, y).
* This method will return immediately in all cases, even if the
* entire image has not yet been scaled, dithered and converted
* for the current output device.

* If the current output representation is not yet complete then
* the method will return false and the indicated
* {@link ImageObserver} object will be notified as the
* conversion process progresses.

@param img the image to be drawn
* @param x the x-coordinate of the northwest corner
* of the destination rectangle in pixels
* @param y the y-coordinate of the northwest corner
* of the destination rectangle in pixels
* @param observer the image observer to be notified as more
* of the image is converted. May be
* null

@return true if the image is completely
* loaded and was painted successfully;
* false otherwise.

@see Image
* @see ImageObserver

@since 1.0
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer);

* Dispose of the system resources used by this graphics context.
* The Graphics context cannot be used after being disposed of.
* While the finalization process of the garbage collector will
* also dispose of the same system resources, due to the number
* of Graphics objects that can be created in short time frames
* it is preferable to manually free the associated resources
* using this method rather than to rely on a finalization
* process which may not happen for a long period of time.

* Graphics objects which are provided as arguments to the paint
* and update methods of Components are automatically disposed
* by the system when those methods return. Programmers should,
* for efficiency, call the dispose method when finished using
* a Graphics object only if it was created directly from a
* Component or another Graphics object.
* @see #create(int, int, int, int)
* @see #finalize()
* @see Component#getGraphics()
* @see Component#paint(Graphics)
* @see Component#update(Graphics)
* @since 1.0
public abstract void dispose();

* Disposes of this graphics context once it is no longer
* referenced.
* @see #dispose()
* @since 1.0
public void finalize() {

Tuesday, January 18, 2011

SVN startup and Commands


SVN stands for subversion and it is a very useful tool for parallel development of an application. If you are developing a software application with collaboration with other developers, then it is a good idea to use SVN to develop parallel because all the burdens and hassles to manage and create consistency of the files is done by it.

The concept of SVN is to distribute files to users from a central file, i.e. all the controls is carried out by central server, so, although, the files are modified by multiple programmers, the actually managing is carried out by the server. Different from the central file server, the SVN actually keeps the file versions so that it is easy for developer to track the files to find out the changes in files, so it is called version control.

As stated earlier, to use SVN, we first of all, need SVN server which carries out the tasks file management. So, you can make your computer to work as SVN repository so that you can use it as SVN testing server. For that, do the following steps:
1) Create a directory. I created temp_repos directory under /home/krishna/tmp
2) Run the below command
     svnadmin create /home/krishna/tmp/temp_repos
This new repository uses the default FSFS database layer.
3)Run the following command for confirmation:
svn info file:///home/krishna/tmp/temp_repos

The above command will print below information:
Path: temp_repos
URL: file:///home/krishna/tmp/temp_repos
Repository Root: file:///home/krishna/tmp/temp_repos
Repository UUID: db10e1a4-0059-44d6-8a0f-289514cf4bb9
Revision: 0
Node Kind: directory
Last Changed Rev: 0
Last Changed Date: 2011-01-18 23:09:24 +0100 (Tue, 18 Jan 2011)

Now we can use the above mentioned URL as repository.
Note: We do not need to start SVN server to use in this way, and we can use it locally.

If we want to run SVN to be accessible by remote computers, we must run the SVN server using the following command:
svnserve --daemon --root /home/krishna/tmp/temp_repos
Now you can access this repository using svn URLs.
svn info svn://svnhostname
The default access is readonly, but we can change the access by changing the file
Similary, we can create and assign the users in that file by using the passwd file in the location. The file is readable and we can easily understand where to modify in the file.


The commond commands for SVN are shown below:
(Note: the commands help can be obtained by typing svn --help)
The command summary is shown below:
blame (praise, annotate, ann)
changelist (cl)
checkout (co)
commit (ci)
copy (cp)
delete (del, remove, rm)
diff (di)
help (?, h)
list (ls)
move (mv, rename, ren)
propdel (pdel, pd)
propedit (pedit, pe)
propget (pget, pg)
proplist (plist, pl)
propset (pset, ps)
status (stat, st)
switch (sw)
update (up)

In linux, I could not actually remove the SVN repository connection to the local working directory. So, one way of doing, although it would be cumbersome, to deleted all .SVN folders. So, there is a shortcut command in linux which removes the all .SVN files:
find . -iname ".svn" -print0 | xargs -0 rm -r