Saturday 22 September 2012

The if-then and if-then-else Statements


The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:
void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){ 
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
void applyBrakes() {
    // same as above, but without braces 
    if (isMoving)
        currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in theapplyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
    if (isMoving) {
        currentSpeed--;
    } else {
        System.err.println("The bicycle has " + "already stopped!");
    } 
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}
The output from the program is:
    Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

Monday 17 September 2012

What is a class in JAVA


In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

    void changeCadence(int newValue) {
         cadence = newValue;
    }
    void changeGear(int newValue) {
         gear = newValue;
    }
    void speedUp(int increment) {
         speed = speed + increment;   
    }
    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }
    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fieldscadencespeed, and gear represent the object's state, and the methods (changeCadencechangeGearspeedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
class BicycleDemo {
    public static void main(String[] args) {

        // Create two different 
        // Bicycle objects
        Bicycle bike1 = new Bicycle();
        Bicycle bike2 = new Bicycle();

        // Invoke methods on 
        // those objects
        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        bike2.printStates();
    }
}

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:

Source:http://docs.oracle.com

Thursday 13 September 2012

Video buffering


A buffer contains data that is stored for a short amount of time, typically in the computer's memory (RAM). The purpose of a buffer is to hold data right before it is used. For example, when you download an audio or video file(watching youtube video) from the Internet, it may load the first 20% of it into a buffer and then begin to play. While the clip plays back, the computer continually downloads the rest of the clip and stores it in the buffer. Because the clip is being played from the buffer, not directly from the Internet, there is less of a chance that the audio or video will stall or skip when there is network congestion.
Buffering is used to improve several other areas of computer performance as well. Most hard disks use a buffer to enable more efficient access to the data on the disk. Video cards send images to a buffer before they are displayed on the screen (known as a screen buffer). Computer programs use buffers to store data while they are running. If it were not for buffers, computers would run a lot less efficiently and we would be waiting around a lot more.

Hacking(not cracking)



Watch a Chinese military hacker launch a successful attack




Download free software using Pirate Bay
https://thepiratebay.se

Download Torrents safely using torch browser

http://www.torchbrowser.com/

Anonymity online

Internet Addressing with Java etc.


There are several communications mechanisms that we can use to provide network services. We could use UDP (unreliable datagram protocol), or TCP (transfer-control protocol). For the purposes of this tutorial, we'll choose TCP, because it makes life much easier. TCP guarantees that messages will arrive at their destination. UDP is unreliable, and your application isn't notified if the message is lost in transit. Also, many protocols (such as HTTP, SMTP, POP & FTP) use TCP, so it's important that you are familiar with it for networking in Java.

Internet Addressing with Java

Handling internet addresses (domain names, and IP addresses) is made easy with Java. Internet addresses are represented in Java by the InetAddress class. InetAddress provides simple methods to convert between domain names, and numbered addresses.
We start by importing the java.net package, which contains a set of pre-written networking routines (including InetAddress).
import java.net.*;
Next, we declare a new variable of type InetAddress, which we assign the value of the local host machine (for machines not connected to a network, this should represent 127.0.0.1). Due to the fact that InetAddresses can generate exceptions, we must place this code between a try .. catch UnknownHostException block.
// Obtain the InetAddress of the computer on which this program is running
InetAddress localaddr = InetAddress.getLocalHost();
The InetAddress class has methods that return the IP address as an array of bytes (which can be easily converted into a string), as well as a string representation of its domain name (e.g. mydomain.org ). We can print out the InternetAddress, as well as the domain name of the local address.
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostName());
public class MyFirstInternetAddress
{
 public static void main(String args[])
 {
  try
  {
   InetAddress localaddr = InetAddress.getLocalHost();
   
   System.out.println ("Local IP Address : " + localaddr );
   System.out.println ("Local hostname   : " + localaddr.getHostName());
  }
  catch (UnknownHostException e)
  {
   System.err.println ("Can't detect localhost : " + e);
  }
  
 }

 /** Converts a byte_array of octets into a string */
 public static String byteToStr( byte[] byte_arr )
 {
  StringBuffer internal_buffer = new StringBuffer();

  // Keep looping, and adding octets to the IP Address
  for (int index = 0; index < byte_arr.length -1; index++)
  {
   internal_buffer.append ( String.valueOf(byte_arr[index]) + ".");
  }
  
  // Add the final octet, but no trailing '.'
  internal_buffer.append ( String.valueOf (byte_arr.length) );

  return internal_buffer.toString();
 }
}
Compile and run this application, and you should be told your local IP address, and hostname. Don't worry if your computer isn't connected to the Internet, though. Providing your system has a TCP stack, it should give you back an IP address even if you aren't currently connected. On most systems, you can refer to your local machine (which often has the hostname "localhost") as IP address 127.0.0.1
Why would every machine that's not connected to the Internet have the same address? This address is known as a loopback address. Every time you connect to this address, you're actually connected to your local machine. So, if you were running a local webserver, and you pointed your browser to http://127.0.0.1, you should see your web-site. But if I were to go to the same address, I'd connect to a different site - that of my own machine.
This is great when developing Java applications. You don't need a permanent connection to the Internet - you can run client and server applications on your own machine. This is handy, because writing and testing client/server applications can take some time, and unless you have a permanant connection, you wouldn't want to be billed on an hourly rate by your ISP!

Writing a TCP client in Java

Writing network client in Java is very simple. If you've ever written a network client in C, you'll know how complicated it can be. You have to be concerned with structures, and pointers. Java cuts out this complexity, through its java.net.Socket class. To demonstrate just how easy Java makes it, I'm going to show you how to write a finger client.
For those who are unfamiliar with the finger protocol, I'll briefly explain how it works. Finger allows a remote user to query a host machine for information, either about the host machine in general or a specific user. Most unix systems support finger, and many non-Unix systems also support the protocol. Most finger applications take as a paramater 'username@hostmachine'.
Finger clients connect to a host server at port 79 and establish a TCP stream. The client sends the username (or a blank, for a general query), followed by a newline character. The server then sends back information about the user, in the form of a text stream. This should be displayed to the user, and then the connection should be terminated.
As with any networking application in Java, we need to first import the network and input/output packages.
import java.io.*;
import java.net.*;
Our application should have a single method, main, which is responsible for issuing a finger query. The first step is to validate and parse the command line paramaters, looking for a username and hostname.
public static void main ( String args[] )
{
 // Check command line paramaters
 if (args.length != 1)
 {
  System.err.println ("Invalid paramaters");
  System.exit(1);
 }
 else
 // Check for existence of @ in paramater
 if (args[0].indexOf("@") == -1)
 {
  System.err.println ("Invalid paramater : syntax user@host");
  System.exit(1);
 }

 // Split command line paramater at the @ character
 String username = args[0].substring(0, args[0].indexOf("@") );
 String hostname = args[0].substring(args[0].indexOf("@") +1, args[0].length());

 ........
}
In the code above, we check that only a single paramater has been entered, and also that there exists an '@' character in the paramater. The next step is to split the command line paramater into a username and a hostname. To do this, we rely on the substring method which can be applied to any string. Username becomes the string from offset 0, to the first index of character '@'. Hostname becomes the string from the first index of character '@', to the length of the original paramater.
Figure 2.0 - Extracting username & hostname from command-line parameter
The next step is to connect to the finger server, which opperates on port 79. As with the previous example, we must enclose our network code inside of a try { ... } catch block. This allows us to trap any network errors that may occur (such as invalid hostnames, or an inability to connect with the server). You'll notice that the code to create a TCP collection is actually only a single line - networking in Java is very easy.
try
{
 // Create a connection to server
 Socket s = new Socket(hostname, 79);

 // Remainder of finger client code goes here
 .........

}
catch (SocketException e )
{
 System.err.println ("Socket error : " + e);
}
catch (UnknownHostException e )
{
 System.err.println ("Invalid host!");
}
catch (IOException e )
{
 System.err.println ("I/O error : " + e);
}
After connecting to port 79 of the finger server, we now have to obtain input and output streams for the socket. We can treat these streams then just as we would file or text input and output. For ease of use we'll covert the input stream into a DataInputStream, and the output stream into a PrintStream. This will allow us to use the readLine and println methods with our socket streams.
// Create input and output streams to socket
PrintStream out = new PrintStream( s.getOutputStream()) ;
DataInputStream in = new DataInputStream(s.getInputStream());
Using our PrintStream out, we write the name of the user we wish to find out information about to the finger server. The server will process the query, and output a result, which we will print to the user's screen.
// Write username to socket output
out.println( username );

// Read response from socket
System.out.println ( in.readLine() );

// Read remaining finger response
String line = in.readLine();

while (line != null)
{
 System.out.println ( line );

 // Read next line
 line = in.readLine();
}
The first line is read from the input stream, and then printed to screen. We then enter a loop, checking to see if there are any more lines to display. The while loop terminates when there are no more bytes available.
Finally, we must close the connection to our finger server. With this last statement, our finger client is complete!
// Terminate connection
s.close();
While the example program functions as a finger client, it can easily be used as a TCP client skeleton, substituting the connection to port 79 with another port matching the application protocol you are trying to use, and modifying the read/write routines to send different data.

Running the example client

To run the client, you'll need to be connected to the Internet (this example requires a direct connection, and won't run behind a firewall). To execute, you need to know the name of a user, and the site on which the user resides. For example, to finger dodo@fan.net.au, you would do the following
java TCP_Finger_Client dodo@fan.net.au

Tip - Not all ISP's run finger servers, so you won't be able to finger every user. The example above should work, however (providing my ISP doesn't change its policy).

Summary

Writing network applications in Java is extremely easy. Java takes away much of the implementation details which are operating system specific. There's no need to worry about hostname lookups, size of IP address structures, or pointers. The java.net package provides all this functionality for you, and provides a simple way to write networking clients. However, when writing Java applets (as opposed to applications), remember that the browser may impose security restrictions - many applets can only communicate with the host from which they were downloaded from.

Additional Resources

Merlin Hughes, et al. Java Network Programming, Manning Publications, 1997.
Reilly, D. Java Network Programming FAQ (online) available at http://www.davidreilly.com/java/java_network_programming/

OSI Reference model


OSI Model
Data unitLayerFunction
Host
layers
Data7. ApplicationNetwork process to application
6. PresentationData representation, encryption and decryption, convert machine dependent data to machine independent data
5. SessionInterhost communication, managing sessions between applications
Segments4. TransportEnd-to-end connections, reliability and flow control
Media
layers
Packet/Datagram3. NetworkPath determination and logical addressing
Frame2. Data linkPhysical addressing
Bit1. PhysicalMedia, signal and binary transmission

Variables in JAVA


Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.
int myInt;         /* Declaring an uninitialized variable called 'myInt',
                   of type 'int' */
myInt = 35;       // Initializing the variable
int myInt = 35;   // Declaring and initializing the variable at the same time
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
int a, b;         // Declaring multiple variable of the same type
 
int a = 2, b = 3; // Declaring and initializing multiple variables of the same type

Distributed programming and CORBA

What is CORBA?

CORBA, or Common Object Request Broker Architecture, is a standard architecture for distributed object systems. It allows a distributed, heterogeneous collection of objects to interoperate.

The OMG

The Object Management Group (OMG) is responsible for defining CORBA. The OMG comprises over 700 companies and organizations, including almost all the major vendors and developers of distributed object technology, including platform, database, and application vendors as well as software tool and corporate developers.

CORBA Architecture

CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.
The services that an object provides are given by its interface. Interfaces are defined in OMG's Interface Definition Language (IDL). Distributed objects are identified by object references, which are typed by IDL interfaces.
The figure below graphically depicts a request. A client holds an object reference to a distributed object. The object reference is typed by an interface. In the figure below the object reference is typed by the Rabbit interface. The Object Request Broker, or ORB, delivers the request to the object and returns any results to the client. In the figure, a jump request returns an object reference typed by the AnotherObject interface.


Arrays in Java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the mainmethod of the "Hello World!" application. This section discusses arrays in greater detail.


An array of ten elements


class ArrayDemo {
public static void main (String[ ] args){
//declares an array of integers
Int [ ] anArray;
//allocates memory for 3 integers
anArray = new int[10];
//initialize first element
anArray[0] = 100;
//etc.
anArray[1] = 200;
anArray[2] = 300;

System.out.println(“Element at index 0: ” + anArray[0]);
System.out.println(“Element at index 1: ” + anArray[1]);
System.out.println(“Element at index 2: ” + anArray[2]);              
}   
}

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300

Windows Server

Adding a client to a Windows Server



For a step by step tutorial about Windows Server 2003 visit http://www.visualwin.com/.All rights belongs to the owner of the website.

Networking with Java


There are several communications mechanisms that we can use to provide network services. We could use UDP (unreliable datagram protocol), or TCP (transfer-control protocol). For the purposes of this tutorial, we'll choose TCP, because it makes life much easier. TCP guarantees that messages will arrive at their destination. UDP is unreliable, and your application isn't notified if the message is lost in transit. Also, many protocols (such as HTTP, SMTP, POP & FTP) use TCP, so it's important that you are familiar with it for networking in Java.

Internet Addressing with Java

Handling internet addresses (domain names, and IP addresses) is made easy with Java. Internet addresses are represented in Java by the InetAddress class. InetAddress provides simple methods to convert between domain names, and numbered addresses.
We start by importing the java.net package, which contains a set of pre-written networking routines (including InetAddress).
import java.net.*;
Next, we declare a new variable of type InetAddress, which we assign the value of the local host machine (for machines not connected to a network, this should represent 127.0.0.1). Due to the fact that InetAddresses can generate exceptions, we must place this code between a try .. catch UnknownHostException block.
// Obtain the InetAddress of the computer on which this program is running
InetAddress localaddr = InetAddress.getLocalHost();
The InetAddress class has methods that return the IP address as an array of bytes (which can be easily converted into a string), as well as a string representation of its domain name (e.g. mydomain.org ). We can print out the InternetAddress, as well as the domain name of the local address.
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostName());

Networking with Java


How do computers talk to each other via the Internet?

The Internet is composed of millions of computers, located all across the globe, communicating and transmitting information over a variety of computing systems, platforms, and networking equipment.  Each of these computers (unless they are connecting via an intranet) will have a unique IP address.
IP addresses are 32-bit numbers, containing four octets (8 bit numbers) separated by a full stop. Each computer with a direct internet connection will have a unique IP address, (e.g. 207.68.156.61). Some computers have temporary addresses, such as when you connect to your ISP through a modem. Others have permanent addresses, and some even have their own unique domain names (e.g.www.microsoft.com).
An IP address allows us to uniquely identify a device or system connected to the Internet. If I wanted to connect to a specific IP address, and send a message, I could do so. Without an IP address, my message would have no way of reaching its destination - a bit like leaving the address off a letter or parcel.
Often, computers connected to the Internet provide services. This page is provided by a web server, for example. Because computers are capable of providing more than one type of service, we need a way to uniquely identify each service. Like an IP address, we use a number. We call this number a port. Common services (such as HTTP, FTP, Telnet, SMTP) have well known port numbers. For example, most web servers use port 80. Of course, you can use any port you like - there's no rule that says you must use 80.
diagram
Figure 1.0 - Ports help computers identify which service data is for.