Commit 033d08f7 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
9780596002831
\ No newline at end of file
public class Circle {
// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r; // The radius of the circle
// Two instance methods: they operate on the instance fields of an object
public double area() { // Compute the area of the circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of the circle
return 2 * PI * r;
}
}
// This method creates and returns an Enumeration object
public java.util.Enumeration enumerate() {
// Here's the definition of Enumerator as a local class
class Enumerator implements java.util.Enumeration {
Linkable current;
public Enumerator() { current = head; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}
// Now return an instance of the Enumerator class defined directly above
return new Enumerator();
}
public java.util.Enumeration enumerate() {
// The anonymous class is defined as part of the return statement
return new java.util.Enumeration() {
Linkable current;
{ current = head; } // Replace constructor with an instance initializer
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}; // Note the required semicolon: it terminates the return statement
}
public class Circle {
public static final double PI = 3.14159; // A constant
public double r; // An instance field that holds the radius of the circle
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// The instance methods: compute values based on the radius
public double circumference() { return 2 * PI * r; }
public double area() { return PI * r*r; }
}
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false
}
}
package shapes; // Specify a package for the class
public class Circle { // The class is still public
// This is a generally useful constant, so we keep it public
public static final double PI = 3.14159;
protected double r; // Radius is hidden, but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected void checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) {
checkRadius(r);
this.r = r;
}
// Public data accessor methods
public double getRadius() { return r; }
public void setRadius(double r) {
checkRadius(r);
this.r = r;
}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
}
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference(); // semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}
public interface Centered {
public void setCenter(double x, double y);
public double getCenterX();
public double getCenterY();
}
public class CenteredRectangle extends Rectangle implements Centered {
// New instance fields
private double cx, cy;
// A constructor
public CenteredRectangle(double cx, double cy, double w, double h) {
super(w, h);
this.cx = cx;
this.cy = cy;
}
// We inherit all the methods of Rectangle, but must
// provide implementations of all the Centered methods.
public void setCenter(double x, double y) { cx = x; cy = y; }
public double getCenterX() { return cx; }
public double getCenterY() { return cy; }
}
// A class that implements a stack as a linked list
public class LinkedStack {
// This static member interface defines how objects are linked
public static interface Linkable {
public Linkable getNext();
public void setNext(Linkable node);
}
// The head of the list is a Linkable object
Linkable head;
// Method bodies omitted
public void push(Linkable node) { ... }
public Object pop() { ... }
}
// This class implements the static member interface
class LinkableInteger implements LinkedStack.Linkable {
// Here's the node's data and constructor
int i;
public LinkableInteger(int i) { this.i = i; }
// Here are the data and methods required to implement the interface
LinkedStack.Linkable next;
public LinkedStack.Linkable getNext() { return next; }
public void setNext(LinkedStack.Linkable node) { next = node; }
}
public class LinkedStack {
// Our static member interface; body omitted here...
public static interface Linkable { ... }
// The head of the list
private Linkable head;
// Method bodies omitted here
public void push(Linkable node) { ... }
public Linkable pop() { ... }
// This method returns an Enumeration object for this LinkedStack
public java.util.Enumeration enumerate() { return new Enumerator(); }
// Here is the implementation of the Enumeration interface,
// defined as a member class.
protected class Enumerator implements java.util.Enumeration {
Linkable current;
// The constructor uses the private head field of the containing class
public Enumerator() { current = head; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}
}
public class Clock extends Thread {
java.text.DateFormat f = // How to format the time for this locale
java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM);
volatile boolean keepRunning = true;
public Clock() { // The constructor
setDaemon(true); // Daemon thread: interpreter can exit while it runs
start(); // This thread starts itself
}
public void run() { // The body of the thread
while(keepRunning) { // This thread runs until asked to stop
String time = f.format(new java.util.Date()); // Current time
System.out.println(time); // Print the time
try { Thread.sleep(1000); } // Wait 1000 milliseconds
catch (InterruptedException e) {} // Ignore this exception
}
}
// Ask the thread to stop running
public void pleaseStop() { keepRunning = false; }
}
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class DOMToStream {
public static void main(String[] args)
throws ParserConfigurationException,
TransformerConfigurationException,
TransformerException
{
// Create a DocumentBuilderFactory and a DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Instead of parsing an XML document, however, just create an empty
// document that we can build up ourselves.
Document document = db.newDocument();
// Now build a document tree using DOM methods
Element book = document.createElement("book"); // Create new element
book.setAttribute("id", "javanut4"); // Give it an attribute
document.appendChild(book); // Add to the document
for(int i = 1; i <= 3; i++) { // Add more elements
Element chapter = document.createElement("chapter");
Element title = document.createElement("title");
title.appendChild(document.createTextNode("Chapter " + i));
chapter.appendChild(title);
chapter.appendChild(document.createElement("para"));
book.appendChild(chapter);
}
// Now create a TransformerFactory, and use it it create a Transformer
// object to transform or DOM document into a stream of XML text.
// No arguments to newTransformer() means no XSLT stylesheet
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
// Create the Source and Result objects for the transformation
DOMSource source = new DOMSource(document); // DOM document
StreamResult result = new StreamResult(System.out); // to XML text
// Finally do the transformation
transformer.transform(source, result);
}
}
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class DateServer {
public static void main(String[] args) throws java.io.IOException {
// Get a CharsetEncoder for encoding the text we send to the client
CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
// Create a new ServerSocketChannel, and bind it to port 8000.
// Note that we have to do this using the underlying ServerSocket.
ServerSocketChannel server = ServerSocketChannel.open();
server.socket().bind(new java.net.InetSocketAddress(8000));
for(;;) { // This server runs forever
// Wait for a client to connect.
SocketChannel client = server.accept();
// Get the current date and time as a string
String response = new java.util.Date().toString() + "\r\n";
// Wrap, encode, and send the string to the client
client.write(encoder.encode(CharBuffer.wrap(response)));
// Disconnect from the client
client.close();
}
}
}
/**
* This program computes the factorial of a number
*/
public class Factorial { // Define a class
public static void main(String[] args) { // The program starts here
int input = Integer.parseInt(args[0]); // Get the user's input
double result = factorial(input); // Compute the factorial
System.out.println(result); // Print out the result
} // The main() method ends here
public static double factorial(int x) { // This method computes x!
if (x < 0) // Check for bad input
return 0.0; // if bad, return 0
double fact = 1.0; // Begin with an initial value
while(x > 1) { // Loop until x equals 1
fact = fact * x; // multiply by x each time
x = x - 1; // and then decrement x
} // Jump back to start of loop
return fact; // Return the result
} // factorial() ends here
} // The class ends here
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class GetSectionTitles {
public static void main(String[] args)
throws IOException, ParserConfigurationException,
org.xml.sax.SAXException
{
// Create a factory object for creating DOM parsers, and configure it
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true); // We want to ignore comments
factory.setCoalescing(true); // Convert CDATA to Text nodes
factory.setNamespaceAware(false); // No namespaces: this is default
factory.setValidating(false); // Don't validate DTD: also default
// Now use the factory to create a DOM parser a.k.a. DocumentBuilder
DocumentBuilder parser = factory.newDocumentBuilder();
// Parse the file and build a Document tree to represent its content
Document document = parser.parse(new File(args[0]));
// Ask the document for a list of all <sect1> elements it contains
NodeList sections = document.getElementsByTagName("sect1");
// Loop through those <sect1> elements one at a time
int numSections = sections.getLength();
for(int i = 0; i < numSections; i++) {
Element section = (Element)sections.item(i); // A <sect1>
// The first Element child of each <sect1> should be a <title>
// element but there may be some whitespace Text nodes first, so
// loop through the children 'till we find the first element child.
Node title = section.getFirstChild();
while(title != null && title.getNodeType() != Node.ELEMENT_NODE)
title = title.getNextSibling();
// Print the text contained in the Text node child of this element
if (title != null)
System.out.println(title.getFirstChild().getNodeValue());
}
}
}
import java.io.*;
import java.net.*;
public class HttpMirror {
public static void main(String[] args) {
try {
int port = Integer.parseInt(args[0]); // The port to listen on
ServerSocket ss = new ServerSocket(port); // Create a socket to listen
for(;;) { // Loop forever
Socket client = ss.accept(); // Wait for a connection
ClientThread t = new ClientThread(client); // A thread to handle it
t.start(); // Start the thread running
} // Loop again
}
catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("Usage: java HttpMirror <port>;");
}
}
static class ClientThread extends Thread {
Socket client;
ClientThread(Socket client) { this.client = client; }
public void run() {
try {
// Get streams to talk to the client
BufferedReader in =
new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out =
new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
// Send an HTTP response header to the client
out.print("HTTP/1.0 200\r\nContent-Type: text/plain\r\n\r\n");
// Read the HTTP request from the client and send it right back
// Stop when we read the blank line from the client that marks
// the end of the request and its headers.
String line;
while((line = in.readLine()) != null) {
if (line.length() == 0) break;
out.println(line);
}
out.close();
in.close();
client.close();
}
catch (IOException e) { /* Ignore exceptions */ }
}
}
}
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
/**
* Get a document from a web server using HTTPS. Usage:
* java HttpsDownload <hostname> <filename>
**/
public class HttpsDownload {
public static void main(String[] args) throws IOException {
// Get a SocketFactory object for creating SSL sockets
SSLSocketFactory factory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
// Use the factory to create a secure socket connected to the
// HTTPS port of the specified web server.
SSLSocket sslsock=(SSLSocket)factory.createSocket(args[0],// hostname
443); // HTTPS port
// Get the certificate presented by the web server.
SSLSession session = sslsock.getSession();
X509Certificate cert;
try { cert = (X509Certificate)session.getPeerCertificates()[0]; }
catch(SSLPeerUnverifiedException e) { // If no or invalid certificate
System.err.println(session.getPeerHost() +
" did not present a valid certificate.");
return;
}
// Display details about the certificate
System.out.println(session.getPeerHost() +
" has presented a certificate belonging to:");
System.out.println("\t[" + cert.getSubjectDN().getName() + "]");
System.out.println("The certificate bears the valid signature of:");
System.out.println("\t[" + cert.getIssuerDN().getName() + "]");
// If the user does not trust the certificate, abort.
System.out.print("Do you trust this certificate (y/n)? ");
System.out.flush();
BufferedReader console =
new BufferedReader(new InputStreamReader(System.in));
if (Character.toLowerCase(console.readLine().charAt(0)) != 'y') return;
// Now use the secure socket just as we would use a regular socket.
// First, send a regular HTTP request over the SSL socket
PrintWriter out = new PrintWriter(sslsock.getOutputStream());
out.print("GET " + args[1] + " HTTP/1.0\r\n\r\n");
out.flush();
// Next, read the server's response and print it to the console.
BufferedReader in =
new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
String line;
while((line = in.readLine()) != null) System.out.println(line);
// Finally, close the socket.
sslsock.close();
}
}
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*; // For Set and Iterator
public class NonBlockingServer {
public static void main(String[] args) throws IOException {
// Get the character encoders and decoders we'll need
Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
CharsetDecoder decoder = charset.newDecoder();
// Allocate a buffer for communicating with clients
ByteBuffer buffer = ByteBuffer.allocate(512);
// All of the channels we use in this code will be in non-blocking
// mode. So we create a Selector object that will block while
// monitoring all of the channels and will only stop blocking when
// one or more of the channels is ready for I/O of some sort.
Selector selector = Selector.open();
// Create a new ServerSocketChannel, and bind it to port 8000.
// Note that we have to do this using the underlying ServerSocket.
ServerSocketChannel server = ServerSocketChannel.open();
server.socket().bind(new java.net.InetSocketAddress(8000));
// Put the ServerSocketChannel into non-blocking mode
server.configureBlocking(false);
// Now register it with the Selector (note we call register() on the
// channel, not the selector object, however). The SelectionKey
// represents the registration of this channel with this Selector
SelectionKey serverkey = server.register(selector,
SelectionKey.OP_ACCEPT);
for(;;) { // The main server loop. The server runs forever.
// This call blocks until there is activity on one of the
// registered channels. This is the key method in non-blocking I/O.
selector.select();
// Get a java.util.Set containing the SelectionKey objects for
// all channels that are ready for I/O.
Set keys = selector.selectedKeys();
// Use a java.util.Iterator to loop through the selected keys
for(Iterator i = keys.iterator(); i.hasNext(); ) {
// Get the next SelectionKey in the set, and then remove it
// from the set. It must be removed explicitly, or it will
// be returned again by the next call to select().
SelectionKey key = (SelectionKey) i.next();
i.remove();
// Check whether this key is the SelectionKey we got when
// we registered the ServerSocketChannel.
if (key == serverkey) {
// Activity on the ServerSocketChannel means a client
// is trying to connect to the server.
if (key.isAcceptable()) {
// Accept the client connection, and obtain a
// SocketChannel to communicate with the client.
SocketChannel client = server.accept();
// Put the client channel in non-blocking mode.
client.configureBlocking(false);
// Now register it with the Selector object, telling it
// that we'd like to know when there is data to be
// read from this channel.
SelectionKey clientkey =
client.register(selector, SelectionKey.OP_READ);
// Attach some client state to the key. We'll use
// this state below when we talk to the client.
clientkey.attach(new Integer(0));
}
}
else {
// If the key we got from the Set of keys is not the
// ServerSocketChannel key, then it must be a key
// representing one of the client connections.
// Get the channel from the key.
SocketChannel client = (SocketChannel) key.channel();
// If we got here, it should mean that there is data to
// be read from the channel, but we double-check here.
if (!key.isReadable()) continue;
// Now read bytes from the client. We assume that
// we get all the client's bytes in one read operation
int bytesread = client.read(buffer);
// If read() returns -1, it indicates end-of-stream, which
// means the client has disconnected, so de-register the
// selection key and close the channel.
if (bytesread == -1) {
key.cancel();
client.close();
continue;
}