Friday, September 19, 2008
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddressExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
byte[] ip = address.getAddress();
int i = 4;
String ipAddress = "";
for (byte b : ip)
{
ipAddress += (b & 0xFF);
if (--i > 0)
{
ipAddress += ".";
}
}
System.out.println(ipAddress);
} catch (UnknownHostException e)
{
e.printStackTrace();
}
}
}
import java.net.UnknownHostException;
public class IPAddressExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
byte[] ip = address.getAddress();
int i = 4;
String ipAddress = "";
for (byte b : ip)
{
ipAddress += (b & 0xFF);
if (--i > 0)
{
ipAddress += ".";
}
}
System.out.println(ipAddress);
} catch (UnknownHostException e)
{
e.printStackTrace();
}
}
}
Wednesday, September 17, 2008
import java.net.InetAddress;
import java.net.UnknownHostException;
public class HostnameExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println("Hostname: " + address.getHostName());
} catch (UnknownHostException e)
{
e.printStackTrace();
}
}
}
import java.net.UnknownHostException;
public class HostnameExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println("Hostname: " + address.getHostName());
} catch (UnknownHostException e)
{
e.printStackTrace();
}
}
}
Monday, September 15, 2008
Since Java 1.5 (Tiger) the InetAddress class introduces an isReachable() method that can be use to ping or check if the address specified by the InetAddress is reachable.
import java.net.InetAddress;
public class PingExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getByName("172.16.2.0");
// Try to reach the specified address within the timeout
// periode. If during this periode the address cannot be
// reach then the method returns false.
boolean reachable = address.isReachable(10000);
System.out.println("Is host reachable? " + reachable);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
import java.net.InetAddress;
public class PingExample
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getByName("172.16.2.0");
// Try to reach the specified address within the timeout
// periode. If during this periode the address cannot be
// reach then the method returns false.
boolean reachable = address.isReachable(10000);
System.out.println("Is host reachable? " + reachable);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Saturday, September 13, 2008
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo {
public static void main(String[] args) {
try {
//
// Creating a url object by specifing each parameter separately, including
// the protocol, hostname, port number, and the page name
//
URL url = new URL("http", "www.kodejava.org", 80, "/index.html");
//
// We can also specify the address in a single line
//
url = new URL("http://www.kodejava.org:80/index.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDemo {
public static void main(String[] args) {
try {
//
// Creating a url object by specifing each parameter separately, including
// the protocol, hostname, port number, and the page name
//
URL url = new URL("http", "www.kodejava.org", 80, "/index.html");
//
// We can also specify the address in a single line
//
url = new URL("http://www.kodejava.org:80/index.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thursday, September 11, 2008
How do I get response header from HTTP request?
package org.kodejava.example.net;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpResponseHeaderDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.kodejava.org/index.html");
URLConnection connection = url.openConnection();
Map responseMap = connection.getHeaderFields();
for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.print(key + " = ");
List values = (List) responseMap.get(key);
for (int i = 0; i < values.size(); i++) {
Object o = values.get(i);
System.out.print(o + ", ");
}
System.out.println("");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.net;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpResponseHeaderDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.kodejava.org/index.html");
URLConnection connection = url.openConnection();
Map responseMap = connection.getHeaderFields();
for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.print(key + " = ");
List values = (List) responseMap.get(key);
for (int i = 0; i < values.size(); i++) {
Object o = values.get(i);
System.out.print(o + ", ");
}
System.out.println("");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tuesday, September 9, 2008
In this example you'll see how to create a client-server socket communication. The example below consist of two main classes, the ServerSocketExample and the ClientSocketExample. The server application listen to port 7777 at the localhost. When we send a message from the client application the server receive the message and send a reply to the client application.
The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.
package org.kodejava.example.net;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketExample {
private ServerSocket server;
private int port = 7777;
public ServerSocketExample() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSocketExample example = new ServerSocketExample();
example.handleConnection();
}
public void handleConnection() {
System.out.println("Waiting for client message...");
//
// The server do a loop here to accept all connection initiated by the
// client application.
//
while (true) {
try {
Socket socket = server.accept();
new ConnectionHandler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket) {
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run() {
try
{
//
// Read a message sent by client application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//
// Send a response information to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hi...");
ois.close();
oos.close();
socket.close();
System.out.println("Waiting for client message...");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.net;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocketExample {
public static void main(String[] args) {
try {
//
// Create a connection to the server socket on the server application
//
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(), 7777);
//
// Send a message to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hello There...");
//
// Read and display the response message sent by server application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
To test the application you need to start the server application. Each time you run the client application it will send a message "Hello There..." and in turns the server reply with a message "Hi...".
The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.
package org.kodejava.example.net;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketExample {
private ServerSocket server;
private int port = 7777;
public ServerSocketExample() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSocketExample example = new ServerSocketExample();
example.handleConnection();
}
public void handleConnection() {
System.out.println("Waiting for client message...");
//
// The server do a loop here to accept all connection initiated by the
// client application.
//
while (true) {
try {
Socket socket = server.accept();
new ConnectionHandler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket) {
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run() {
try
{
//
// Read a message sent by client application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//
// Send a response information to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hi...");
ois.close();
oos.close();
socket.close();
System.out.println("Waiting for client message...");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.net;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocketExample {
public static void main(String[] args) {
try {
//
// Create a connection to the server socket on the server application
//
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(), 7777);
//
// Send a message to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hello There...");
//
// Read and display the response message sent by server application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
To test the application you need to start the server application. Each time you run the client application it will send a message "Hello There..." and in turns the server reply with a message "Hi...".
Sunday, September 7, 2008
You want to create a program that reada a webpage content from the internet. The example below using the URL class to create a connection to the website. When you get the connection to a website you can read the stream and write the data to a file.
package org.kodejava.example.net;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlReadPageDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.kodejava.org");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.net;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlReadPageDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.kodejava.org");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Previously for obtaining a MAC address we need to use a native code as a solution. In JDK 1.6 a new method is added in the java.net.NetworkInterface class, this method is getHardwareAddress().
package org.kodejava.example.net;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MacAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
package org.kodejava.example.net;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MacAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
Wednesday, September 3, 2008
How to Add Java™ Applets to Your Site
A lot of sites feature Java applets, and if you've been searching through the Java Boutique's applet library, you may have found an applet you'd like to add to your own site. This guide will help you to do just that, and will point out some common problems and tips to simplify the task. You may also want to read Java for the Webmaster and Java On Your Site to find out more about selecting and using the proper applets for your Web site.
The assumption is made that you are able to run Java on your computer system. If you have problems viewing Java applets, you can find help at: http://www.microsoft.com/java/
1. First, select the Java applet you would like to add to your site. Many of the applets are free with some requiring only a link back to the author's site. Others have a link to the author's site written in them which can be removed by paying a registration fee. Still others require a fee before they can be used.
2. Download the zip file to a directory on your computer (make sure you remember the directory where you downloaded it). The zip file contains the necessary files to run the Java applet.
In a few cases, you must download the jar or class files individually. Note that in Netscape Communicator, you must hold down the shift key and then click the link to download the files.
Another alternative would be downloading the .JAVA source code, if it is available, and compiling it using the Java Compiler that is included with the Sun Microsystems Java Developers Kit or this Java Compiler Service.
3. In order to run the applet, it must be loaded by an HTML file. This would be the Web page you want to display the applet on, i.e. your home page. Many times the author has included an example in the zip file. (If the applet comes from the Java Boutique, the HTML source is included on the applet page for you to copy) The code ("HTML source") will look something like the following:
width=300 height=300>
Your browser is not Java enabled.
Note: The term "code" points to the class file, which contains the applet code; "archive" points to the file that contains the class files. You can leave the zip file intact and just point to it i.e. archive="NameOfApplet.zip". Many applets have a "param" listing. This is to list the parameters for the item mentioned, in this case the background color ("bgcolor") and the font color ("fontcolor"). The "value" is the value assigned to the parameter. This information should be contained in the zip file.
4. If the Applet requires image and/or sound files (generally .GIF, .JPG, and .AU files), place them in the appropriate directories as indicated on the applet page.
5. You are now ready to test the applet using a Java-enabled browser.
6. Assuming the applet loaded successfully, you can now move your files to your Web server. These should either all be in the same directory or the HTML source code should point to the directory where the class and/or zip files are, i.e. "CODEBASE=DirectoryNameWhereClassFilesReside".
Upload the HTML file and the image and/or sound files. You will also need to upload all the files that were included in the applet zip file. If some of the files have a "$" in the name — i.e. this$file.class — you may not be able to upload them to the server. In that case, just use the "archive" parameter and point to the zip file: archive="NameOfApplet.zip". The applet will pull the code directly from the zip file.
javaboutique.com
7. Finally, crediting the author of the Applet (as well as the Java Boutique) on your page would probably be a nice finishing touch. Feel free to copy the button to the right or use the following code to incorporate it into your page:
src="http://javaboutique.internet.com/img/javabtq_button.gif">
Troubleshooting
If you see "Applet can't start: class ______ not found" in your browser's status line, it can mean one of two things:
1. The .class file(s) are not named correctly. Java is case-sensitive, so be sure to follow precise capitalization.
2. The .class file(s) are not in the correct directory. They should be located in the path indicated in the CODEBASE= portion of the
A lot of sites feature Java applets, and if you've been searching through the Java Boutique's applet library, you may have found an applet you'd like to add to your own site. This guide will help you to do just that, and will point out some common problems and tips to simplify the task. You may also want to read Java for the Webmaster and Java On Your Site to find out more about selecting and using the proper applets for your Web site.
The assumption is made that you are able to run Java on your computer system. If you have problems viewing Java applets, you can find help at: http://www.microsoft.com/java/
1. First, select the Java applet you would like to add to your site. Many of the applets are free with some requiring only a link back to the author's site. Others have a link to the author's site written in them which can be removed by paying a registration fee. Still others require a fee before they can be used.
2. Download the zip file to a directory on your computer (make sure you remember the directory where you downloaded it). The zip file contains the necessary files to run the Java applet.
In a few cases, you must download the jar or class files individually. Note that in Netscape Communicator, you must hold down the shift key and then click the link to download the files.
Another alternative would be downloading the .JAVA source code, if it is available, and compiling it using the Java Compiler that is included with the Sun Microsystems Java Developers Kit or this Java Compiler Service.
3. In order to run the applet, it must be loaded by an HTML file. This would be the Web page you want to display the applet on, i.e. your home page. Many times the author has included an example in the zip file. (If the applet comes from the Java Boutique, the HTML source is included on the applet page for you to copy) The code ("HTML source") will look something like the following:
width=300 height=300>
Your browser is not Java enabled.
Note: The term "code" points to the class file, which contains the applet code; "archive" points to the file that contains the class files. You can leave the zip file intact and just point to it i.e. archive="NameOfApplet.zip". Many applets have a "param" listing. This is to list the parameters for the item mentioned, in this case the background color ("bgcolor") and the font color ("fontcolor"). The "value" is the value assigned to the parameter. This information should be contained in the zip file.
4. If the Applet requires image and/or sound files (generally .GIF, .JPG, and .AU files), place them in the appropriate directories as indicated on the applet page.
5. You are now ready to test the applet using a Java-enabled browser.
6. Assuming the applet loaded successfully, you can now move your files to your Web server. These should either all be in the same directory or the HTML source code should point to the directory where the class and/or zip files are, i.e. "CODEBASE=DirectoryNameWhereClassFilesReside".
Upload the HTML file and the image and/or sound files. You will also need to upload all the files that were included in the applet zip file. If some of the files have a "$" in the name — i.e. this$file.class — you may not be able to upload them to the server. In that case, just use the "archive" parameter and point to the zip file: archive="NameOfApplet.zip". The applet will pull the code directly from the zip file.
javaboutique.com
7. Finally, crediting the author of the Applet (as well as the Java Boutique) on your page would probably be a nice finishing touch. Feel free to copy the button to the right or use the following code to incorporate it into your page:
Troubleshooting
If you see "Applet can't start: class ______ not found" in your browser's status line, it can mean one of two things:
1. The .class file(s) are not named correctly. Java is case-sensitive, so be sure to follow precise capitalization.
2. The .class file(s) are not in the correct directory. They should be located in the path indicated in the CODEBASE= portion of the
Subscribe to:
Posts (Atom)
SUBSCRIBE VIA eMAIL
Recent Posts
Archives
- December 2008 (5)
- November 2008 (15)
- October 2008 (17)
- September 2008 (9)
- August 2008 (12)
- July 2008 (19)
- June 2008 (22)
- May 2008 (17)
- April 2008 (2)
Categories
- java.sql (19)
- Examples (18)
- INTRODUCTION (9)
- JAVA APPLET (9)
- java.awt (8)
- java.net (8)
- java.beans (7)
- JAVA String Utility (6)
- Arrays (4)
- java.math (3)
- java.util.regex (3)
- Sort (2)
- Swing (2)
- java.security (2)
- java.util.zip (2)
- Catching Exceptions (1)
- Classes and Objects (1)
- Core Java Programs-part 1 (1)
- Core Java Programs-part 2 (1)
- Core Java Programs-part3 (1)
- Criticism of Java programming language (1)
- Falling Letters (1)
- File I/O and Streams (1)
- Fun With Letters and Words (1)
- Get current working directory (1)
- How do I convert String to Date object? (1)
- How do I convert string into InputStream? (1)
- How do i calculate directory size? (1)
- How to make executable jar files in JDK1.3.1? (1)
- Interfaces (1)
- JAVA Date Utility (1)
- Java Arithmetic Operators (1)
- Java Assignment Operators (1)
- Java Boolean Operators (1)
- Java Command Line Arguments (1)
- Java Comments (1)
- Java Conditional Operators (1)
- Java Data and Variables (1)
- Java Hello World Program (1)
- Java If-Else Statement (1)
- Java Increment and Decrement Operators (1)
- Java Loops (while (1)
- Java Relational Operators (1)
- Java Variables and Arithmetic Expressions (1)
- Java Virtual Machine (1)
- Know the current position of cursor (1)
- Letters (1)
- Methods (Includes Recursive Methods) (1)
- Rotating Lines (1)
- Send an email with attachment (1)
- Use for..each in Java (1)
- What is Autoboxing? (1)
- Write text file (1)
- connection to database (1)
- do-while and for loops) (1)

