Professional Documents
Culture Documents
Java Adv Core Tech Workshop Solutions
Java Adv Core Tech Workshop Solutions
Core Techniques
Solutions to
Workshops
Advanced Java Core Techniques: Solutions to Workshops Page i
Table of Contents
Lesson 1:
Using Basic Threads
// StockApp.java
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
// StockStream class
class StockStream extends Thread {
private Stock _stock;
private List _lstOutput;
_name = name;
_low = low;
_high = high;
}
show();
}
// APP METHODS
private void addStock(String sName, String sLow, String sHigh) {
// Instantiate Stock with values from TextFields
double low = Double.valueOf(sLow).doubleValue();
double high = Double.valueOf(sHigh).doubleValue();
Stock stk = new Stock(sName, low, high);
Thread.sleep(5000);
} catch (InterruptedException e) {
}
stopStream();
}
// SETUP METHODS
// Set up panel
Panel pnlMain = new Panel();
pnlMain.setLayout(new BorderLayout());
return pnlMain;
}
// INNER CLASSES
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Button btn = (Button) ae.getSource();
if (ae.getActionCommand().equals("start")) {
startStream();
btn.setLabel("Stop");
btn.setActionCommand("stop");
} else if (ae.getActionCommand().equals("stop")) {
stopStream();
btn.setLabel("Start");
btn.setActionCommand("start");
} else if (ae.getActionCommand().equals("clear")) {
_lstPrices.removeAll();
} else if (ae.getActionCommand().equals("add")) {
addStock(
_tfName.getText(),
_tfLow.getText(),
_tfHigh.getText());
} else if (ae.getActionCommand().equals("auto")) {
toggleAutoRun();
}
}
} // End of inner class ButtonHandler
} // End of StockAppGui class
class StockApp {
public static void main(String[] args) {
new StockAppGui(args);
}
}
Lesson 2:
Thread States
// StockApp.java
// Threads Lab 2.
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
// StockStream class
class StockStream extends Thread {
private Stock _stock;
private List _lstOutput;
show();
}
// APP METHODS
private void addStock(String sName, String sLow, String sHigh) {
// Instantiate Stock with values from TextFields
double low = Double.valueOf( sLow ).doubleValue();
double high = Double.valueOf( sHigh ).doubleValue();
Stock stk = new Stock( sName, low, high );
_vThreads.addElement( ss );
}
}
private void stopStream() {
// Go through Vector of threads, stop each one.
// Then clear Vector.
Enumeration e = _vThreads.elements();
while (e.hasMoreElements())
((StockStream) e.nextElement()).interrupt();
System.out.println("StockStream stopped");
_vThreads.clear();
}
// SETUP METHODS
}
private Panel getStockFeedPanel() {
Panel pnl = new Panel();
pnl.setLayout( new BorderLayout() );
pnl.add( BorderLayout.CENTER, _lstPrices );
pnl.add( BorderLayout.SOUTH, getStockFeedButtonPanel() );
return pnl;
}
return pnlMain;
}
// INNER CLASSES
private class ButtonHandler implements ActionListener {
public void actionPerformed( ActionEvent ae ) {
Button btn = (Button) ae.getSource();
if( ae.getActionCommand().equals("start")) {
startStream();
btn.setLabel("Stop");
btn.setActionCommand("stop");
}
else if( ae.getActionCommand().equals("stop")) {
stopStream();
btn.setLabel("Start");
btn.setActionCommand("start");
}
else if( ae.getActionCommand().equals("clear")) {
_lstPrices.removeAll();
}
else if( ae.getActionCommand().equals("add")) {
addStock( _tfName.getText(), _tfLow.getText(),
_tfHigh.getText() );
}
else if( ae.getActionCommand().equals("auto")) {
if( _thrAuto != null && _thrAuto.isAlive() )
stopAutoRun();
else
startAutoRun();
}
}
} // End of inner class ButtonHandler
} // End of StockAppGui class
class StockApp {
public static void main( String[] args ) {
new StockAppGui(args);
}
}
Lesson 5:
Using Text Streams
package mycode;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import java.util.Iterator;
if (args.length < 1) {
tfrw.info(
"{Input File Name}
[{output File Name}] [{name of serialized vector}]");
return;
}
inputFileName = args[0];
vec = tfrw.readTextFile(inputFileName);
if (vec == null) {
return;
}
//------------------------------------------------
// Read input from text file
//------------------------------------------------
public Vector readTextFile(String inputFileName) {
try {
Vector vec = new Vector();
FileReader fr = new FileReader(inputFileName);
BufferedReader br = new BufferedReader(fr);
//------------------------------------------------
// Print to standard output
//------------------------------------------------
public void printLines(Vector vec) {
Iterator iter = vec.iterator();
while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}
//------------------------------------------------
// Write to a text file
//------------------------------------------------
public void writeTextFile(String outputFileName, Vector vec) {
try {
FileWriter fw = new FileWriter(outputFileName);
PrintWriter pw = new PrintWriter(fw);
Iterator iter = vec.iterator();
while (iter.hasNext()) {
pw.println((String) iter.next());
}
pw.close();
} catch (Exception e) {
info("Exception in writeTextFile():");
info(e.getClass().getName());
info(e.getMessage());
}
}
//------------------------------------------------
// Serialize the vector
//------------------------------------------------
public void serializeVector(String fileName, Vector vec) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vec);
oos.close();
} catch (Exception e) {
info("Exception in writeObjectFile():");
info(e.getClass().getName());
info(e.getMessage());
}
}
Lesson 6: Serialization
package mycode;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import java.util.Iterator;
if (args.length < 1) {
sor.info(
"{name of serialized vector} [-print]");
return;
}
serializedObjectName = args[0];
vec = sor.readObjectFile(serializedObjectName);
if (vec == null) {
return;
}
sor.printLines(vec);
}
//------------------------------------------------
// Print to standard output
//------------------------------------------------
public void printLines(Vector vec) {
Iterator iter = vec.iterator();
while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}
// ------------------------------------------------
Lesson 8:
Inet Addresses
import java.io.*;
import java.net.*;
import course.application.Keyboard;
try {
Keyboard.setPrompt("Enter a host name or address: > ");
String strInput = Keyboard.getLine();
while( strInput.length() > 0 ) {
displayHost(strInput);
strInput = Keyboard.getLine();
}
}
catch(IOException e) {
System.out.println("Couldn't get keyboard input:\n" + e);
}
}
}
Lesson 9:
The Finger Application
package mycode;
import course.application.*;
import java.io.*;
import java.net.*;
//================================================
// Static Variables
//================================================
public static final int fingerPort = 79;
//================================================
// Instance Variables
//================================================
private Socket _socket;
private BufferedReader _br;
private PrintWriter _pw;
//================================================
// Methods for labs:
//================================================
sendData();
receiveReply();
}
catch (IOException e) {
System.err.println(e);
System.exit(0);
}
}
}
Lesson 10:
Writing a Finger Server
package mycode;
import course.application.*;
import java.util.Date;
import java.io.*;
import java.net.*;
//================================================
// Methods for labs:
//================================================
//------------------------------------------------
// Initialize server socket
//------------------------------------------------
public void init() {
ServerSocket srvSocket;
try {
while (true) {
System.err.println("=======================");
// Receive call from next client:
Socket socket = srvSocket.accept();
System.err.println("Socket accepted from " +
socket.getInetAddress().getHostName());
// Pass new socket to sendReply() method
sendReply(socket);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(0);
}
}
System.out.println("Composing reply...");
pw.println(new Date());
pw.println("Reply from Finger server on " +
socket.getLocalAddress().getHostName());
pw.flush();
socket.close();
}
catch(IOException e) {
System.err.println("IOException from individual socket:\n" + e);
}
}
}
Lesson 11:
Displaying a Page
from a URL
package mycode;
import course.application.*;
import java.net.*;
import java.io.*;
try {
url = new URL(strURL);
}
catch (MalformedURLException mue) {
System.err.println("Bad URL:\n" + mue);
System.exit(-1);
return;
}