Monday, May 31, 2010

Network Technology

Unit-1:  Overview of Internet:  Address and domain Management, SNMP, Transport Layer issues, 
TCP/IP, FTP, WWW undergoing technology, E mail talent, FTP, Gateway, Dial-up, SLIP/PPP 
Dedicated lines, Internet searching tools, gopher, Archie, Veronica, WWW, Lynx, Mosaic, WAIS, 
Usenet.


Unit-2:  Security issues, CGI, PERL, HTML, VRML, JAVA, VB script and other internet development
tools, internet networking  TCP/IP protocols . ) Network Security and Management.



Unit-3:  Application Layer Services and protocols (RPC, NFC, SMTP, FTP, TELENET), Review of
LAN, Principles of IBASE5 (Strain), Transmitter and  receiver of  IBASE5 (Starian), Node, LAN
Manager, Software of IBASE5 Node, 10BASE5 Ethernet and 10BASE2 (Cheaper net), Twisted pair
Ethernet, Serial Communication, Connecting LANs and WANS.



Unit-4:  Serial Communication Circuits, Modems, USART-Processor  Interface Data Buffer Block of
8251A, Control logic of USART, PROTOCOLS, Transmitter, Receiver, Synchronous Modems and 
Asynchronous Modems.  SYNDET/BRKDET ion 8251A, Monitoring of 8251A, writing characters to be
transmitted to 8251A, Monitoring of 8251A.  Read status, ISDN: Technology, devices, Architecture
Protocols, Flow Control Error detection and Correction, ATM, Technology, Inter Networking
SDH/SONET.

Saturday, May 29, 2010

Fibonacci series

#include<stdio.h>
#include<conio.h>

void main(void)
{
  int i,j,k,n;
  clrscr();
  i=0;
  j=1;
  printf("%d\n %d\n",i,j);
  for(n=0;n<=5;n++)
  {
    k=i+j;
    i=j;
    j=k;
    printf("%d\n",k);
  }
  getch();
}

Output------>

Prime No.

- Program for Prime Number Generation

#include<stdio.h> 
main()
{
 int n,i=1,j,c;
 clrscr();
 printf("Enter Number Of Terms");
 printf("Prime Numbers Are Follwing");
 scanf("%d",&n);
 while(i<=n)
 {
   c=0;
   for(j=1;j<=i;j++)
   {
     if(i%j==0)
     c++;
    }
    if(c==2)
    printf("%d ",i);
    i++;
 }
 getch();
}
Output-------->
---------------- - Program to findout all Prime Number between 1 to 100.
#include<stdio.h>
void main()
{
  int i,num=1;
  clrscr();

  while(num<=100)
  {
   i=2;
   while(i<=num)
   {
    if(num%i==0)
    break;
    i++;
   }
   if(i==num)
   printf(" %d",num);
   num++;
 }  
  printf(" all are Prime");
  getch();
}
Output-------->

Thursday, May 27, 2010

PHP Functions

The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.

PHP Built-in Functions

For a complete reference and examples of the built-in functions, please visit our PHP Reference.

PHP Functions

In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.

Create a PHP Function

A function will be executed by a call to the function.

Syntax

function functionName()
{
code to be executed;
}
PHP function guidelines:
  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)

Example

A simple function that writes my name when it is called:



function writeName()
{
echo "Kai Jim Refsnes";
}

echo "My name is ";
writeName();
?>


Output:
My name is Kai Jim Refsnes


PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.

Example 1

The following example will write different first names, but equal last name:



function writeName($fname)
{
echo $fname . " Refsnes.
";
}

echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>


Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.

Example 2

The following function has two parameters:



function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "
";
}

echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>


Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?
 

PHP Functions - Return values

To let a function return a value, use the return statement.

Example




function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo "1 + 16 = " . add(1,16);
?>


Output:
1 + 16 = 17

PHP Looping

Loops execute a block of code a specified number of times, or while a specified condition is true.

PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while - loops through a block of code while a specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

The while Loop

The while loop executes a block of code while a condition is true.

Syntax

while (condition)
  {
  code to be executed;
  }

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:



$i=1;
while($i<=5)
  {
  echo "The number is " . $i . "
";
  $i++;
  }
?>


Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5


The do...while Statement

The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.

Syntax

do
  {
  code to be executed;
 
}
while (condition);

Example

The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:



$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "
";
  }
while ($i<=5);
?>


Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
_____________________________________________________________________________

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init; condition; increment)
  {
  code to be executed;
  }
Parameters:
  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:



for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "
";
  }
?>


Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5


The foreach Loop

The foreach loop is used to loop through arrays.

Syntax

foreach ($array as $value)
  {
  code to be executed;
  }
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.

Example

The following example demonstrates a loop that will print the values of the given array:



$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "
";
  }
?>


Output:
one
two
three

PHP Operators

This section lists the different operators used in PHP.


Arithmetic Operators
Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x=4
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus (division remainder) 5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4


Assignment Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y


Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true


Logical Operators
Operator Description Example
&& and x=6
y=3 (x < 10 && y > 1) returns true
|| or x=6
y=3 (x==5 || y==5) returns false
! not x=6
y=3 !(x==y) returns true

PHP

What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
  • PHP is an open source software
  • PHP is free to download and use

What is a PHP File?

  • PHP files can contain text, HTML tags and scripts
  • PHP files are returned to the browser as plain HTML 
  • PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use

PHP + MySQL

  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP is FREE to download from the official PHP resource:  www.php.net
  • PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:
  • Install Apache (or IIS) on your own server, install PHP, and MySQL
  • Or find a web hosting plan with PHP and MySQL support.

What do you Need?

If your server supports PHP you don't need to do anything.
Just create some .php files in your web directory, and the server will parse them for you. Because it is free, most web hosts offer PHP support.
However, if your server does not support PHP, you must install PHP.
Here is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php

Download PHP

Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database

Download MySQL for free here: http://www.mysql.com/downloads/index.html

Download Apache Server

Download Apache for free here: http://httpd.apache.org/download.cgi

PHP code is executed on the server, and the plain HTML result is sent to the browser.

Basic PHP Syntax

A PHP scripting block always starts with and ends with ?>. A PHP scripting block can be placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with .
For maximum compatibility, we recommend that you use the standard form (
?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:



echo "Hello World";
?>


Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed.

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.



//This is a comment

/*
This is
a comment
block
*/
?>



Usage

PHP is a general-purpose scripting language that is especially suited to server-side web development where PHP generally runs on a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content. It can also be used for command-line scripting and client-side GUI applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use


Syntax



PHP only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and is not processed by PHP (although non-PHP text is still subject to control structures described within PHP code). The most common delimiters are to open and ?> to close PHP sections. delimiters are also available, as are the shortened forms or (which is used to echo back a string or variable) and ?> as well as ASP-style short forms <% or <%= and %>. While short delimiters are used, they make script files less portable as their purpose can be disabled in the PHP configuration, and so they are discouraged. The purpose of all these delimiters is to separate PHP code from non-PHP code, including HTML.
The first form of delimiters, and ?>, in XHTML and other XML documents, creates correctly formed XML 'processing instructions'. This means that the resulting mixture of PHP code and other markup in the server-side file is itself well-formed XML.
Variables are prefixed with a dollar symbol and a type does not need to be specified in advance. Unlike function and class names, variable names are case sensitive. Both double-quoted ("") and heredoc strings allow the ability to embed a variable's value into the string. PHP treats newlines as whitespace in the manner of a free-form language (except when inside string quotes), and statements are terminated by a semicolon. PHP has three types of comment syntax: /* */ marks block and inline comments; // as well as # are used for one-line comments. The echo statement is one of several facilities PHP provides to output text (e.g. to a web browser).
In terms of keywords and language syntax, PHP is similar to most high level languages that follow the C style syntax. If conditions, for and while loops, and function returns are similar in syntax to languages such as C, C++, Java and Perl.

Friday, May 21, 2010

Class loader

The class loader concept, one of the cornerstones of the Java virtual machine, describes the behavior of converting a named class into the bits responsible for implementing that class. Because class loaders exist, the Java run time does not need to know anything about files and file systems when running Java programs.

What class loaders do

Classes are introduced into the Java environment when they are referenced by name in a class that is already running. There is a bit of magic that goes on to get the first class running (which is why you have to declare the main() method as static, taking a string array as an argument), but once that class is running, future attempts at loading classes are done by the class loader.
At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:
Class r = loadClass(String className, boolean resolveIt); 


The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well).
All Java virtual machines include one class loader that is embedded in the virtual machine. This embedded loader is called the primordial class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.
The primordial class loader implements the default implementation of loadClass(). Thus, this code understands that the class name java.lang.Object is stored in a file with the prefix java/lang/Object.class somewhere in the class path. This code also implements both class path searching and looking into zip files for classes. The really cool thing about the way this is designed is that Java can change its class storage model simply by changing the set of functions that implements the class loader.
Digging around in the guts of the Java virtual machine, you will discover that the primordial class loader is implemented primarily in the functions FindClassFromClass and ResolveClass.
So when are classes loaded? There are exactly two cases: when the new bytecode is executed (for example, FooClass f = new FooClass();) and when the bytecodes make a static reference to a class (for example, System.out).

A non-primordial class loader

"So what?" you might ask.

The Java virtual machine has hooks in it to allow a user-defined class loader to be used in place of the primordial one. Furthermore, since the user class loader gets first crack at the class name, the user is able to implement any number of interesting class repositories, not the least of which is HTTP servers -- which got Java off the ground in the first place.
There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files). 
A user class loader gets the chance to load a class before the primordial class loader does. Because of this, it can load the class implementation data from some alternate source, which is how the AppletClassLoader can load classes using the HTTP protocol.

Building a SimpleClassLoader

A class loader starts by being a subclass of java.lang.ClassLoader. The only abstract method that must be implemented is loadClass(). The flow of loadClass() is as follows:

  • Verify class name.
  • Check to see if the class requested has already been loaded.
  • Check to see if the class is a "system" class.
  • Attempt to fetch the class from this class loader's repository.
  • Define the class for the VM.
  • Resolve the class.
  • Return the class to the caller.


Some Java code that implements this flow is taken from the file SimpleClassLoader and appears as follows with descriptions about what it does interspersed with the code.
public synchronized Class loadClass(String className, boolean resolveIt) 
         throws ClassNotFoundException { 
         Class result; 
         byte classData[]; 
         System.out.println(" >>>>>> Load class : "+className); 
         /* Check our local cache of classes */ 
         result = (Class)classes.get(className); 
         if (result != null) { 
             System.out.println(" >>>>>> returning cached result."); 
             return result; 
} 


The code above is the first section of the loadClass method. As you can see, it takes a class name and searches a local hash table that our class loader is maintaining of classes it has already returned. It is important to keep this hash table around since you must return the same class object reference for the same class name every time you are asked for it. Otherwise the system will believe there are two different classes with the same name and will throw a ClassCastException whenever you assign an object reference between them. It's also important to keep a cache because the loadClass() method is called recursively when a class is being resolved, and you will need to return the cached result rather than chase it down for another copy. 

/* Check with the primordial class loader */ 
try { 
    result = super.findSystemClass(className); 
    System.out.println(" >>>>>> returning system class (in CLASSPATH)."); 
    return result; 
    } catch (ClassNotFoundException e) { 
             System.out.println("        >>>>>> Not a system class."); 
    } 


As you can see in the code above, the next step is to check if the primordial class loader can resolve this class name. This check is essential to both the sanity and security of the system. For example, if you return your own instance of java.lang.Object to the caller, then this object will share no common superclass with any other object! The security of the system can be compromised if your class loader returned its own value of java.lang.SecurityManager, which did not have the same checks as the real one did.
/* Try to load it from our repository */ 
classData = getClassImplFromDataBase(className); 
if (classData == null) { 
    throw new ClassNotFoundException(); 
} 


After the initial checks, we come to the code above which is where the simple class loader gets an opportunity to load an implementation of this class. As you can see from the source code, the SimpleClassLoader has a method getClassImplFromDataBase() which in our simple example merely prefixes the directory "store\" to the class name and appends the extension ".impl". I chose this technique in the example so that there would be no question of the primordial class loader finding our class. Note that the sun.applet.AppletClassLoader prefixes the codebase URL from the HTML page where an applet lives to the name and then does an HTTP get request to fetch the bytecodes.

/* Define it (parse the class file) */ 
result = defineClass(classData, 0, classData.length); 


If the class implementation was loaded, the penultimate step is to call the defineClass() method from java.lang.ClassLoader, which can be considered the first step of class verification. This method is implemented in the Java virtual machine and is responsible for verifying that the class bytes are a legal Java class file. Internally, the defineClass method fills out a data structure that the JVM uses to hold classes. If the class data is malformed, this call will cause a ClassFormatError to be thrown.
if (resolveIt) { 
    resolveClass(result); 
} 


The last class loader-specific requirement is to call resolveClass() if the boolean parameter resolveIt was true. This method does two things: First, it causes any classes that are referenced by this class explicitly to be loaded and a prototype object for this class to be created; then, it invokes the verifier to do dynamic verification of the legitimacy of the bytecodes in this class. If verification fails, this method call will throw a LinkageError, the most common of which is a VerifyError.
Note that for any class you will load, the resolveIt variable will always be true. It is only when the system is recursively calling loadClass() that it may set this variable false because it knows the class it is asking for is already resolved.
classes.put(className, result); 
System.out.println("        >>>>>> Returning newly loaded class."); 
        return result; 
} 


The final step in the process is to store the class we've loaded and resolved into our hash table so that we can return it again if need be, and then to return the Class reference to the caller.
Of course if it were this simple there wouldn't be much more to talk about. In fact, there are two issues that class loader builders will have to deal with, security and talking to classes loaded by the custom class loader.

Security considerations

Whenever you have an application loading arbitrary classes into the system through your class loader, your application's integrity is at risk. This is due to the power of the class loader. Let's take a moment to look at one of the ways a potential villain could break into your application if you aren't careful.

In our simple class loader, if the primordial class loader couldn't find the class, we loaded it from our private repository. What happens when that repository contains the class java.lang.FooBar ? There is no class named java.lang.FooBar, but we could install one by loading it from the class repository. This class, by virtue of the fact that it would have access to any package-protected variable in the java.lang package, can manipulate some sensitive variables so that later classes could subvert security measures. Therefore, one of the jobs of any class loader is to protect the system name space.
In our simple class loader we can add the code:
if (className.startsWith("java.")) 
    throw newClassNotFoundException(); 


just after the call to findSystemClass above. This technique can be used to protect any package where you are sure that the loaded code will never have a reason to load a new class into some package.

Another area of risk is that the name passed must be a verified valid name. Consider a hostile application that used a class name of "..\..\..\..\netscape\temp\xxx.class" as its class name that it wanted loaded. Clearly, if the class loader simply presented this name to our simplistic file system loader this might load a class that actually wasn't expected by our application. Thus, before searching our own repository of classes, it is a good idea to write a method that verifies the integrity of your class names. Then call that method just before you go to search your repository.

Using an interface to bridge the gap

The second non-intuitive issue with working with class loaders is the inability to cast an object that was created from a loaded class into its original class. You need to cast the object returned because the typical use of a custom class loader is something like:

CustomClassLoader ccl = new CustomClassLoader(); 
Object o; 
Class c; 
c = ccl.loadClass("someNewClass"); 
o = c.newInstance(); 
((SomeNewClass)o).someClassMethod(); 


However, you cannot cast o to SomeNewClass because only the custom class loader "knows" about the new class it has just loaded.
There are two reasons for this. First, the classes in the Java virtual machine are considered castable if they have at least one common class pointer. However, classes loaded by two different class loaders will have two different class pointers and no classes in common (except java.lang.Object usually). Second, the idea behind having a custom class loader is to load classes after the application is deployed so the application does not know a priory about the classes it will load. This dilemma is solved by giving both the application and the loaded class a class in common.
There are two ways of creating this common class, either the loaded class must be a subclass of a class that the application has loaded from its trusted repository, or the loaded class must implement an interface that was loaded from the trusted repository. This way the loaded class and the class that does not share the complete name space of the custom class loader have a class in common. In the example I use an interface named LocalModule, although you could just as easily make this a class and subclass it.
The best example of the first technique is a Web browser. The class defined by Java that is implemented by all applets is java.applet.Applet. When a class is loaded by AppletClassLoader, the object instance that is created is cast to an instance of Applet. If this cast succeeds the init() method is called. In my example I use the second technique, an interface.

Playing with the example

To round out the example I've created a couple more .java files. These are:

public interface LocalModule { 
    /* Start the module */ 
    void start(String option); 
} 


This interface is shared between my local class repository (it is in the classpath of my application) and the loaded module. A test class helps illustrate the class loader in operation. The code below shows an example class named TestClass that implements the shared interface. When this class is loaded by the SimpleClassLoader class, we can cast instantiated objects to the common interface named LocalModule.
import java.util.Random; 
import java.util.Vector>; 
public class TestClass implements LocalModule { 
    /* 
     * This is an example of a class reference that will be resolved 
     * at load time. 
     */ 
    Vector v = new Vector(); 
    /** This is our start function */ 
    public void start(String opt) { 
        /* This reference will be resolved at run time. */ 
        Random r; 
        System.out.println("Running the Test class, option was                   '"+opt+"'"); 
        System.out.println("Now initializing a Random object."); 
        r = new Random(); 
        for (int i = 0; i < 5; i++) { 
            v.addElement(new Integer(r.nextInt())); 
        } 
        /* This reference should get the cached copy of random. */ 
        r = new Random(); 
        System.out.println("A series of 5 random numbers: "); 
        for (int i = 0; i < v.size(); i++) { 
            Integer z = (Integer)v.elementAt(i); 
            System.out.println(i+": "+z); 
        } 
    } 
} 


This test class is to be loaded by our simple class loader and then executed by the example application. There are a couple of interesting things to try and do when running the application. First, watch which classes get loaded and when they get loaded. The initialization of v and the static reference to System cause these classes to be loaded. Furthermore, since out is actually a PrintStream object, this class gets loaded as well, and perhaps suprisingly the class java.lang.StringBuffer gets loaded. This last class is loaded because the compiler automatically changes string expressions into invocations of StringBuffer objects.
When you run it, you will notice that the java.util.Random class is not loaded until after the statement "Now initializing a Random object" is printed. Even though it was referenced in the definition of r, it is not actually used until the new operator is executed. The last thing to notice is that the second time java.util.Random is referenced, your class loader does not get a chance to load it; it is already installed in the virtual machine's loaded class database. It is this latter feature that will be changed in a future release of Java to support garbage collectible classes.
Our simple application Example ties everything together:
public class Example { 
    public static void main(String args[]) { 
        SimpleClassLoader sc = new SimpleClassLoader(); 
        Object o; 
        String tst = "TestClass"; 
        System.out.println("This program will use SimpleClassLoader."); 
             if (args.length != 0) 
                 tst = args[0]; 
             try { 
                 o = (sc.loadClass(tst)).newInstance(); 
                ((LocalModule) o).start("none"); 
             } catch (Exception e) { 
                 System.out.println("Caught exception : "+e); 
             } 
        } 
} 


This simple application first creates a new instance of SimpleClassLoader and then uses it to load the class named TestClass (which is shown above). When the class is loaded, the newInstance() method (defined in class Class) is invoked to generate a new instance of the TestClass object; of course, we don't know it's a TestClass. However, our application has been designed to accept only classes that implement the LocalModule interface as valid loadable classes. If the class loaded did not implement the LocalModule interface, the cast in line #12 will throw a ClassCastException. If the cast does succeed then we invoke the expected start() method and pass it an option string of "none." 

Winding down, wrapping up

With this introduction you should have enough information to build an application with its own custom class loader. Feel free to base any code you wish on the code in this article (for commercial or non-commercial purposes).

Class loaders provide the mechanism that allows Java applications, whether they are Web browsers or EMACs replacements, to be dynamically extended in a controlled way with additional Java code. The applications of class loaders are bounded only by your imagination. Some interesting experiments for you to run if you download and compile the code.
  • Try creating two instances of SimpleClassLoader and see what programs loaded by separate class loaders can, and cannot, do to or with each other.
  • Think of how you might be able to implement class identity checks with a class loader.
  • Try writing a text editor where every key is bound to a dynamically loaded Java class, then send me a copy. :-)


Next month I think I'll focus a bit on application development in Java, building something a bit more significant than spinning pictures or tumbling mascots.

About the author

Chuck McManis is currently the director of system software at FreeGate Corp. FreeGate is a venture-funded start-up that is exploring opportunities in the Internet marketplace. Before joining FreeGate, McManis was a member of the Java group. He joined the Java group just after the formation of FirstPerson Inc. and was a member of the portable OS group (the group responsible for the OS portion of Java). Later, when FirstPerson was dissolved, he stayed with the group through the development of the alpha and beta versions of the Java platform. He created the first "all Java" home page on the Internet when he did the programming for the Java version of the Sun home page in May 1995. He also developed a cryptographic library for Java and versions of the Java class loader that could screen classes based on digital signatures. Before joining FirstPerson, Chuck worked in the operating systems area of SunSoft developing networking applications, where he did the initial design of NIS+.

Digital Signature in java

The basic idea in the use of digital signatures is as follows.

  1. You "sign" the document or code using one of your private keys, which you can generate by using keytool or security API methods. That is, you generate a digital signature for the document or code, using the jarsigner tool or Security API methods.
  2. You send your signed document to your recipient.
  3. You also supply your recipient with your public key. This public key corresponds to the private key you originally used to generate the signature.
  4. Your recipient uses your public key to verify that your document came from you and was not modified before it reached him/her.
A recipient needs to ensure that your public key itself is authentic before he/she can use it to verify that your signature is authentic. Therefore, you will usually supply a certificate that contains your public key together with the key of a Certificate Authority who can vouch for your key's authenticity. See the next section for details.

Generating and Verifying Signatures
This lesson walks you through the steps necessary to use the JDK Security API to generate a digital signature for data and to verify that a signature is authentic. This lesson is meant for developers who wish to incorporate security functionality into their programs, including cryptography services.
This lesson demonstrates the use of the JDK Security API with respect to signing documents. The lesson shows what one program, executed by the person who has the original document, would do to generate keys, generate a digital signature for the document using the private key, and export the public key and the signature to files.
Then it shows an example of another program, executed by the receiver of the document, signature, and public key. It shows how the program could import the public key and verify the authenticity of the signature. The lesson also discusses and demonstrates possible alternative approaches and methods of supplying and importing keys, including in certificates.
For further information about the concepts and terminology (digital signatures, certificates, keystores), see the API and Tools Use for Secure Code and File Exchanges lesson.
In this lesson you create two basic applications, one for the digital signature generation and the other for the verification. This is followed by a discussion and demonstration of potential enhancements. The lesson contains three sections.
  • Generating a Digital Signature shows using the API to generate keys and a digital signature for data using the private key and to export the public key and the signature to files. The application gets the data file name from the command line.
  • Verifying a Digital Signature shows using the API to import a public key and a signature that is alleged to be the signature of a specified data file and to verify the authenticity of the signature. The data, public key, and signature file names are specified on the command line.
  • Weaknesses and Alternatives discusses potential weaknesses of the approach used by the basic programs. It then presents and demonstrates possible alternative approaches and methods of supplying and importing keys, including the use of files containing encoded key bytes and the use of certificates containing public keys.
 Generating a Digital Signature
  • The GenSig program you are about to create will use the JDK Security API to generate keys and a digital signature for data using the private key and to export the public key and the signature to files. The application gets the data file name from the command line.
    The following steps create the GenSig sample program.
    1. Prepare Initial Program Structure Create a text file named GenSig.java. Type in the initial program structure (import statements, class name, main method, and so on).
    2. Generate Public and Private Keys Generate a key pair (public key and private key). The private key is needed for signing the data. The public key will be used by the VerSig program for verifying the signature.
    3. Sign the Data Get a Signature object and initialize it for signing. Supply it with the data to be signed, and generate the signature.
    4. Save the Signature and the Public Key in Files Save the signature bytes in one file and the public key bytes in another.
    5. Compile and Run the Program
Prepare Initial Program Structure
Here's the basic structure of the GenSig program. Place it in a file called GenSig.java.
import java.io.*;
import java.security.*;

class GenSig {

    public static void main(String[] args) {

        /* Generate a DSA signature */

        if (args.length != 1) {
            System.out.println("Usage: GenSig nameOfFileToSign");
            }
        else try {

        // the rest of the code goes here

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }
    }

}

Notes:
  • The methods for signing data are in the java.security package, so the program imports everything from that package. The program also imports the java.io package, which contains the methods needed to input the file data to be signed.
  • A single argument is expected, specifying the data file to be signed.
  • The code written in subsequent steps will go between the try and the catch blocks.

Generate Public and Private Keys
In order to be able to create a digital signature, you need a private key. (Its corresponding public key will be needed in order to verify the authenticity of the signature.)
In some cases the key pair (private key and corresponding public key) are already available in files. In that case the program can import and use the private key for signing, as shown in Weaknesses and Alternatives.
In other cases the program needs to generate the key pair. A key pair is generated by using the KeyPairGenerator class.
In this example you will generate a public/private key pair for the Digital Signature Algorithm (DSA). You will generate keys with a 1024-bit length.
Generating a key pair requires several steps:
Create a Key Pair Generator
The first step is to get a key-pair generator object for generating keys for the DSA signature algorithm.
As with all engine classes, the way to get a KeyPairGenerator object for a particular type of algorithm is to call the getInstance static factory method on the KeyPairGenerator class. This method has two forms, both of which hava a String algorithm first argument; one form also has a String provider second argument.
A caller may thus optionally specify the name of a provider, which will guarantee that the implementation of the algorithm requested is from the named provider. The sample code of this lesson always specifies the default SUN provider built into the JDK.
Put the following statement after the
else try {
line in the file created in the previous step, Prepare Initial Program Structure:
KeyPairGenerator keyGen =
    KeyPairGenerator.getInstance("DSA", "SUN");
Initialize the Key-Pair Generator
The next step is to initialize the key-pair generator. All key-pair generators share the concepts of a keysize and a source of randomness. The KeyPairGenerator class has an initialize method that takes these two types of arguments.
The keysize for a DSA key generator is the key length (in bits), which you will set to 1024.
The source of randomness must be an instance of the SecureRandom class. This example requests one that uses the SHA1PRNG pseudo-random-number generation algorithm, as provided by the built-in SUN provider. The example then passes this SecureRandom instance to the key-pair generator initialization method.
SecureRandom random =
    SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
Note: The SecureRandom implementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to the getInstance method with a call to the setSeed method. So if you had a specific seed value that you wanted used, you would call the following prior to the initialize call:
random.setSeed(seed);
Generate the Pair of Keys
 
The final step is to generate the key pair and to store the keys in PrivateKey and PublicKey objects.
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
In order to be able to create a digital signature, you need a private key. (Its corresponding public key will be needed in order to verify the authenticity of the signature.)
In some cases the key pair (private key and corresponding public key) are already available in files. In that case the program can import and use the private key for signing, as shown in Weaknesses and Alternatives.
In other cases the program needs to generate the key pair. A key pair is generated by using the KeyPairGenerator class.
In this example you will generate a public/private key pair for the Digital Signature Algorithm (DSA). You will generate keys with a 1024-bit length.
Generating a key pair requires several steps: 

Create a Key Pair Generator
The first step is to get a key-pair generator object for generating keys for the DSA signature algorithm.
As with all engine classes, the way to get a KeyPairGenerator object for a particular type of algorithm is to call the getInstance static factory method on the KeyPairGenerator class. This method has two forms, both of which hava a String algorithm first argument; one form also has a String provider second argument.
A caller may thus optionally specify the name of a provider, which will guarantee that the implementation of the algorithm requested is from the named provider. The sample code of this lesson always specifies the default SUN provider built into the JDK.
Put the following statement after the
else try {
line in the file created in the previous step, Prepare Initial Program Structure:
KeyPairGenerator keyGen =
    KeyPairGenerator.getInstance("DSA", "SUN");
Initialize the Key-Pair Generator
The next step is to initialize the key-pair generator. All key-pair generators share the concepts of a keysize and a source of randomness. The KeyPairGenerator class has an initialize method that takes these two types of arguments.
The keysize for a DSA key generator is the key length (in bits), which you will set to 1024.
The source of randomness must be an instance of the SecureRandom class. This example requests one that uses the SHA1PRNG pseudo-random-number generation algorithm, as provided by the built-in SUN provider. The example then passes this SecureRandom instance to the key-pair generator initialization method.
SecureRandom random =
    SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
Note: The SecureRandom implementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to the getInstance method with a call to the setSeed method. So if you had a specific seed value that you wanted used, you would call the following prior to the initialize call:
random.setSeed(seed);
Generate the Pair of Keys
The final step is to generate the key pair and to store the keys in PrivateKey and PublicKey objects.
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();

Sign the Data
Now that you have created a public key and a private key, you are ready to sign the data. In this example you will sign the data contained in a file. GenSig gets the file name from the command line. A digital signature is created (or verified) using an instance of the Signature class.
Signing data, generating a digital signature for that data, is done with the following steps.
Get a Signature Object:
The following gets a Signature object for generating or verifying signatures using the DSA algorithm, the same algorithm for which the program generated keys in the previous step, Generate Public and Private Keys.
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN"); 
Note: When specifying the signature algorithm name, you should also include the name of the message digest algorithm used by the signature algorithm. SHA1withDSA is a way of specifying the DSA signature algorithm, using the SHA-1 message digest algorithm.
Initialize the Signature Object
Before a Signature object can be used for signing or verifying, it must be initialized. The initialization method for signing requires a private key. Use the private key placed into the PrivateKey object named priv in the previous step.
dsa.initSign(priv);
Supply the Signature Object the Data to Be Signed
This program will use the data from the file whose name is specified as the first (and only) command line argument. The program will read in the data a buffer at a time and will supply it to the Signature object by calling the update method.
FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len = bufin.read(buffer)) >= 0) {
    dsa.update(buffer, 0, len);
};
bufin.close();
Generate the Signature
Once all of the data has been supplied to the Signature object, you can generate the digital signature of that data.
byte[] realSig = dsa.sign();
Save the Signature and the Public Key in Files
Now that you have generated a signature for some data, you need to save the signature bytes in one file and the public key bytes in another so you can send (via modem, floppy, mail, and so on) someone else
  • the data for which the signature was generated,
  • the signature, and
  • the public key
The receiver can verify that the data came from you and was not modified in transit by running the VerSig program you will generate in the upcoming Verifying a Digital Signature steps. That program uses the public key to verify that the signature received is the true signature for the data received. Recall that the signature was placed in a byte array named realSig. You can save the signature bytes in a file named sig via the following.
/* save the signature in a file */
        FileOutputStream sigfos = new FileOutputStream("sig");
        sigfos.write(realSig);
        sigfos.close();
Recall from the Generate Public and Private Keys step that the public key was placed in a PublicKey object named pub. You can get the encoded key bytes by calling the getEncoded method and then store the encoded bytes in a file. You can name the file whatever you want. If, for example, your name is Susan, you might name it something like suepk (for "Sue's public key"), as in the following:
/* save the public key in a file */
        byte[] key = pub.getEncoded();
        FileOutputStream keyfos = new FileOutputStream("suepk");
        keyfos.write(key);
        keyfos.close();
Compile and Run the Program
Here is the complete source code for the GenSig.java program, with some comments added. Compile and run it. Remember, you need to specify the name of a file to be signed, as in
java GenSig data
You can download and use this sample file named data or any other file you like. The file will not be modified. It will be read so that a signature can be generated for it.
After executing the program, you should see the saved suepk (public key) and sig (signature) files.

Verifying a Digital Signature
If you have data for which a digital signature was generated, you can verify the authenticity of the signature. To do so, you need
  • the data
  • the signature
  • the public key corresponding to the private key used to sign the data
In this example you write a VerSig program to verify the signature generated by the GenSig program. This demonstrates the steps required to verify the authenticity of an alleged signature.
VerSig imports a public key and a signature that is alleged to be the signature of a specified data file and then verifies the authenticity of the signature. The public key, signature, and data file names are specified on the command line.
The steps to create the VerSig sample program to import the files and to verify the signature are the following.
  1. Prepare Initial Program Structure Create a text file named VerSig.java. Type in the initial program structure (import statements, class name, main method, and so on).
  2. Input and Convert the Encoded Public Key Bytes Import the encoded public key bytes from the file specified as the first command line argument and convert them to a PublicKey.
  3. Input the Signature Bytes Input the signature bytes from the file specified as the second command line argument.
  4. Verify the Signature Get a Signature object and initialize it with the public key for verifying the signature. Supply it with the data whose signature is to be verified (from the file specified as the third command line argument), and verify the signature.
  5. Compile and Run the Program


Sunday, May 16, 2010

Computer network

A computer network, often simply referred to as a network, is a collection of computers and devices connected by communications channels that facilitates communications among users and allows users to share resources with other users. Networks may be classified according to a wide variety of characteristics. This article provides a general overview of types and categories and also presents the basic components of a network.
  • Network classification
    •  Connection method
    •  Wired technologies
    •  Wireless technologies
    •  Scale
    •  Functional relationship (network architecture)
    •  Network topology
  •  Types of networks
    • Personal area network
    •  Local area network
      •  Home area network
    •  Campus network
    •  Wide area network
    •  Global area network
    •  Enterprise Private Network
    •  Virtual private network
    •  Internetwork
      •  Internet
      •  Intranets and extranets
      •  Overlay Network
  •  Basic hardware components
    •  Network interface cards
    •  Repeaters
    •  Hubs
    •  Bridges
    •  Switches
    •  Routers

Sunday, May 2, 2010

JDBC

What Is JDBC?

Working with leaders in the database field, JavaSoft developed a single API for database access--JDBC. As part of this process, they kept three main goals in mind:

* JDBC should be an SQL-level API.

* JDBC should capitalize on the experience of existing database APIs.

* JDBC should be simple.

An SQL-level API means that JDBC allows us to construct SQL statements and embed them inside Java API calls. In short, you are basically using SQL. But JDBC lets you smoothly translate between the world of the database and the world of the Java application. Your results from the database, for instance, are returned as Java variables, and access problems get thrown as exceptions. Later on in the book, we go a step further and talk about how we can completely hide the existence of the database from a Java application using a database class library.

Because of the confusion caused by the proliferation of proprietary database access APIs, the idea of a universal database access API to solve this problem is not a new one. In fact, JavaSoft drew upon the successful aspects of one such API, Open DataBase Connectivity (ODBC). ODBC was developed to create a single standard for database access in the Windows environment. Although the industry has accepted ODBC as the primary means of talking to databases in Windows, it does not translate well into the Java world. First of all, ODBC is a C API that requires intermediate APIs for other languages. But even for C developers, ODBC has suffered from an overly complex design that has made its transition outside of the controlled Windows environment a failure. ODBC's complexity arises from the fact that complex, uncommon tasks are wrapped up in the API with its simpler and more common functionality. In other words, in order for you to understand a little of ODBC, you have to understand a lot.

In addition to ODBC, JDBC is heavily influenced by existing database programming APIs such as X/OPEN SQL Call Level Interface. JavaSoft wanted to re-use the key abstractions from these APIs, which would ease acceptance by database vendors and capitalize on the existing knowledge capital of ODBC and SQL CLI developers. In addition, JavaSoft also realized that deriving an API from existing ones can provide quick development of solutions for database engines that support the old protocols. Specifically, JavaSoft worked in parallel with Intersolv to create an ODBC bridge that maps JDBC calls to ODBC calls, thus giving Java applications access to any database management system (DBMS) that supports ODBC.

JDBC attempts to remain as simple as possible while providing developers with maximum flexibility. A key criterion employed by JavaSoft is simply asking whether database access applications read well. The simple and common tasks use simple interfaces, while more uncommon or bizarre tasks are enabled through extra interfaces. For example, three interfaces handle a vast majority of database access. JDBC nevertheless provides several other interfaces for handling more complex and unusual tasks.
The Structure of JDBC

JDBC accomplishes its goals through a set of Java interfaces, each implemented differently by individual vendors. The set of classes that implement the JDBC interfaces for a particular database engine is called a JDBC driver. In building a database application, you do not have to think about the implementation of these underlying classes at all; the whole point of JDBC is to hide the specifics of each database and let you worry about just your application. Figure 4-1 shows the JDBC classes and interfaces.
Figure 4-1. The classes and interfaces of java.sql, the JDBC API package



If you think about a database query for any database engine, it requires you to connect to the database, issue your SELECT statement, and process the result set. In Example 4-1, we have the full code listing for a simple SELECT application from the Imaginary JDBC Driver for mSQL.[1] I wrote this driver for the Center for Imaginary Environments (http://www.imaginary.com), which is a non-commercial organization that promotes the development of virtual environment technologies like muds. This application is a single class that gets all of the rows from a table in an mSQL database located on my Sun box. First, it connects to the database by getting a database connection under my user id, borg, from the JDBC DriverManager class. It uses that database connection to create a Statement object that performs the SELECT query. A ResultSet object then provides the application with the key and val fields from the t_test table.

Example: A Simple SELECT Application from the Imaginary JDBC Implementation for mSQL

import java.sql.*;

public class SelectApp {
public static void main(String args[]) {
String url = "jdbc:msql://athens.imaginary.com:4333/db_web";

try {
Class.forName("imaginary.sql.iMsqlDriver");
}
catch( Exception e ) {
System.out.println("Failed to load mSQL driver.");
return;
}
try {
Connection con = DriverManager.getConnection(url, "borg", "");
Statement select = con.createStatement();
ResultSet result = select.executeQuery
("SELECT key, val FROM t_test");

System.out.println("Got results:");
while(result.next()) { // process results one row at a time
int key = result.getInt(1);
String val = result.getString(2);

System.out.println("key = " + key);
System.out.println("val = " + val);
}
select.close();
con.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}

If you already have Java experience, then you should be able to understand the flow of the code in Example 4-1 without knowing any JDBC. There are no references to specific database engine classes. Instead, the code simply uses JDBC interfaces to provide a facade for the DBMS-specific implementation. The JDBC implementation, in turn, performs the actual database access somewhere behind the scenes.

In this simple application, the SelectApp class asks the JDBC DriverManager to hand it the proper database implementation based on a database URL. The database URL looks similar to other Internet URLs. The actual content of the URL is loosely specified as jdbc:subprotocol:subname. The subprotocol identifies which driver to use, and the subname provides the driver with any required connection information. For the Imaginary JDBC Implementation for mSQL that I used in testing the above example, the URL is jdbc:msql://athens.imaginary.com:4333/db_web. In other words, this URL says to use the mSQL JDBC driver to connect to the database db_web on the server running at port 4333 on athens.imaginary.com. Each URL, however, is specific to the JDBC implementation being sought, and so I can't say anything more explicit about it. Whatever its format, the primary function of a database URL is to uniquely identify the implementation needed by the application and pass that implementation any information it needs in order to connect to the proper database.

Databases and Drivers
In putting together the examples in this book, I used both an mSQL database for the simple Chapter 4 examples and an Oracle database for the more complex examples of Chapter 5. If you do not have a corporate pocketbook to back up your database purchase, mSQL is probably the most feasible solution. You should keep in mind, however, that mSQL does not allow you to abort transactions and does not support the stored procedures used in Chapter 5. Whatever your database choice, you must set up your database engine, create a database, and create the tables shown in the Chapter 3 data model before you can begin writing JDBC code.

Once your database engine is installed and your database is all set up, you will need a JDBC driver for that database engine. You can find an mSQL JDBC driver at http://www.imaginary.com/Java. The more commercial database engines like Oracle have commercial JDBC drivers. Most of them, however, allow you to have a free trial period for experimenting with the driver. Follow the install instructions for the driver you choose, and remember that some JDBC drivers require to you install native code on client machines. To help you understand what different drivers require, JavaSoft has defined the following driver categorization system:

type 1
These drivers use a bridging technology to access a database. The JDBC-ODBC bridge that comes with the JDK 1.1 is a good example of this kind of driver. It provides a gateway to the ODBC API. Implementations of that API in turn do the actual database access. Bridge solutions generally require software to be installed on client systems, meaning that they are not good solutions for applications that do not allow you to install software on the client.

type 2
The type 2 drivers are native API drivers. This means that the driver contains Java code that calls native C or C++ methods provided by the individual database vendors that perform the database access. Again, this solution requires software on the client system.

type 3
Type 3 drivers provide a client with a generic network API that is then translated into database specific access at the server level. In other words, the JDBC driver on the client uses sockets to call a middleware application on the server that translates the client requests into an API specific to the desired driver. As it turns out, this kind of driver is extremely flexible since it requires no code installed on the client and a single driver can actually provide access to multiple databases.

type 4
Using network protocols built into the database engine, type 4 drivers talk directly to the database using Java sockets. This is the most direct pure Java solution. In nearly every case, this type of driver will come only from the database vendor.