Commit 581293f1 by O'Reilly Media, Inc.

Initial commit

parents
9781565927186
\ No newline at end of file
## Example files for the title:
# Learning Java, by Jonathan Knudsen
[![Learning Java, by Jonathan Knudsen](http://akamaicovers.oreilly.com/images/9781565927186/cat.gif)](https://www.safaribooksonline.com/library/view/title/1565927184//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
<html>
<head><title>Signed JAR</title></head>
<h1>Signed JAR</h1>
<!--"CONVERTED_APPLET"-->
<!-- CONVERTER VERSION 1.0 -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 350 HEIGHT = 200 codebase="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0">
<PARAM NAME = CODE VALUE = TestWrite >
<PARAM NAME = ARCHIVE VALUE = SignedTestWrite.jar >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.2">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.2" java_CODE = TestWrite java_ARCHIVE = SignedTestWrite.jar WIDTH = 350 HEIGHT = 200 pluginspage="http://java.sun.com/products/plugin/1.2/plugin-install.html"><NOEMBED></COMMENT>
</NOEMBED></EMBED>
</OBJECT>
<!--
<APPLET CODE = TestWrite ARCHIVE = SignedTestWrite.jar WIDTH = 350 HEIGHT = 200 >
</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->
</html>
<html>
<head><title>Unsigned JAR</title></head>
<h1>Unsigned JAR</h1>
<!--"CONVERTED_APPLET"-->
<!-- CONVERTER VERSION 1.0 -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 350 HEIGHT = 200 codebase="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0">
<PARAM NAME = CODE VALUE = TestWrite >
<PARAM NAME = ARCHIVE VALUE = UnsignedTestWrite.jar >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.2">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.2" java_CODE = TestWrite java_ARCHIVE = UnsignedTestWrite.jar WIDTH = 350 HEIGHT = 200 pluginspage="http://java.sun.com/products/plugin/1.2/plugin-install.html"><NOEMBED></COMMENT>
</NOEMBED></EMBED>
</OBJECT>
<!--
<APPLET CODE = TestWrite ARCHIVE = UnsignedTestWrite.jar WIDTH = 350 HEIGHT = 200 >
</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->
</html>
Learning Java, 'examples' subdirectory
May 15, 2000
The per-chapter subdirectories of this directory contain
complete Java applications and applets. In the book, each
such example begins with a comment line in this form:
//file: XXXXX.java
These source-code text files are in Linux/Unix format: each
line ends with a new-line character (octal 012). Following
are advisories for viewing/editing the source-code files
on other systems.
* On a Windows machine, use a text editor that recognizes
the new-line character (e.g. WordPad, not NotePad).
Alternatively, convert the text files by adding a
carriage-return character (octal 015) before each
new-line character (octal 012).
* On a Macintosh machine, convert the text files by changing
each new-line character (octal 012) to a carriage-return
character (octal 015).
//file: CryptURLConnection.java
class CryptURLConnection extends URLConnection {
static int defaultPort = 80;
CryptInputStream cis;
public String getContentType( ) {
return guessContentTypeFromName( url.getFile( ) );
}
CryptURLConnection ( URL url, String crypType )
throws IOException {
super( url );
try {
String classname = "learningjava.protocolhandlers.crypt."
+ crypType + "CryptInputStream";
cis = (CryptInputStream)
Class.forName(classname).newInstance( );
} catch ( Exception e ) {
throw new IOException("Crypt Class Not Found: "+e);
}
}
public void connect( ) throws IOException {
int port = ( url.getPort( ) == -1 ) ?
defaultPort : url.getPort( );
Socket s = new Socket( url.getHost( ), port );
// Send the filename in plaintext
OutputStream server = s.getOutputStream( );
new PrintWriter( new OutputStreamWriter( server, "8859_1" ),
true).println( "GET " + url.getFile( ) );
// Initialize the CryptInputStream
cis.set( s.getInputStream( ), server );
connected = true;
}
public InputStream getInputStream( ) throws IOException {
if (!connected)
connect( );
return ( cis );
}
}
//file: Handler.java
package learningjava.protocolhandlers.crypt;
import java.io.*;
import java.net.*;
public class Handler extends URLStreamHandler {
protected void parseURL(URL url, String spec,
int start, int end) {
int slash = spec.indexOf('/');
String crypType = spec.substring(start, slash-1);
super.parseURL(url, spec, slash, end);
setURL( url, "crypt:"+crypType, url.getHost( ),
url.getPort(), url.getFile(), url.getRef( ) );
}
protected URLConnection openConnection(URL url)
throws IOException {
String crypType = url.getProtocol( ).substring(6);
return new CryptURLConnection( url, crypType );
}
}
//file: rot13CryptInputStream.java
package learningjava.protocolhandlers.crypt;
import java.io.*;
abstract class CryptInputStream extends InputStream {
InputStream in;
OutputStream out;
abstract public void set( InputStream in, OutputStream out );
} // end of class CryptInputStream
class rot13CryptInputStream extends CryptInputStream {
public void set( InputStream in, OutputStream out ) {
this.in = new learningjava.io.rot13InputStream( in );
}
public int read( ) throws IOException {
return in.read( );
}
}
//file: x_tar.java
package learningjava.contenthandlers.application;
import java.net.*;
import java.io.*;
import java.util.Date;
public class x_tar extends ContentHandler {
static int
RECORDLEN = 512,
NAMEOFF = 0, NAMELEN = 100,
SIZEOFF = 124, SIZELEN = 12,
MTIMEOFF = 136, MTIMELEN = 12;
public Object getContent(URLConnection uc) throws IOException {
InputStream is = uc.getInputStream( );
StringBuffer output =
new StringBuffer( "Tape Archive Listing:\n\n" );
byte [] header = new byte[RECORDLEN];
int count = 0;
while ( (is.read(header) == RECORDLEN)
&& (header[NAMEOFF] != 0) ) {
String name =
new String(header, NAMEOFF, NAMELEN, "8859_1"). trim( );
String s =
new String(header, SIZEOFF, SIZELEN, "8859_1").trim( );
int size = Integer.parseInt(s, 8);
s = new String(header, MTIMEOFF, MTIMELEN, "8859_1").trim( );
long l = Integer.parseInt(s, 8);
Date mtime = new Date( l*1000 );
output.append( size + " " + mtime + " " + name + "\n" );
count += is.skip( size ) + RECORDLEN;
if ( count % RECORDLEN != 0 )
count += is.skip ( RECORDLEN - count % RECORDLEN);
}
if ( count == 0 )
output.append("Not a valid TAR file\n");
return( output.toString( ) );
}
}
//file: HelloJava1.java
public class HelloJava1 extends javax.swing.JComponent {
public static void main(String[] args) {
javax.swing.JFrame f = new javax.swing.JFrame("HelloJava1");
f.setSize(300, 300);
f.getContentPane().add(new HelloJava1( ));
f.setVisible(true);
}
public void paintComponent(java.awt.Graphics g) {
g.drawString("Hello, Java!", 125, 95);
}
}
//file: HelloJava2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloJava2
extends JComponent implements MouseMotionListener {
// Coordinates for the message
int messageX = 125, messageY = 95;
String theMessage;
public HelloJava2(String message) {
theMessage = message;
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
g.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent e) {
// Save the mouse coordinates and paint the message.
messageX = e.getX( );
messageY = e.getY( );
repaint( );
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
JFrame f = new JFrame("HelloJava2");
// Make the application exit when the window is closed.
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});
f.setSize(300, 300);
f.getContentPane( ).add(new HelloJava2("Hello, Java!"));
f.setVisible(true);
}
}
//file: HelloJava3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloJava3
extends JComponent
implements MouseMotionListener, ActionListener {
// Coordinates for the message
int messageX = 125, messageY = 95;
String theMessage;
JButton theButton;
// Current index into someColors
int colorIndex;
static Color[] someColors = { Color.black, Color.red,
Color.green, Color.blue, Color.magenta };
public HelloJava3(String message) {
theMessage = message;
theButton = new JButton("Change Color");
setLayout(new FlowLayout( ));
add(theButton);
theButton.addActionListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
g.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent e) {
// Save the mouse coordinates and paint the message.
messageX = e.getX( );
messageY = e.getY( );
repaint( );
}
public void mouseMoved(MouseEvent e) {}
public void actionPerformed(ActionEvent e) {
// Did somebody push our button?
if (e.getSource( ) == theButton)
changeColor( );
}
synchronized private void changeColor( ) {
// Change the index to the next color.
if (++colorIndex == someColors.length)
colorIndex = 0;
setForeground(currentColor( )); // Use the new color.
repaint( ); // Paint again so we can see the change.
}
synchronized private Color currentColor( ) {
return someColors[colorIndex];
}
public static void main(String[] args) {
JFrame f = new JFrame("HelloJava3");
// Make the application exit when the window is closed.
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});
f.setSize(300, 300);
f.getContentPane( ).add(new HelloJava3("Hello, Java!"));
f.setVisible(true);
}
}
//file: HelloJava4.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloJava4
extends JComponent
implements MouseMotionListener, ActionListener, Runnable {
// Coordinates for the message
int messageX = 125, messageY = 95;
String theMessage;
JButton theButton;
int colorIndex; // Current index into someColors.
static Color[] someColors = { Color.black, Color.red,
Color.green, Color.blue, Color.magenta };
boolean blinkState;
public HelloJava4(String message) {
theMessage = message;
theButton = new JButton("Change Color");
setLayout(new FlowLayout( ));
add(theButton);
theButton.addActionListener(this);
addMouseMotionListener(this);
Thread t = new Thread(this);
t.start( );
}
public void paintComponent(Graphics g) {
g.setColor(blinkState ? getBackground() : currentColor( ));
g.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent e) {
messageX = e.getX( );
messageY = e.getY( );
repaint( );
}
public void mouseMoved(MouseEvent e) {}
public void actionPerformed(ActionEvent e) {
// Did somebody push our button?
if (e.getSource( ) == theButton)
changeColor( );
}
synchronized private void changeColor( ) {
// Change the index to the next color.
if (++colorIndex == someColors.length)
colorIndex = 0;
setForeground(currentColor( )); // Use the new color.
repaint( ); // Paint again so we can see the change.
}
synchronized private Color currentColor( ) {
return someColors[colorIndex];
}
public void run( ) {
try {
while(true) {
blinkState = !blinkState; // Toggle blinkState.
repaint( ); // Show the change.
Thread.sleep(500);
}
}
catch (InterruptedException ie) {}
}
public static void main(String[] args) {
JFrame f = new JFrame("HelloJava4");
// Make the application exit when the window is closed.
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});
f.setSize(300, 300);
f.getContentPane( ).add(new HelloJava4("Hello, Java!"));
f.setVisible(true);
}
}
//file: EvilEmpire.java
import java.net.*;
public class EvilEmpire {
public static void main(String[] args) throws Exception{
try {
Socket s = new Socket("???.???.???.???", 80);
System.out.println("Connected!");
}
catch (SecurityException e) {
System.out.println("SecurityException: could not connect.");
}
}
}
//file: Invoke.java
import java.lang.reflect.*;
class Invoke {
public static void main( String [] args ) {
try {
Class c = Class.forName( args[0] );
Method m = c.getMethod( args[1], new Class [] { } );
Object ret = m.invoke( null, null );
System.out.println(
"Invoked static method: " + args[1]
+ " of class: " + args[0]
+ " with no args\nResults: " + ret );
} catch ( ClassNotFoundException e ) {
// Class.forName( ) can't find the class
} catch ( NoSuchMethodException e2 ) {
// that method doesn't exist
} catch ( IllegalAccessException e3 ) {
// we don't have permission to invoke that method
} catch ( InvocationTargetException e4 ) {
// an exception ocurred while invoking that method
System.out.println(
"Method threw an: " + e4.getTargetException( ) );
}
}
}
//file: Clock.java
public class Clock extends UpdateApplet {
public void paint( java.awt.Graphics g ) {
g.drawString( new java.util.Date().toString( ), 10, 25 );
}
}
//file: Consumer.java
import java.util.Vector;
class Producer extends Thread {
static final int MAXQUEUE = 5;
private Vector messages = new Vector( );
public void run( ) {
try {
while ( true ) {
putMessage( );
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}
private synchronized void putMessage( )
throws InterruptedException {
while ( messages.size( ) == MAXQUEUE )
wait( );
messages.addElement( new java.util.Date().toString( ) );
notify( );
}
// called by Consumer
public synchronized String getMessage( )
throws InterruptedException {
notify( );
while ( messages.size( ) == 0 )
wait( );
String message = (String)messages.firstElement( );
messages.removeElement( message );
return message;
}
} // end of class Producer
public class Consumer extends Thread {
Producer producer;
Consumer(Producer p) {
producer = p;
}
public void run( ) {
try {
while ( true ) {
String message = producer.getMessage( );
System.out.println("Got message: " + message);
sleep( 2000 );
}
}
catch( InterruptedException e ) { }
}
public static void main(String args[]) {
Producer producer = new Producer( );
producer.start( );
new Consumer( producer ).start( );
}
}
//file: NamedConsumer.java
public class NamedConsumer extends Thread {
Producer producer;
String name;
NamedConsumer(String name, Producer producer) {
this.producer = producer;
this.name = name;
}
public void run( ) {
try {
while ( true ) {
String message = producer.getMessage( );
System.out.println(name + " got message: " + message);
sleep( 2000 );
}
}
catch( InterruptedException e ) { }
}
public static void main(String args[]) {
Producer producer = new Producer( );
producer.start( );
// start two this time
new NamedConsumer( "One", producer ).start( );
new NamedConsumer( "Two", producer ).start( );
}
}
//file: Thready.java
public class Thready {
public static void main( String args [] ) {
new MyThread("Foo").start( );
new MyThread("Bar").start( );
}
} // end of class Thready
class MyThread extends Thread {
String message;
MyThread ( String message ) {
this.message = message;
}
public void run( ) {
while ( true )
System.out.println( message );
}
}
//file: UpdateApplet.java
public class UpdateApplet extends java.applet.Applet
implements Runnable {
private Thread updateThread;
int updateInterval = 1000;
public void run( ) {
while ( updateThread != null ) {
try {
Thread.sleep( updateInterval );
}
catch (InterruptedException e ) {
return;
}
repaint( );
}
}
public void start( ) {
if ( updateThread == null ) {
updateThread = new Thread(this);
updateThread.start( );
}
}
public void stop( ) {
if ( updateThread != null ) {
Thread runner = updateThread;
updateThread = null; // flag to quit
runner.interrupt( ); // wake up if asleep
}
}
}
//file: Hello.java
import java.util.*;
public class Hello {
public static void main(String[] args) {
ResourceBundle bun;
bun = ResourceBundle.getBundle("Message", Locale.ITALY);
System.out.println(bun.getString("HelloMessage"));
bun = ResourceBundle.getBundle("Message", Locale.US);
System.out.println(bun.getString("HelloMessage"));
}
}