Tuesday, August 6, 2013

JSF (JavaServer Faces) Tutorial

This article describes how to develop JavaServer Faces web applications with Eclipse WTP JSF tooling. It demonstrates managed beans, validators, external resource bundles and the JSF navigation concept.
This tutorial was developed with Java 1.6, JavaServerFaces 1.2, the Apache MyFaces JSF implementation, Tomcat 6.0 and Eclipse 3.6.

Table of Contents
1. JavaServer Faces - JSF
1.1. What is JSF
1.2. A JSF application
1.3. Value and Method Binding
1.4. Prerequisites to use JSF
1.5. JSF Main features
1.6. JSP and JSF
2. JSF configuration files
2.1. Overview
2.2. web.xml
2.3. faces-config.xml
3. Installation
3.1. Eclipse
3.2. JSF library
3.3. JSLT library
4. Your first JSF project
4.1. Create JSF Project
4.2. Review the generated project
4.3. Domain Model
4.4. Define managed bean
4.5. Create JSP
4.6. Run your webapplication
4.7. Layout via css
5. Your second JSF application
5.1. Create JSF Project
5.2. Domain model
5.3. Register your managed beans
5.4. Validators
5.5. Resource bundle for messages
5.6. JavaServer Page with JSF components
5.7. Navigation Rule
5.8. Run your webapplication
6. JSF application with a controller
6.1. Create JSF Project
6.2. Domain model
6.3. Controller
6.4. Register your managed beans- Dependency injection
6.5. Resource bundle for messages
6.6. JavaServer Page with JSF components
6.7. Run your webapplication
7. A Todo JSF application
7.1. Create JSF Project
7.2. Domain model
7.3. Controller
7.4. Register your managed beans
7.5. Create css
7.6. JavaServer Page with JSF components
7.7. Run your webapplication
8. Thank you
9. Questions and Discussion
10. Links and Literature
10.1. Tutorials and Websites
10.2. JSF component libraries

1. JavaServer Faces - JSF

1.1. What is JSF

JavaServer Faces (JSF) is a UI component based Java Web application framework. JSF is serverbased, e.g. the JSF UI components and their state are represented on the server with a defined life-cycle of the UI components. JSF is part of the Java EE standard.
A JSF application run in a standard web container, for example Tomcat or Jetty.
This articles provides an introduction to JSF using only standard JSF features. For the usage of special Apache Trinidad features please see Apache Myfaces Trinidad with Eclipse - Tutorial .

Java Snake Game

Snake

In this part of the Java 2D games tutorial, we will create a Java Snake game clone.

Snake

Snake is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple, its body grows. The snake must avoid the walls and its own body. This game is sometimes called Nibbles.

Development

The size of each of the joints of a snake is 10px. The snake is controlled with the cursor keys. Initially the snake has three joints. The game is started by pressing one of the cursor keys. If the game is finished, we display Game Over message in the middle of the Board.

Java 2D games tutorial

Basics

This is Java 2D games tutorial. It is aimed at beginners. This tutorial will teach you basics of programming 2D games in Java programming language and Swing GUI toolkit. All images used in this tutorial can be downloaded here.

Skeleton

We will show the skeleton of each of our Java 2D games.
Board.java
package skeleton;

import javax.swing.JPanel;

public class Board extends JPanel {
    public Board() {
    }
}
The Board is a panel, where the game takes place.
Skeleton.java
package skeleton;

import javax.swing.JFrame;

public class Skeleton extends JFrame {

    public Skeleton() {
        add(new Board());
        setTitle("Skeleton");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 280);
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public static void main(String[] args) {
        new Skeleton();
    }
}
This is the entry point of the game. Here we have the main method.
add(new Board());
Here we put the Board to the center of the JFrame component.
setDefaultCloseOperation(EXIT_ON_CLOSE);
This will close the application when we click on the close button. It is not the default behaviour.
setSize(300, 280);
This line sets the size for our window.
setLocationRelativeTo(null);
We center the window.
setVisible(true);
Show the window on the screen.
setResizable(false);
Make the window unresizable.
Skeleton
Figure: Skeleton

Comparison of Java and Android API

This article compares the Java and Android API and virtual machines.
While most Android applications are written in Java, there are many differences between the Java API and the Android API, and Android does not use a Java Virtual Machine but another one called Dalvik.

Android's Process Virtual machine

There is no Java Virtual Machine in the Android platform. Java byte code is not executed. Instead Java classes are compiled into Dalvik executables and run on Dalvik, a specialized virtual machine (VM) designed specifically for Android. Unlike Java VMs, which are stack machines, the Dalvik VM is a register-based architecture.

Dalvik has some specific characteristics that differentiate it from other standard VMs:
  • The VM was designed to use less space.
  • The constant pool has been modified to use only 32-bit indexes to simplify the interpreter.
  • Standard Java bytecode executes 8-bit stack instructions. Local variables must be copied to or from the operand stack by separate instructions. Dalvik instead uses its own 16-bit instruction set that works directly on local variables. The local variable is commonly picked by a 4-bit 'virtual register' field.
Because the bytecode loaded by the Dalvik virtual machine is not Java bytecode, and of the specific way Dalvik load classes, it is not possible to load Java libraries packages as jar files, and even a specific logic must be used to load Android libraries (specifically the content of the underlying dex file must be copied in the application private internal storage area, before being able to be loaded).

System properties

As it is the case for the Java SE class System, the Android System class allows the retrieval of system properties. However, some mandatory properties defined with the Java Virtual Machine have no meaning or a different meaning on Android. For example:

  • "java.version" property returns 0 because it is not used on Android,
  • "java.specification.version" invariably returns 0.9 independently of the version of Android used,
  • "java.class.version" invariably returns 50 independently of the version of Android used,
  • "user.dir" has a different meaning on Android,
  • "user.home" and "user.name" properties do not exist on Android

Class library

Dalvik does not align to Java SE nor Java ME class library profiles (e.g., Java ME classes, AWT or Swing are not supported). Instead it uses its own library ,built on a subset of the Apache Harmony Java implementation.

java.lang package

By default, the default output stream System.out and System.err do not output anything,[6] and developers are encouraged to use the Log class, which logs Strings on the LogCat tool.[7] (this has changed at least from HoneyComb, and they now output to the log console as well)

Graphics and Widget library

Android does not use the Abstract Window Toolkit nor the Swing library. User Interface is built using View objects. Android uses a framework similar to Swing based around Views rather thanJComponents. However, Android widgets are not JavaBeans: the Android application Context must be provided to the widget at creation.

Look and feel

Android widget library does not support a Pluggable look and feel architecture; The Look and Feel of Android widgets must be embedded in the widgets themselves. There is, however, a limited capability to set styles and themes for an application.

Layout manager

Contrary to Java where Layout managers can be applied to any container widget, Android layout behavior is encoded in the containers.

J2ME Tutorial

Introduction

This tutorial assumes that you have some familiarity with general programming concepts and the Java language.

What is J2ME?

J2ME stands for Java 2, Micro Edition. It is a stripped-down version of Java targeted at devices which have limited processing power and storage capabilities and intermittent or fairly low-bandwidth network connections. These include mobile phones, pagers,wireless devices and set-top boxes among others.

A Sample Wireless Stack would consist of:
  • Profiles
  • Configurations
  • Java Virtual Machines
  • Host Operating System

What is a J2ME Configuration?

A configuration defines the minimum Java technology that an application developer can expect on a broad range of implementing devices.

J2ME Connected, Limited Device Configuration (CLDC)

  • specifies the Java environment for mobile phone, pager and wireless devices
  • CLDC devices are usually wireless
  • 160 - 512k of memory available for Java
  • typically has limited power or battery operated
  • network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)

J2ME Connected Device Configuration (CDC)

  • describes the Java environment for digital television set-top boxes, high end wireless devices and automotive telematics systems.
  • device is powered by a 32-bit processor
  • 2MB or more of total memory available for Java
  • network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)
These two configurations differ only in their respective memory and display capabilities.

What is a J2ME Profile?

A specification layer above the configuration which describes the Java configuration for a specific vertical market or device type.

J2ME Profiles

J2ME Mobile Information Device Profile (MIDP)

  • this is the application environment for wireless devices based on the CLDC
  • contains classes for user interface, storage and networking

J2ME Foundation Profile, Personal Basis, Personal and RMI profiles

  • these are profiles for devices based on the CDC, which are not addressed in this tutorial

Virtual Machines

The CLDC and the CDC each require their own virtual machine because of their different memory and display capabilities. The CLDC virtual machine is far smaller than that required by the CDC and supports less features. The virtual machine for the CLDC is called the Kilo Virtual Machine (KVM) and the virtual machine for the CDC is called the CVM.

Java Cryptography

Cryptography is a field looking at techniques for "encoding and verifying things securely". It tends to focus on the following issues:

  • encryption of data so that an unauthorised third party cannot read it without a key of some sort;
  • authentication and validation (or certification): broadly speaking, checking that a piece of data is "what it should be" or "hasn't been tampered with"— e.g. whether the data was transmitted error-free, whether it was deliberately altered by third parties, and indeed whether the parties are who we believe they are;
  • computer protocols for using the previous two techniques correctly and in a way that allows all parties to know how they're being used (e.g. the TLS protocol allows a client to connect to a server over the Internet without the two machines previously knowing things such as session key or even preferred encryption method, maximum key length etc).
Indirectly at least, it is also concerned with human protocols for using these techniques (e.g. "don't make your password less than X characters", "don't just use letters in your password" etc).
When used appropriately, cryptography brings developers some very powerful tools, allowing us to do things like transmit login information securely across an untrusted network. Java is an excellent choice for building secure applications from the point of view that it has various standard cryptographical functions built in to the standard runtime libraries. But just as the existence of the Swing library doesn't automatically give your application a fantastic user interface, a cryptography library does not bring automatic security. There are still various challenges that we need to address beyond the simple "how do I perform such-and-such a function", for example:
  • we need to understand which tool/algorithm we need when;
  • where there's a choice, we need to assess the strengths and weaknesses of each;
  • some algorithms have various parameters that we need to understand;
  • using some algorithms correctly can be tricky and requires a little understanding of what is going on (e.g. using "128-bit encryption" with a key generated by java.util.Random doesn't give anything like 128 bits of security...);
  • even issues such as "what data should we encrypt when" can be a problem;
  • we need to take account of the security risks and needs, vs other needs, of different parts of our application and system as a whole.
On the following pages, we therefore discuss various topics:
  • we start with an introduction to encryption in general, considering why key-based encryption with a public algorithm is generally a better solution than "security through obscurity";
  • we look at symmetric encryption, which gives generally fast encryption via a shared secret key, generally using a type of algorithm called a block cipher whose weaknesses we need to assess;
  • asymmetric encryption, including how to use the common RSA encryption scheme in Java;
  • we give a comparison of encryption algorithms, showing performance data and an overview of current security opinion on the various symmetric ciphers;
  • key sizes: how to choose an encryption key size for symmetric encryption and how to enable and use larger key sizes in Java;
  • Secure hash functions, used for a variety of purpoes; we consider the performance and security of the various algorithms provided by standard in Java 6;
  • password-based encryption, in which we derive an encryption key from a password entered by the user.

Tuesday, July 9, 2013

Simple Search Engine Using C and CPP Project

Introduction :

This is a 'SSE' application. SSE stands for Simple Search Engine. It is a simple application that can be used to search within text file on a system.

Application Platform : GNU/Linux
Development Platform : Red Hat Linux
Programming Language : C++
Libraries used : C++ Standard Library

Project Specification:

Following is a summary of the requirements from the Requirements specification.
                1. Keyword Search: Search for a given keyword and return the set of documents containing the keyword. Rank the quesry results based on how frequently the keyword has appeared in the documents.
                2. Case-insensitivity: Keyword searches should be case insensitive.
                3. Logical operators: Define logical operators AND and OR that can be used to compose a complex query.
                4. Pharse matching: Pharses that are enclosed in quotes should match exactly.
                5. Stemming: An asterisk (*) at the end of a keyword should match all endings of the word.

                6. The result of a query should be a set of path names ordered in decending order of the number of occurences of the keywords.



Download Project Here

Java Mini Projects Download

Thursday, July 4, 2013

Java Networking (Socket Programming)



The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols:
  • TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
  • UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.
This tutorial gives good understanding on the following two subjects:
  • Socket Programming: This is most widely used concept in Networking and it has been explained in very detail.
  • URL Processing: This would be covered separately. Click here to learn about URL Processing in Java language.

Socket Programming:

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
  • The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
  • The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
  • After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.
  • The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.
  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets.

ServerSocket Class Methods:

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
The ServerSocket class has four constructors:
SNMethods with Description
1public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application.
2public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue.
3public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on
4public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests.
Here are some of the common methods of the ServerSocket class:
SNMethods with Description
1public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you.
2public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely
3public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept().
4public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object. Use this method if you instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and server, and communication can begin.

Socket Class Methods:

The java.net.Socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server:
SNMethods with Description
1public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.
2public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.
3public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
Connects to the specified host and port, creating a socket on the local host at the specified address and port.
4public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String
5public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server have a Socket object, so these methods can be invoked by both the client and server.
SNMethods with Description
1public void connect(SocketAddress host, int timeout) throws IOException
This method connects the socket to the specified host. This method is needed only when you instantiated the Socket using the no-argument constructor.
2public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to.
3public int getPort()
Returns the port the socket is bound to on the remote machine.
4public int getLocalPort()
Returns the port the socket is bound to on the local machine.
5public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket.
6public InputStream getInputStream() throws IOException
Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket.
7public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket
8public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting again to any server

InetAddress Class Methods:

This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while doing socket programming:
SNMethods with Description
1static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
2static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP address.
3static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name.
4String getHostAddress() 
Returns the IP address string in textual presentation.
5String getHostName() 
Gets the host name for this IP address.
6static InetAddress InetAddress getLocalHost()
Returns the local host.
7String toString()
Converts this IP address to a String.

Socket Client Example:

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.
// File Name GreetingClient.java

import java.net.*;
import java.io.*;

public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("Connecting to " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Just connected to "
                      + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out =
                       new DataOutputStream(outToServer);

         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in =
                        new DataInputStream(inFromServer);
         System.out.println("Server says " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Socket Server Example:

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument:
// File Name GreetingServer.java

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("Waiting for client on port " +
            serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to "
                  + server.getRemoteSocketAddress());
            DataInputStream in =
                  new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out =
                 new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to "
              + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt(args[0]);
      try
      {
         Thread t = new GreetingServer(port);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}
Compile client and server and then start server as follows:
$ java GreetingServer 6066
Waiting for client on port 6066...
Check client program as follows:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!