Cricinfo Live Scores

Tuesday, January 29, 2008

Writing Your Own ClassLoader

What is a ClassLoader?

Among commercially popular programming languages, the Java language distinguishes itself by running on a Java virtual machine (JVM). This means that compiled programs are expressed in a special, platform-independent format, rather than in the format of the machine they are running on. This format differs from traditional executable program formats in a number of important ways. In particular, a Java program, unlike one written in C or C++, isn't a single executable file, but instead is composed of many individual class files, each of which corresponds to a single Java class. Additionally, these class files are not loaded into memory all at once, but rather are loaded on demand, as needed by the program. The ClassLoader is the part of the JVM that loads classes into memory. The Java ClassLoader, furthermore, is written in the Java language itself. This means that it's easy to create your own ClassLoader without having to understand the finer details of the JVM.

Why write a ClassLoader?

If the JVM has a ClassLoader, then why would you want to write another one? Good question. The default ClassLoader only knows how to load class files from the local filesystem. This is fine for regular situations, when you have your Java program fully compiled and waiting on your computer. But one of the most innovative things about the Java language is that it makes it easy for the JVM to get classes from places other than the local hard drive or network. For example, browsers use a custom ClassLoader to load executable content from a Web site. There are many other ways to get class files. Besides simply loading files from the local disk or from a network, you can use a custom ClassLoader to:

* Automatically verify a digital signature before executing untrusted code

* Transparently decrypt code with a user-supplied password

* Create dynamically built classes customized to the user's specific needs

Anything you can think of to write that can generate Java bytecode can be integrated into your application.

A Custom Class Loader:

The following code is an example of a custom class loader. For details you can go through this PDF Article.

Here is the source code for CompilingClassLoader.java

// $Id$

import java.io.*;

/*

A CompilingClassLoader compiles your Java source on-the-fly. It

checks for nonexistent .class files, or .class files that are older

than their corresponding source code.

*/

public class CompilingClassLoader extends ClassLoader

{

// Given a filename, read the entirety of that file from disk

// and return it as a byte array.

private byte[] getBytes( String filename ) throws IOException {

// Find out the length of the file

File file = new File( filename );

long len = file.length();

// Create an array that's just the right size for the file's

// contents

byte raw[] = new byte[(int)len];

// Open the file

FileInputStream fin = new FileInputStream( file );

// Read all of it into the array; if we don't get all,

// then it's an error.

int r = fin.read( raw );

if (r != len)

throw new IOException( "Can't read all, "+r+" != "+len );

// Don't forget to close the file!

fin.close();

// And finally return the file contents as an array

return raw;

}

// Spawn a process to compile the java source code file

// specified in the 'javaFile' parameter. Return a true if

// the compilation worked, false otherwise.

private boolean compile( String javaFile ) throws IOException {

// Let the user know what's going on

System.out.println( "CCL: Compiling "+javaFile+"..." );

// Start up the compiler

Process p = Runtime.getRuntime().exec( "javac "+javaFile );

// Wait for it to finish running

try {

p.waitFor();

} catch( InterruptedException ie ) { System.out.println( ie ); }

// Check the return code, in case of a compilation error

int ret = p.exitValue();

// Tell whether the compilation worked

return ret==0;

}

// The heart of the ClassLoader -- automatically compile

// source as necessary when looking for class files

public Class loadClass( String name, boolean resolve )

throws ClassNotFoundException {

// Our goal is to get a Class object

Class clas = null;

// First, see if we've already dealt with this one

clas = findLoadedClass( name );

//System.out.println( "findLoadedClass: "+clas );

// Create a pathname from the class name

// E.g. java.lang.Object => java/lang/Object

String fileStub = name.replace( '.', '/' );

// Build objects pointing to the source code (.java) and object

// code (.class)

String javaFilename = fileStub+".java";

String classFilename = fileStub+".class";

File javaFile = new File( javaFilename );

File classFile = new File( classFilename );

//System.out.println( "j "+javaFile.lastModified()+" c "+

// classFile.lastModified() );

// First, see if we want to try compiling. We do if (a) there

// is source code, and either (b0) there is no object code,

// or (b1) there is object code, but it's older than the source

if (javaFile.exists() &&

(!classFile.exists() ||

javaFile.lastModified() > classFile.lastModified())) {

try {

// Try to compile it. If this doesn't work, then

// we must declare failure. (It's not good enough to use

// and already-existing, but out-of-date, classfile)

if (!compile( javaFilename ) || !classFile.exists()) {

throw new ClassNotFoundException( "Compile failed: "+javaFilename );

}

} catch( IOException ie ) {

// Another place where we might come to if we fail

// to compile

throw new ClassNotFoundException( ie.toString() );

}

}

// Let's try to load up the raw bytes, assuming they were

// properly compiled, or didn't need to be compiled

try {

// read the bytes

byte raw[] = getBytes( classFilename );

// try to turn them into a class

clas = defineClass( name, raw, 0, raw.length );

} catch( IOException ie ) {

// This is not a failure! If we reach here, it might

// mean that we are dealing with a class in a library,

// such as java.lang.Object

}

//System.out.println( "defineClass: "+clas );

// Maybe the class is in a library -- try loading

// the normal way

if (clas==null) {

clas = findSystemClass( name );

}

//System.out.println( "findSystemClass: "+clas );

// Resolve the class, if any, but only if the "resolve"

// flag is set to true

if (resolve && clas != null)

resolveClass( clas );

// If we still don't have a class, it's an error

if (clas == null)

throw new ClassNotFoundException( name );

// Otherwise, return the class

return clas;

}

}

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Game Programming Event




In Pyxisnet we had a game programming contest which lasted for 3 days. During this time all the employees of our company gave their full effort to make it a success. Some of us spent the whole
night before pc's.

So, the thing i want to add here, my team which had 5 group members received the
"Most Creative" award. And, Now what i am going to do.....!!!!!!!!!!

I am going to share some pics of those award giving ceremony with all.

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Java print API for splitted JTable

In this article i am posting a Java API which is capable of printing JTable by splitting
the columns according to the Page Format of the printing file.

The example creates a Table Model from a set of data. The number of columns in this
case is more to fit in one page. So, the solution is provided here to split the table columns
and print them as such this.

Full Page
--------------------------
--------------------------
--------------------------
-----------1--------------
--------------------------

Split Page 1
---------
---------
---------
---1-2---
---------

Split Page 2
---------
---------
---------
---1-2---
---------

Split Page 3
---------
---------
---------
---1-3---
---------

The solution is implemented as applet. The solution goes in this way First getPageInfo()
function derives the page information. That is, the number of splits should be made depending
upon the length of the table column and page format. This function makes a temporary data
array subTableSplit which describes the page left and page right for each split of the page
through out the JTable.

Next that particular part pageWidth = pageRight-pageLeft is printed.

The complete code is available in the following link.


http://www.mediafire.com/?excw0rz0s7c

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Monday, January 28, 2008

Java Print API

This section explains how to create a basic printing program that displays a print dialog and prints the text "Hello World" to the selected printer.

Printing task usually consists of two parts:

Job control — Creating a print job, associating it with a printer, specifying the number of copies, and user print dialog interaction.
Page Imaging — Drawing content to a page, and managing content that spans pages (pagination).
First create the printer job. The class representing a printer job and most other related classes is located in the java.awt.print package.

import java.awt.print.*;

PrinterJob job = PrinterJob.getPrinterJob();

Next provide code that renders the content to the page by implementing the Printable interface.

class HelloWorldPrinter implements Printable { ... }
..
job.setPrintable(new HelloWorldPrinter());

An application typically displays a print dialog so that the user can adjust various options such as number of copies, page orientation, or the destination printer.

boolean doPrint = job.printDialog();

This dialog appears until the user either approves or cancels printing. The doPrint variable will be true if the user gave a command to go ahead and print. If the doPrint variable is false, the user cancelled the print job. Since displaying the dialog at all is optional, the returned value is purely informational.

If the doPrint variable is true, then the application will request that the job be printed by calling the PrinterJob.print method.

if (doPrint) {
try {
job.print();
} catch (PrinterException e) {
/* The job did not successfully complete */
}
}

The PrinterException will be thrown if there is problem sending the job to the printer. However, since the PrinterJob.print method returns as soon as the job is sent to the printer, the user application cannot detect paper jams or paper out problems. This job control boilerplate is sufficient for basic printing uses.

The Printable interface has only one method:

public int print(Graphics graphics, PageFormat pf, int page)
throws PrinterException;

The PageFormat class describes the page orientation (portrait or landscape) and its size and imageable area in units of 1/72nd of an inch. Imageable area accounts for the margin limits of most printers (hardware margin). The imageable area is the space inside these margins, and in practice if is often further limited to leave space for headers or footers.

A page parameter is the zero-based page number that will be rendered.

The following code represents the full Printable implementation:

import java.awt.print.*;
import java.awt.*;

public class HelloWorldPrinter implements Printable {

public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {

if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}

/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());

/* Now we perform our rendering */
g.drawString("Hello world!", 100, 100);

/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
}

The complete code for this example is in HelloWorldPrinter.java.
Sending a Graphics instance to the printer is essentially the same as rendering it to the screen. In both cases you need to perform the following steps:

To draw a test string is as easy as the other operations that were described for drawing to a Graphics2D.
Printer graphics have a higher resolution, which should be transparent to most code.
The Printable.print() method is called by the printing system, just as the Component.paint() method is called to paint a Component on the display. The printing system will call the Printable.print() method for page 0, 1,.. etc until the print() method returns NO_SUCH_PAGE.
The print() method may be called with the same page index multiple times until the document is completed. This feature is applied when the user specifies attributes such as multiple copies with collate option.
The PageFormat's imageable area determines the clip area. Imageable area is also important in calculating pagination, or how to span content across printed pages, since page breaks are determined by how much can fit on each page.

--------------------------------------------------------------------------------
Note: This article is taken from SUN Java Print Tutorial
--------------------------------------------------------------------------------

The source code avaiable through this link is a complete class which prints
components like JPanel, JTable etc.

Source Code

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Why I am a Software Engineer?


When I was young I thought I would be a Computer Engineer.

When I got admitted in University I thought I would be a Computer Engineer.

When I participated in several programming contests my teachers and friends said you should be a software engineer.

When I solved several problems and gave birth to my beautiful child solutions I thought I should be a software engineer.

When I thought to my mind I saw in my dreams I was a good Software Engineer.

When, the nature is showing that everyone even my mind also want me to be a Software Engineer. Then I decide to be a software Engineer because I am a child of the nature, how can I disobey my MUM.



Author:
-----------------------
Kazi Masudul Alam
Software Engineer

Sunday, January 27, 2008

The Course Booking Form

The Course Booking Form is a simple form illustrating the principles of UserForm design and the associated VBA coding.

It uses a selection of controls including textbox, combo boxes, option buttons grouped in a frame, check boxes and command buttons.

When the user clicks the OK button their input is entered into the next available row on the worksheet.

Description of the Form:

There are two simple text boxes (Name: and Phone:) into which the user can type free text, and two combo boxes (Department and Course) that let the user to pick an item from the list.

There are three option buttons (Introduction, Intermediate and Advanced) grouped in a frame (Level) so that the user can choose only one of the options.

There are two check boxes (Lunch Required and Vegetarian) that, because they are not grouped in a frame, can both be chosen if required. However, if the person making the booking does not want lunch we do not need to know whether or not they are vegetarian. So, the Vegetarian check box is greyed-out until required.

There are three command buttons (OK, Cancel and Clear Form) each of which performs a pre-defined function when clicked.

The Control Properties Settings:

Control

Type

Property

Setting

UserForm

UserForm

Name

frmCourseBooking



Caption

Course Booking Form

Name

Text Box

Name

txtName

Phone

Text Box

Name

txtPhone

Department

Combo Box

Name

cboDepartment

Course

Combo Box

Name

cboCourse

Level

Frame

Name

fraLevel



Caption

Level

Introduction

Option Button

Name

optIntroduction

Intermediate

Option Button

Name

optIntermediate

Advanced

Option Button

Name

optAdvanced

Lunch Required

Check Box

Name

chkLunch

Vegetarian

Check Box

Name

chkVegetarian



Enabled

False

OK

Command Button

Name

cmdOk



Caption

OK



Default

True

Cancel

Command Button

Name

cmdCancel



Caption

Cancel



Cancel

True

Clear Form

Command Button

Name

cmdClearForm

Building the Form

If you want to build the form yourself, simply copy the layout shown in the illustration above. Follow the steps below:

1. Open the workbook that you want the form to belong in (UserForms like macros have to be attached to a workbook) and switch to the Visual Basic Editor.

2. In the Visual Basic Editor click the Insert UserForm button (or go to Insert > UserForm).

3. If the toolbox does not appear by itself (first click the form to make sure it isn’t hiding) click the Toolbox button (or go to View > Toolbox).

4. To place a control on the form click the appropriate button on the toolbox then click the form. Controls can be moved by dragging them by their edges, or resized by dragging the buttons around their perimeter.

5. To edit the properties of a control, make sure the chosen control is selected then make the appropriate changes in the Properties window. If you can’t see the properties window go to View > Properties Window.

6. To remove a control from the form, select it and click the Delete key on your keyboard.

A UserForm will not actually do anything until the code that drives the form and its various controls is created. The next step is to write the code that drives the form itself.

Adding the Code: 1 Initialising the Form

Initialising the Form:

Most forms need some kind of setting up when they open. This may be setting default values, making sure field are empty, or building the lists of combo boxes. This process is called Initialising the Form and it is taken care of by a macro called UserForm_Initialize (in case you are confused by my varying spelling of the word "initialis(z)e", it's because I speak English and VBA speaks American - but don't worry, VBA will spell it for you!). Here's how to build the code to initialise the Course Booking Form:

1. To view the form’s code window go to View > Code or click F7.

2. When the code window first opens it contains an empty UserForm_Click() procedure. Use the drop-down lists at the top of the code window to choose UserForm and Initialize. This will create the procedure you need. You can now delete the UserForm_Click() procedure.

3. Enter the following code into the procedure:

Private Sub UserForm_Initialize()

txtName.Value = ""

txtPhone.Value = ""

With cboDepartment

.AddItem "Sales"

.AddItem "Marketing"

.AddItem "Administration"

.AddItem "Design"

.AddItem "Advertising"

.AddItem "Dispatch"

.AddItem "Transportation"

End With

cboDepartment.Value = ""

With cboCourse

.AddItem "Access"

.AddItem "Excel"

.AddItem "PowerPoint"

.AddItem "Word"

.AddItem "FrontPage"

End With

cboCourse.Value = ""

optIntroduction = True

chkLunch = False

chkVegetarian = False

txtName.SetFocus

End Sub

How the Initialise Code Works:

The purpose of the UserForm_Initialize() procedure is to prepare the form for use, setting the default values for the various controls and creating the lists that the combo boxes will show.

These lines set the contents of the two text boxes to empty:

txtName.Value = ""

txtPhone.Value = ""

Next come the instructions for the combo boxes. First of all the contents of the list are specified, then the initial value of the combo box is set to empty.

With cboDepartment

.AddItem "Sales"

.AddItem "Marketing"

(as many as necessary…)

End With

cboDepartment.Value = ""

If required an initial choice can be made from the option group, in this case:

optIntroduction = True

Both check boxes are set to False (i.e. no tick). Set to True if you want the check box to appear already ticked:

chkLunch = False

chkVegetarian = False

Finally, The focus is taken to the first text box. This places the users cursor in the text box so that they do not need to click the box before they start to type:

txtName.SetFocus

Adding the Code: 2 Making the Buttons Work

There are three command buttons on the form and each must be powered by its own procedure. Starting with the simple ones…

Coding the Cancel Button:

Earlier, we used the Properties Window to set the Cancel property of the Cancel button to True. When you set the Cancel property of a command button to True, this has the effect of "clicking" that button when the user presses the Esc key on their keyboard. But this alone will not cause anything to happen to the form. You need to create the code for the click event of the button that will, in this case, close the form. Here's how:

1. With the UserForm open for editing in the Visual Basic Editor, double-click the Cancel button. The form's code window opens with the cmdCancel_Click() procedure ready for editing.

2. The code for closing a form is very simple. Add a line of code to the procedure so it looks like this:

Private Sub cmdCancel_Click()

Unload Me

End Sub

Coding the Clear Form Button:

I added a button to clear the form in case the user wanted to change their mind and reset everything, and to make it easier if they had several bookings to make at one time. All it has to do is run the Initialise procedure again. A macro can be told to run another macro (or series of macros if necessary) by using the Call keyword:

1. Double-click the Clear Form button. The form's code window opens with the cmdClearForm_Click() procedure ready for editing.

2. Add a line of code to the procedure so it looks like this:

Private Sub cmdClearForm_Click()

Call UserForm_Initialize

End Sub

Coding the OK Button:

This is the piece of code that has to do the job of transferring the user's choices and text input on to the worksheet. When we set the Cancel button's Cancel property to True we also set the OK button's Default property to True. This has of clicking the OK button when the user presses the Enter (or Return) key on their keyboard (providing they have not used their Tab key to tab to another button). Here's the code to make the button work:

1. Double-click the OK button. The form's code window opens with the cmdOK_Click() procedure ready for editing.

2. Edit the procedure to add the following code:

Private Sub cmdOK_Click()

ActiveWorkbook.Sheets("Course Bookings").Activate

Range("A1").Select

Do

If IsEmpty(ActiveCell) = FalseThen

ActiveCell.Offset(1, 0).Select

End If

Loop Until IsEmpty(ActiveCell) = True

ActiveCell.Value = txtName.Value

ActiveCell.Offset(0, 1) = txtPhone.Value

ActiveCell.Offset(0, 2) = cboDepartment.Value

ActiveCell.Offset(0, 3) = cboCourse.Value

If optIntroduction = True Then

ActiveCell.Offset(0, 4).Value = "Intro"

ElseIf optIntermediate = True Then

ActiveCell.Offset(0, 4).Value = "Intermed"

Else

ActiveCell.Offset(0, 4).Value = "Adv"

End If

If chkLunch = True Then

ActiveCell.Offset(0, 5).Value = "Yes"

Else

ActiveCell.Offset(0, 5).Value = "No"

End If

If chkVegetarian = True Then

ActiveCell.Offset(0, 6).Value = "Yes"

Else

If chkLunch = False Then

ActiveCell.Offset(0, 6).Value = ""

Else

ActiveCell.Offset(0, 6).Value = "No"

End If

End If

Range("A1").Select

End Sub

How the CmdOK_Click code works:

The first two lines make sure that the correct workbook is active and moves the selection to cell A1:

ActiveWorkbook.Sheets("Course Bookings").Activate

Range("A1").Select

The next few lines moves the selection down the worksheet until it finds an empty cell:

Do

If IsEmpty(ActiveCell) = False Then

ActiveCell.Offset(1, 0).Select

End If

Loop Until IsEmpty(ActiveCell) = True

The next four lines start to write the contents of the form on to the worksheet, using the active cell (which is in column A) as a reference and moving along the row a cell at a time:

ActiveCell.Value = txtName.Value

ActiveCell.Offset(0, 1) = txtPhone.Value

ActiveCell.Offset(0, 2) = cboDepartment.Value

ActiveCell.Offset(0, 3) = cboCourse.Value

Now we come to the option buttons. These have been placed in a frame on the form so the user can choose only one. An IF statement is used to instruct Excel what to for each option:

If optIntroduction = True Then

ActiveCell.Offset(0, 4).Value = "Intro"

ElseIf optIntermediate = True Then

ActiveCell.Offset(0, 4).Value = "Intermed"

Else

ActiveCell.Offset(0, 4).Value = "Adv"

End If

VBA IF statements are much easier to manage than Excel's IF function. You can have as many options as you want, just insert an additional ElseIf for each one. If there were only two options, you wouldn't need the ElseIf, just the If and Else would suffice (don't forget - they all need an End If).

There is another IF statement for each check box. For the Lunch Required check box, a tick in the box means "Yes" the person requires lunch, and no tick means "No" they don't.

If chkLunch = True Then

ActiveCell.Offset(0, 5).Value = "Yes"

Else

ActiveCell.Offset(0, 5).Value = "No"

End If

We could use a similar IF statement for the Vegetarian check box, but if the person does not require lunch it is irrelevant whether or not they are vegetarian. I any case, it would be wrong to assume that they were not vegetarian simply because they did not require lunch. The IF statement therefore contains a second, nested if statement:

If chkVegetarian = True Then

ActiveCell.Offset(0, 6).Value = "Yes"

Else

If chkLunch = False Then

ActiveCell.Offset(0, 6).Value = ""

Else

ActiveCell.Offset(0, 6).Value = "No"

End If

End If

A tick in the box means "Yes" the person is vegetarian. If there is no tick in the box, the nested IF statement looks at the Lunch Required check box. If the Lunch Required check box has a tick in it then no tick in the Vegetarian check box means that the person is not vegetarian so it inserts "No" into the cell. However, if the Lunch Required check box does not have a tick in it, then we do not know whether or not the person is vegetarian (it doesn't matter anyway) so the cell is left blank ("").

Finally the selection is taken back to the beginning of the worksheet, ready for the next entry:

Range("A1").Select

Adding the Code 3: Manipulating the Form

Finally, an example of how the controls on a form can be manipulated whilst it is in use. When the control properties were set, the Enabled property of the Vegetarian check box was set to False. When a control is not enabled the user cannot enter a value into it, although it can hold a value that was there already, and VBA can add, remove or change the value.

We don't need to know whether or not the person is vegetarian (even if they are!) if they aren't ordering lunch. So, the Vegetarian check box remains disabled unless a tick is placed in the Lunch Required check box. Then the user is free to tick the Vegetarian check box if they want to. If they tick it we will know that they have answered "Yes" and if they don't we know they have answered "No".

We can toggle the Enabled property from False to True by having a procedure that runs automatically whenever the value of the Lunch Required check box changes. Fortunately, more controls have a Change procedure and the one we use here is chkLunch_Change(). We'll use this to enable the Vegetarian check box when the Lunch Required check box is ticked, and disable it when the Lunch Required check box is not ticked.

There's just one more thing we need to do. Supposing someone ticked the Lunch Required check box, and also ticked the Vegetarian check box. Then they changed their mind and removed the tick from the Lunch Required check box. The Vegetarian check box would be disabled but the tick that was put in earlier would remain.

An extra line of code can make sure the tick is removed when the box is disabled. Here's the whole thing:

Private Sub chkLunch_Change()

If chkLunch = True Then

chkVegetarian.Enabled = True

Else

chkVegetarian.Enabled = False

chkVegetarian = False

End If

End Sub

Opening the Form

The form is now ready for use so it needs to be opened with a simple macro. That can be attached to a custom toolbar button, a command button drawn on the worksheet, or any graphic (right click the graphic and choose Assign Macro). If necessary, create a new module for the workbook and add this procedure:

Sub OpenCourseBookingForm()

frmCourseBooking.Show

End Sub



Author:
-----------------------
Kazi Masudul Alam
Software Engineer


One day i wanted to create a big buisness network


I guess one day there will be a business network where people will be able to make their own business domains in the PC's. No Money for DOMAIN name and No Money for web hosting.
Only my PC and my space.

Network speed will be high and p2p connections will be possible for each client. A beautiful
p2p network. There will be an invisible world where with the plug in of one pc a network grows
and others are connected to the domain. A separate business world. My PC will be my market.

Author:
-----------------------
Kazi Masudul Alam
Software Engineer

A website resides in the p2p network

Again i wish something! There will be a floating website which will reside in a P2P network.
A website which is owned by all the users of the network.

When, one user will plug in the PC then the network will start and other will join the growth.
Pages will be in separate PCs. Every thing is distributed. Every word, every sentence and
every mind will be distributed in the p2p network.

May be there will be some missing of information. But, think! what will happen! Global people,
gloabl site with global content....!!!
It will be fully parallel! Every word of the site will be parallel.

A central site locator will manage the list of the links.

The request will be distributed in the P2P network. And the result will be merged to provide
the result. Hoping in the mind when there will be a P2P website!!!

Author:
-----------------------
Kazi Masudul Alam
Software Engineer