Sunday, August 28, 2011

Assignment - Week 8

Develop a simple web application with simple layout of web application & some HTML skills. Your final project's layout will be similar.

Some links for HTML Learners

http://www.w3schools.com/html/default.asp
http://www.htmlcodetutorial.com/
http://www.tizag.com/htmlT/
http://htmldog.com/guides/htmlbeginner/
http://www.htmltutorials.ca/
http://www.quackit.com/html/tutorial/
http://www.w3.org/MarkUp/Guide/ [Quick Guide]

First Servlet - Using Tomcat 7


package com.evs.objava33.class16;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.getOutputStream();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
out.println("<title>First HTML Page</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>This is first Servlet Page: " + new Date() + "</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

Web Application Deployment Descriptor


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>objava33web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>First JSP Page</title>
</head>
<body>
<h1>
This is first JSP Page
<%=new java.util.Date()%></h1>
</body>
</html>

index.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>First HTML Page</title>
</head>
<body>
<h1>This is first HTML Page</h1>
</body>
</html>

Application Server Architecture

Java Enterprise Edition

The Java 2 Platform, Enterprise Edition (J2EE) defines the standard for developing multitier enterprise applications. The J2EE platform simplifies enterprise applications by basing them on standardized, modular components, by providing a complete set of services to those components, and by handling many details of application behavior automatically, without complex programming.

The J2EE platform takes advantage of many features of the Java 2 Platform, Standard Edition (J2SE), such as "Write Once, Run Anywhere" portability, JDBC API for database access, CORBA technology for interaction with existing enterprise resources, and a security model that protects data even in internet applications. Building on this base, the Java 2 Platform, Enterprise Edition adds full support for Enterprise JavaBeans components, Java Servlets API, JavaServer Pages and XML technology. The J2EE standard includes complete specifications and compliance tests to ensure portability of applications across the wide range of existing enterprise systems capable of supporting the J2EE platform. In addition, the J2EE specification now ensures Web services interoperability through support for the WS-I Basic Profile.

Monday, August 22, 2011

Assignment - Week 7

Continue Assignment of Week 6, and implement it as a client server address book. Additional attribute is to create a simple client; from which user can add/update/delete/view all address book entries. On server, there should be an audit of last added/update/delete/view entry, as who did what.

Note: Core Projects has been assigned in addition to this. Dead Line for Core Project is: 10-Sept-2011

Test Bank


package com.evs.objava33.class14;

import java.io.RandomAccessFile;
import java.util.Random;

public class TestBank {

private static double initialBalance = 10000;
private static int noOfTrans = 100;
private static double totalCredit = 0.0;
private static double totalDebit = 0.0;

public static void main(String[] args) {
Bank bank = new Bank();
Account account = new Account(1111, initialBalance);

Clerk c1 = new Clerk(bank);
Clerk c2 = new Clerk(bank);

Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();

Random rand = new Random();
Double amount = 0.0;
Transaction trans = null;

for (int i = 0; i < noOfTrans; i++) {
// Credit
amount = 50.0 + rand.nextInt(50);
trans = new Transaction(account, TransType.CREDIT, amount);
c1.doTransaction(trans);
totalCredit += amount;

// Debit
amount = 30.0 + rand.nextInt(30);
trans = new Transaction(account, TransType.DEBIT, amount);
c2.doTransaction(trans);
totalDebit += amount;
}

while (c1.isBusy() || c2.isBusy()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("Starting Balance: " + initialBalance);
System.out.println("Total Debits: " + totalDebit);
System.out.println("Total Credits: " + totalCredit);
System.out.println("Actual Balance: "
+ (initialBalance - totalDebit + totalCredit));
System.out.println("Account Balance: " + account.getBalance());

System.exit(0);
}
}

Clerk


package com.evs.objava33.class14;

public class Clerk implements Runnable {

private Bank bank;
private Transaction transaction;

public Clerk(Bank bank) {
this.bank = bank;
}

public void run() {
while (true) {
while (isBusy() == false) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bank.doTransaction(transaction);
transaction = null;
}
}

public void doTransaction(Transaction transaction) {
while (isBusy()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.transaction = transaction;
}

public boolean isBusy() {
return transaction != null;
}

}

Bank


package com.evs.objava33.class14;

public class Bank {

public synchronized void doTransaction(Transaction transaction) {
switch (transaction.getTransType()) {
case DEBIT:
// synchronized (transaction.getAccount()) {
double balance = transaction.getAccount().getBalance();
balance -= transaction.getAmount();
transaction.getAccount().setBalance(balance);
// }
break;
case CREDIT:
// synchronized (this) {
balance = transaction.getAccount().getBalance();
balance += transaction.getAmount();
transaction.getAccount().setBalance(balance);
// }
break;
default:
System.out.println("Unknown Transaction Type ... ");
break;
}

}
}

Transaction


package com.evs.objava33.class14;

public class Transaction {

private Account account;
private TransType transType;
private Double amount;

public Transaction(Account account, TransType transType, Double amount) {
this.account = account;
this.transType = transType;
this.amount = amount;
}

/**
* @return the account
*/
public Account getAccount() {
return account;
}

/**
* @param account
*            the account to set
*/
public void setAccount(Account account) {
this.account = account;
}

/**
* @return the transType
*/
public TransType getTransType() {
return transType;
}

/**
* @param transType
*            the transType to set
*/
public void setTransType(TransType transType) {
this.transType = transType;
}

/**
* @return the amount
*/
public Double getAmount() {
return amount;
}

/**
* @param amount
*            the amount to set
*/
public void setAmount(Double amount) {
this.amount = amount;
}

public String toString() {
return "Transaction [account=" + account + ", transType=" + transType
+ ", amount=" + amount + "]";
}
}

Account


package com.evs.objava33.class14;

/**
 * THis class is used for Account holding purposes
 *
 * @author Masuds
 * @since 1.1
 */
public class Account {

private Integer accountNumber;
private Double balance;

/**
* THis is default Constructor
*
* @param accountNumber
*            - Bank Account Number
* @param balance
*            - Bank Account Balance
*/
public Account(Integer accountNumber, Double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}

/**
* @return the accountNumber
*/
public Integer getAccountNumber() {
return accountNumber;
}

/**
* @param accountNumber
*            the accountNumber to set
*/
public void setAccountNumber(Integer accountNumber) {
this.accountNumber = accountNumber;
}

/**
* @return the balance
*/
public Double getBalance() {
return balance;
}

/**
* @param balance
*            the balance to set
*/
public void setBalance(Double balance) {
this.balance = balance;
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Account [accountNumber=" + accountNumber + ", balance="
+ balance + "]";
}
}

TransType


package com.evs.objava33.class14;

public enum TransType {
CREDIT, DEBIT;
}

Try Runnable


package com.evs.objava33.class14;

public class TryRunnable implements Runnable {

private String firstName;
private String lastName;
private Long delay;

public TryRunnable(String firstName, String lastName, Long delay) {
this.firstName = firstName;
this.lastName = lastName;
this.delay = delay;
}

public void run() {
while (true) {
System.out.println(firstName);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(lastName);
}
}

public static void main(String[] args) {
Thread first = new Thread(new TryRunnable("Asif", "Sajjad", 2000L),
"First");
Thread second = new Thread(new TryRunnable("Shahzad", "Masud", 3000L),
"Second");
Thread third = new Thread(new TryThread("Kamran", "Ahmad", 5000L),
"Third");

//first.setDaemon(true);
first.start();
second.start();
third.start();
}
}

Try Thread


package com.evs.objava33.class14;

public class TryThread extends Thread {

private String firstName;
private String lastName;
private Long delay;

public TryThread(String firstName, String lastName, Long delay) {
this.firstName = firstName;
this.lastName = lastName;
this.delay = delay;
}

public void run() {
while (true) {
System.out.println(firstName);
try {
sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(lastName);
}
}

public static void main(String[] args) {
Thread first = new TryThread("Asif", "Sajjad", 2000L);
Thread second = new TryThread("Shahzad", "Masud", 3000L);
Thread third = new TryThread("Kamran", "Ahmad", 5000L);

first.start();
second.start();
third.start();
}
}

Test Collections


package com.evs.objava33.class13;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Vector;

public class TestCollections {

public static void main(String[] args) {
// Sorted Duplicate Ordered
// Set No Yes No
// Sequence / List No/Yes Yes Yes
// Map Yes No Yes

// Set -> HashSet, LinkedHashSet, TreeSet, EnumSet
// List -> Vector, Stack, LinkedList, ArrayList, Queue
// Map -> Hashtable, HashMap, LinkedHashMap, WeakHashMap
// IdentityHashMap, TreeMap

Vector<Person> vec = new Vector<Person>();
vec.add(new Person(30, "Shahzad", "shahzad@gmail.com"));
vec.add(new Person(21, "Ahmad", "zeeshan@gmail.com"));
vec.add(new Person(11, "Mahmood", "mahmood@gmail.com"));

System.out.println(vec);
// System.out.println(vec.indexOf(new Person(21, "", "")));
// System.out.println(vec.contains(new Person(21, "", "")));
Collections.sort(vec);
System.out.println(vec);
Collections.sort(vec, new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.getEmail().compareTo(o2.getEmail());
}
});
System.out.println(vec);

// Date
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());

// Time
Time time = new Time(System.currentTimeMillis());

// Timestamp
Timestamp timestamp = new Timestamp(System.currentTimeMillis());

// Calendar
Calendar cal = Calendar.getInstance();
// cal.add(Calendar.DAY_OF_MONTH, 15);
// java.sql.Date dt = new java.sql.Date(cal.getTimeInMillis());
// cal.add(Calendar.DAY_OF_WEEK, -2);
// cal.get(Calendar.DAY_OF_WEEK);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, -3);
java.sql.Date begin = new java.sql.Date(cal.getTimeInMillis());
cal.add(Calendar.MONTH, 4);
cal.add(Calendar.DAY_OF_MONTH, -1);

}

private static class Person implements Comparable<Person> {
private Integer id;
private String name;
private String email;

public int compareTo(Person o) {
// Small = -1
// Equal = 0
// Greater = 1
int idx = getId().compareTo(o.getId());
return idx == 0 ? getName().compareTo(o.getName()) : idx;
}

public boolean equals(Object obj) {
// return super.equals(obj);
Person p = (Person) obj;
return p.getId().intValue() == getId().intValue();
}

public Person(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

/**
* @return the id
*/
public Integer getId() {
return id;
}

/**
* @param id
*            the id to set
*/
public void setId(Integer id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the email
*/
public String getEmail() {
return email;
}

/**
* @param email
*            the email to set
*/
public void setEmail(String email) {
this.email = email;
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", email=" + email
+ "]";
}
}
}

Sunday, August 7, 2011

Assignment - Week 6



Address Book
1. Name, Email, Phone, Address, Semester

1. Add / Update / Delete / View Person
2. Search (Name, Email, Phone, Address, Semester)
3. Pagination (5 per page)
4. Load on startup, Save on exit

Constraints:
- Object Serialization
- Composition / Inheritance / Abstraction
- GUI is optional
- Program should be Platform independent (work on Linux + windows)

PS: Please start working on your project ideas, and share it in next class.

Pair (Generics)


package com.evs.objava33.class12;

public class Pair<KeyType, ValueType> {

private KeyType key;
private ValueType value;

public Pair(KeyType key, ValueType value) {
this.key = key;
this.value = value;
}

/**
* @return the key
*/
public KeyType getKey() {
return key;
}

/**
* @param key
*            the key to set
*/
public void setKey(KeyType key) {
this.key = key;
}

/**
* @return the value
*/
public ValueType getValue() {
return value;
}

/**
* @param value
*            the value to set
*/
public void setValue(ValueType value) {
this.value = value;
}

public String toString() {
return "Pair [key=" + key + ", value=" + value + "]";
}
}

Try LinkedList


package com.evs.objava33.class12;

import com.evs.objava33.class7.PalmTree;
import com.evs.objava33.class7.Tree;

public class TryLinkedList {

public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addItem("One");
list.addItem("Two");
list.addItem("Three");

System.out.println(list);

LinkedList<Integer> intList = new LinkedList<Integer>();
LinkedList<PalmTree> palmList = new LinkedList<PalmTree>();

LinkedList<LinkedList<LinkedList<String>>> lst = new LinkedList<LinkedList<LinkedList<String>>>();
LinkedList<Pair<String, Integer>> newList = new LinkedList<Pair<String, Integer>>();
// newList.getFirst().getKey()
// newList.getFirst().getValue()

LinkedList<?>[] listArray = { list, intList, palmList, lst, newList };

print(list);
print(intList);
}

private static void print(LinkedList<?> list) {
StringBuilder buf = new StringBuilder();
buf.append("Linked List: ");
for (Object item = list.getFirst(); item != null; item = list.getNext()) {
buf.append(item);
buf.append(",");
}
System.out.println(buf.toString());
}
}

Linked List (Generics)


package com.evs.objava33.class12;

public class LinkedList<T> {

private ListItem start, end, current;

public LinkedList() {
start = end = current = null;
}

public LinkedList(T item) {
addItem(item);
}

public T getFirst() {
current = start;
return start == null ? null : start.item;
}

public T getNext() {
if (current != null) {
current = current.next;
}
return current == null ? null : current.item;
}

public void addItem(T[] items) {
if (items != null) {
for (T s : items) {
addItem(s);
}
}
}

public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Linked List: ");
for (T item = getFirst(); item != null; item = getNext()) {
buf.append(item);
buf.append(",");
}
return buf.toString();
}

public void addItem(T item) {
ListItem newItem = new ListItem(item);
if (start == null) {
start = end = newItem;
} else {
end.next = newItem;
end = newItem;
}
}

private class ListItem {
T item;
ListItem next;

public ListItem(T item) {
this.item = item;
}

@Override
public String toString() {
return "ListItem [item=" + item + "]";
}
}
}

Test File & Serialization


package com.evs.objava33.class11;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TestFile {

public static void main(String[] args) {
File myFile = new File("d:/abc.txt");
// File myDir = new File("c:/abc");
// File myDirFile = new File(myDir, "File.java");
// File myDirFile1 = new File("c:/abc", "File.java");
//
// try {
// File remoteFile = new File(new URI("http://www.yahoo.com/abc.html"));
// } catch (URISyntaxException e) {
// e.printStackTrace();
// }

String userDir = System.getProperty("user.dir");

// File dDrive = new File("D:" + File.pathSeparator + "temp-read");
File dDrive = new File("D:/temp-read");
String[] files = dDrive.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("txt");
}
});
File[] files1 = dDrive.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return true;
}
});
for (String s : files) {
System.out.println(s);
/*
* abc.txt Solaris10_9-10_VM.zip WorkFlowDAOImpl.class
*/
}

// try {
// BufferedOutputStream out = new BufferedOutputStream(
// new FileOutputStream(myFile, true));
// out.write("this is my first file".getBytes());
// out.close();
//
// // RandomAccessFile raf = new RandomAccessFile(myFile, "rw");
// // raf.write("This is my first File".getBytes());
// // raf.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }

// try {
// Process p = Runtime.getRuntime().exec("ping 192.168.0.1");
// } catch (IOException e) {
// e.printStackTrace();
// }

ObjectOutputStream fout = null;
try {
fout = new ObjectOutputStream(new FileOutputStream(myFile));
fout.writeObject(new TestObject(1, "One"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

ObjectInputStream fin = null;
try {
fin = new ObjectInputStream(new FileInputStream(myFile));
Object obj = fin.readObject();
if (obj instanceof TestObject) {
TestObject testObj = (TestObject) obj;
System.out.println(testObj);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

private static class TestObject implements Serializable {
private static final long serialVersionUID = -4314877130551524995L;

private String value;
private Integer key;
private transient String anotherString;

public TestObject(Integer key, String value) {
this.key = key;
this.value = value;
this.anotherString = "Unknown";
}

/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TestObject [value=" + value + ", key=" + key
+ ", anotherString=" + anotherString + "]";
}

/**
* @return the value
*/
public String getValue() {
return value;
}

/**
* @param value
*            the value to set
*/
public void setValue(String value) {
this.value = value;
}

/**
* @return the key
*/
public Integer getKey() {
return key;
}

/**
* @param key
*            the key to set
*/
public void setKey(Integer key) {
this.key = key;
}
}
}

Thursday, August 4, 2011

Assignment - Week 5

Create one chat solution, which will be used to chat between two users.

- Server component will be used to connect multiple users
- Client Component will be used to connect to server.
- Multiple Client Components will be able to send message to each other via Server.

Server Start Up Flow
- Server Listen to a port (6666)

Connect Flow
- Client Open Socket with Server and then Send a message 'LOGON' which will ensure that this user is connected with Server

Chat with Server
- Client Open Socket with Server
- Client Send 'LOGON' Message to Server
- Client Send Message to 'Chat Message'

Chat with Another Client
- Client Open Socket with Server
- Client Send 'LOGIN' Message to Server
- Client Send Message 'CLIENT1 == Message for Client'
- Server check if CLIENT1 is connected or not.
- If Client1 is connected send this message to him/her, otherwise respond user is not present

Chat Client


package com.evs.objava33.class10;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatClient {
public static void main(String[] args) {

try {
Socket client = new Socket("127.0.0.1", 6666);
// Here you are connected
BufferedOutputStream out = new BufferedOutputStream(
client.getOutputStream());
BufferedInputStream in = new BufferedInputStream(
client.getInputStream());
BufferedInputStream keyboard = new BufferedInputStream(System.in);

byte[] bKey = new byte[1024];
// byte[] bIn = new byte[1024];
// byte[] bOut = new byte[1024];

while (true) {
int readKey = keyboard.read(bKey); // Read from Keyboard
out.write(bKey, 0, readKey); // Write to client
out.flush();
}
// int readClient = in.read(bIn); // Input Buffer from Client
// System.out.println("Client: " + new String(bIn, 0, readClient));
} catch (IOException e) {
e.printStackTrace();
}

}

}

Chat Server


package com.evs.objava33.class10;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6666);
// You ensured that there isn't any server socket
Socket client = server.accept();
System.out.println("New Client: " + client);
// Here you are connected
BufferedOutputStream out = new BufferedOutputStream(
client.getOutputStream());
BufferedInputStream in = new BufferedInputStream(
client.getInputStream());
BufferedInputStream keyboard = new BufferedInputStream(System.in);

byte[] bKey = new byte[1024];
byte[] bIn = new byte[1024];
byte[] bOut = new byte[1024];

// int readKey = keyboard.read(bKey); // Read from Keyboard
// out.write(bKey, 0, readKey); // Write to client
// out.flush();
while (true) {
int readClient = in.read(bIn); // Input Buffer from Client
System.out.println("Client: ("
+ new java.util.Date(System.currentTimeMillis())
+ "): " + new String(bIn, 0, readClient));
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

Try Streams


package com.evs.objava33.class10;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class TryStream {

// BufferredInputStream = Memory Buffer
// DataINputStream = Primitive Data Types Read / Write
// CheckedInputStreamjj = Checksum maintenance
// CiperInputSteam = ENcypt- decyrtion
// DigestInputStream = One way encryption
// InflatorINputStream = Compression (91-97%), Image (4-9%), Video (1-3%).
// LineNUmberINputStream = Read Data and keep track of line#
// ProgressMonitorInputStream = Keep track of progress
// PushBackInputStream = Send it to designated resource

public static void main(String[] args) {
// BufferedInputStream in = new BufferedInputStream(System.in);
// try {
// byte[] b = new byte[100];
// int readBytes = in.read(b);
// String str = new String(b, 0, readBytes);
// System.out.println(str);
// } catch (IOException e) {
// e.printStackTrace();
// }

BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
char[] b = new char[100];
int readBytes = reader.read(b);
String str = new String(b, 0, readBytes);
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}

}
}

MyExceptionClass


package com.evs.objava33.class9;

public class MyExceptionClass extends Exception {

public MyExceptionClass() {
// TODO Auto-generated constructor stub
}

public MyExceptionClass(String message) {
super(message);
// TODO Auto-generated constructor stub
}

public MyExceptionClass(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}

public MyExceptionClass(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}

}

Test Exception


package com.evs.objava33.class9;

public class TestException {

private static int[] intArray = { 1, 2, 3, 4, 5, 6 };

public static void main(String[] args) {
try {
// Catchable Code
// System.out.println(3 / 0);
System.out.println(getValue(3, 0.0));
System.out.println(getArrayValue(7));
} catch (Exception e) {
System.out.println("Exception occur: Please contact ");
e.printStackTrace();
} finally {
// Clean up
}
}

public static int getValue(final Integer i, final Double j)
throws Exception {
return (int) (i / j);
}

private static int getArrayValue(int i) throws MyExceptionClass {
try {
return intArray[i];
} catch (Exception e) {
e.printStackTrace();
throw new MyExceptionClass(e);
}
}

}