Reorganized network appendix. try-with-finally reformatting

This commit is contained in:
Bruce Eckel 2016-09-06 12:32:51 -06:00
parent 13a6e2c5e6
commit 073f20e221
44 changed files with 438 additions and 324 deletions

View File

@ -50,9 +50,11 @@ extends AbstractProcessor {
} }
private void private void
writeInterfaceFile(String interfaceName) { writeInterfaceFile(String interfaceName) {
try(Writer writer = processingEnv.getFiler() try(
Writer writer = processingEnv.getFiler()
.createSourceFile(interfaceName) .createSourceFile(interfaceName)
.openWriter()) { .openWriter()
) {
String packageName = elementUtils String packageName = elementUtils
.getPackageOf(interfaceMethods .getPackageOf(interfaceMethods
.get(0)).toString(); .get(0)).toString();

View File

@ -17,21 +17,25 @@ public class GZIPcompress {
"the file to test.gz"); "the file to test.gz");
System.exit(1); System.exit(1);
} }
try(InputStream in = new BufferedInputStream( try(
InputStream in = new BufferedInputStream(
new FileInputStream(args[0])); new FileInputStream(args[0]));
BufferedOutputStream out = BufferedOutputStream out =
new BufferedOutputStream( new BufferedOutputStream(
new GZIPOutputStream( new GZIPOutputStream(
new FileOutputStream("test.gz")))) { new FileOutputStream("test.gz")))
) {
System.out.println("Writing file"); System.out.println("Writing file");
int c; int c;
while((c = in.read()) != -1) while((c = in.read()) != -1)
out.write(c); out.write(c);
} }
System.out.println("Reading file"); System.out.println("Reading file");
try(BufferedReader in2 = new BufferedReader( try(
BufferedReader in2 = new BufferedReader(
new InputStreamReader(new GZIPInputStream( new InputStreamReader(new GZIPInputStream(
new FileInputStream("test.gz"))))) { new FileInputStream("test.gz"))))
) {
String s; String s;
while((s = in2.readLine()) != null) while((s = in2.readLine()) != null)
System.out.println(s); System.out.println(s);

View File

@ -13,19 +13,23 @@ import java.util.*;
public class ZipCompress { public class ZipCompress {
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(FileOutputStream f = try(
FileOutputStream f =
new FileOutputStream("test.zip"); new FileOutputStream("test.zip");
CheckedOutputStream csum = CheckedOutputStream csum =
new CheckedOutputStream(f, new Adler32()); new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum); ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = BufferedOutputStream out =
new BufferedOutputStream(zos)) { new BufferedOutputStream(zos)
) {
zos.setComment("A test of Java Zipping"); zos.setComment("A test of Java Zipping");
// No corresponding getComment(), though. // No corresponding getComment(), though.
for(String arg : args) { for(String arg : args) {
System.out.println("Writing file " + arg); System.out.println("Writing file " + arg);
try(InputStream in = new BufferedInputStream( try(
new FileInputStream(arg))) { InputStream in = new BufferedInputStream(
new FileInputStream(arg))
) {
zos.putNextEntry(new ZipEntry(arg)); zos.putNextEntry(new ZipEntry(arg));
int c; int c;
while((c = in.read()) != -1) while((c = in.read()) != -1)
@ -39,13 +43,15 @@ public class ZipCompress {
} }
// Now extract the files: // Now extract the files:
System.out.println("Reading file"); System.out.println("Reading file");
try(FileInputStream fi = try(
FileInputStream fi =
new FileInputStream("test.zip"); new FileInputStream("test.zip");
CheckedInputStream csumi = CheckedInputStream csumi =
new CheckedInputStream(fi, new Adler32()); new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi); ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = BufferedInputStream bis =
new BufferedInputStream(in2)) { new BufferedInputStream(in2)
) {
ZipEntry ze; ZipEntry ze;
while((ze = in2.getNextEntry()) != null) { while((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze); System.out.println("Reading file " + ze);
@ -58,7 +64,9 @@ public class ZipCompress {
"Checksum: "+csumi.getChecksum().getValue()); "Checksum: "+csumi.getChecksum().getValue());
} }
// Alternative way to open and read Zip files: // Alternative way to open and read Zip files:
try(ZipFile zf = new ZipFile("test.zip")) { try(
ZipFile zf = new ZipFile("test.zip")
) {
Enumeration e = zf.entries(); Enumeration e = zf.entries();
while(e.hasMoreElements()) { while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry)e.nextElement(); ZipEntry ze2 = (ZipEntry)e.nextElement();

View File

@ -18,8 +18,10 @@ class Second extends Reporter {}
public class AutoCloseableDetails { public class AutoCloseableDetails {
public static void main(String[] args) { public static void main(String[] args) {
try(First f = new First(); try(
Second s = new Second()) { First f = new First();
Second s = new Second()
) {
} }
} }
} }

View File

@ -7,8 +7,10 @@ class Third extends Reporter {}
public class BodyException { public class BodyException {
public static void main(String[] args) { public static void main(String[] args) {
try(First f = new First(); try(
Second s2 = new Second()) { First f = new First();
Second s2 = new Second()
) {
System.out.println("In body"); System.out.println("In body");
Third t = new Third(); Third t = new Third();
new SecondExcept(); new SecondExcept();

View File

@ -25,9 +25,11 @@ class Closer extends Reporter2 {
public class CloseExceptions { public class CloseExceptions {
public static void main(String[] args) { public static void main(String[] args) {
try(First f = new First(); try(
First f = new First();
Closer c = new Closer(); Closer c = new Closer();
Second s = new Second()) { Second s = new Second()
) {
System.out.println("In body"); System.out.println("In body");
} catch(CloseException e) { } catch(CloseException e) {
System.out.println("Caught: " + e); System.out.println("Caught: " + e);

View File

@ -14,9 +14,11 @@ class SecondExcept extends Reporter {
public class ConstructorException { public class ConstructorException {
public static void main(String[] args) { public static void main(String[] args) {
try(First f = new First(); try(
First f = new First();
SecondExcept s = new SecondExcept(); SecondExcept s = new SecondExcept();
Second s2 = new Second()) { Second s2 = new Second()
) {
System.out.println("In body"); System.out.println("In body");
} catch(CE e) { } catch(CE e) {
System.out.println("Caught: " + e); System.out.println("Caught: " + e);

View File

@ -9,10 +9,12 @@ import java.util.stream.*;
public class StreamsAreAutoCloseable { public class StreamsAreAutoCloseable {
public static void public static void
main(String[] args) throws IOException{ main(String[] args) throws IOException{
try(Stream<String> in = Files.lines( try(
Stream<String> in = Files.lines(
Paths.get("StreamsAreAutoCloseable.java")); Paths.get("StreamsAreAutoCloseable.java"));
PrintWriter outfile = new PrintWriter( PrintWriter outfile = new PrintWriter(
"Results.txt");) { // (1) "Results.txt"); // (1)
) {
in.skip(5) in.skip(5)
.limit(1) .limit(1)
.map(String::toLowerCase) .map(String::toLowerCase)

View File

@ -8,7 +8,9 @@ class Anything {}
public class TryAnything { public class TryAnything {
public static void main(String[] args) { public static void main(String[] args) {
try(Anything a = new Anything()) { try(
Anything a = new Anything()
) {
} }
} }
} }

View File

@ -6,8 +6,10 @@ import java.io.*;
public class TryWithResources { public class TryWithResources {
public static void main(String[] args) { public static void main(String[] args) {
try(InputStream in = new FileInputStream( try(
new File("TryWithResources.java"))) { InputStream in = new FileInputStream(
new File("TryWithResources.java"))
) {
int contents = in.read(); int contents = in.read();
// Process contents // Process contents
} catch(IOException e) { } catch(IOException e) {

View File

@ -8,10 +8,12 @@ import java.util.stream.*;
public class StreamInAndOut { public class StreamInAndOut {
public static void main(String[] args) { public static void main(String[] args) {
try(Stream<String> input = try(
Stream<String> input =
Files.lines(Paths.get("StreamInAndOut.java")); Files.lines(Paths.get("StreamInAndOut.java"));
PrintWriter output = PrintWriter output =
new PrintWriter("StreamInAndOut.txt")) { new PrintWriter("StreamInAndOut.txt")
) {
input input
.map(String::toUpperCase) .map(String::toUpperCase)
.forEachOrdered(output::println); .forEachOrdered(output::println);

View File

@ -9,12 +9,14 @@ public class BasicFileOutput {
static String file = "BasicFileOutput.dat"; static String file = "BasicFileOutput.dat";
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(BufferedReader in = new BufferedReader( try(
BufferedReader in = new BufferedReader(
new StringReader( new StringReader(
BufferedInputFile.read( BufferedInputFile.read(
"BasicFileOutput.java"))); "BasicFileOutput.java")));
PrintWriter out = new PrintWriter( PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(file)))) { new BufferedWriter(new FileWriter(file)))
) {
int lineCount = 1; int lineCount = 1;
String s; String s;
while((s = in.readLine()) != null ) while((s = in.readLine()) != null )

View File

@ -8,8 +8,10 @@ import java.io.*;
public class BufferedInputFile { public class BufferedInputFile {
public static String public static String
read(String filename) throws IOException { read(String filename) throws IOException {
try(BufferedReader in = new BufferedReader( try(
new FileReader(filename))) { BufferedReader in = new BufferedReader(
new FileReader(filename))
) {
String s; String s;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) while((s = in.readLine())!= null)

View File

@ -9,11 +9,13 @@ public class FileOutputShortcut {
static String file = "FileOutputShortcut.dat"; static String file = "FileOutputShortcut.dat";
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(BufferedReader in = new BufferedReader( try(
BufferedReader in = new BufferedReader(
new StringReader(BufferedInputFile.read( new StringReader(BufferedInputFile.read(
"FileOutputShortcut.java"))); "FileOutputShortcut.java")));
// Here's the shortcut: // Here's the shortcut:
PrintWriter out = new PrintWriter(file)) { PrintWriter out = new PrintWriter(file)
) {
int lineCount = 1; int lineCount = 1;
String s; String s;
while((s = in.readLine()) != null ) while((s = in.readLine()) != null )

View File

@ -8,11 +8,13 @@ import java.io.*;
public class FormattedMemoryInput { public class FormattedMemoryInput {
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(DataInputStream in = new DataInputStream( try(
DataInputStream in = new DataInputStream(
new ByteArrayInputStream( new ByteArrayInputStream(
BufferedInputFile.read( BufferedInputFile.read(
"FormattedMemoryInput.java") "FormattedMemoryInput.java")
.getBytes()))) { .getBytes()))
) {
while(true) while(true)
System.out.write((char)in.readByte()); System.out.write((char)in.readByte());
} catch(EOFException e) { } catch(EOFException e) {

View File

@ -7,17 +7,21 @@ import java.io.*;
public class StoringAndRecoveringData { public class StoringAndRecoveringData {
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(DataOutputStream out = new DataOutputStream( try(
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream( new BufferedOutputStream(
new FileOutputStream("Data.txt")))) { new FileOutputStream("Data.txt")))
) {
out.writeDouble(3.14159); out.writeDouble(3.14159);
out.writeUTF("That was pi"); out.writeUTF("That was pi");
out.writeDouble(1.41413); out.writeDouble(1.41413);
out.writeUTF("Square root of 2"); out.writeUTF("Square root of 2");
} }
try(DataInputStream in = new DataInputStream( try(
DataInputStream in = new DataInputStream(
new BufferedInputStream( new BufferedInputStream(
new FileInputStream("Data.txt")))) { new FileInputStream("Data.txt")))
) {
System.out.println(in.readDouble()); System.out.println(in.readDouble());
// Only readUTF() will recover the // Only readUTF() will recover the
// Java-UTF String properly: // Java-UTF String properly:

View File

@ -9,9 +9,11 @@ import java.io.*;
public class TestEOF { public class TestEOF {
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(DataInputStream in = new DataInputStream( try(
DataInputStream in = new DataInputStream(
new BufferedInputStream( new BufferedInputStream(
new FileInputStream("TestEOF.java")))) { new FileInputStream("TestEOF.java")))
) {
while(in.available() != 0) while(in.available() != 0)
System.out.write(in.readByte()); System.out.write(in.readByte());
} }

View File

@ -7,8 +7,10 @@ import java.io.*;
public class UsingRandomAccessFile { public class UsingRandomAccessFile {
static String file = "rtest.dat"; static String file = "rtest.dat";
static void display() throws IOException { static void display() throws IOException {
try(RandomAccessFile rf = try(
new RandomAccessFile(file, "r")) { RandomAccessFile rf =
new RandomAccessFile(file, "r")
) {
for(int i = 0; i < 7; i++) for(int i = 0; i < 7; i++)
System.out.println( System.out.println(
"Value " + i + ": " + rf.readDouble()); "Value " + i + ": " + rf.readDouble());
@ -17,16 +19,20 @@ public class UsingRandomAccessFile {
} }
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
try(RandomAccessFile rf = try(
new RandomAccessFile(file, "rw")) { RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
for(int i = 0; i < 7; i++) for(int i = 0; i < 7; i++)
rf.writeDouble(i*1.414); rf.writeDouble(i*1.414);
rf.writeUTF("The end of the file"); rf.writeUTF("The end of the file");
rf.close(); rf.close();
display(); display();
} }
try(RandomAccessFile rf = try(
new RandomAccessFile(file, "rw")) { RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
rf.seek(5*8); rf.seek(5*8);
rf.writeDouble(47.0001); rf.writeDouble(47.0001);
rf.close(); rf.close();

View File

@ -2,31 +2,22 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// {ValidateByHand} // Starts multiple clients, each of which sends datagrams.
// Tests the ChatterServer by starting multiple
// clients, each of which sends datagrams.
package network; package network;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import onjava.*;
public class ChatterClient extends Thread { public class ChatterClient implements Runnable {
private InetAddress hostAddress; private InetAddress hostAddress;
private byte[] buf = new byte[1000]; private byte[] buf = new byte[1000];
private DatagramPacket dp = private DatagramPacket dp =
new DatagramPacket(buf, buf.length); new DatagramPacket(buf, buf.length);
private int id; private static int counter = 0;
private int id = counter++;
public ChatterClient(int identifier) { public ChatterClient(InetAddress hostAddress) {
id = identifier; this.hostAddress = hostAddress;
try { System.out.println("ChatterClient #" + id + " starting");
hostAddress =
InetAddress.getByName("localhost");
} catch(UnknownHostException e) {
System.err.println("Cannot find host");
System.exit(1);
}
System.out.println("ChatterClient starting");
} }
public void sendAndEcho(String msg) { public void sendAndEcho(String msg) {
try ( try (
@ -45,21 +36,13 @@ public class ChatterClient extends Thread {
dp.getPort() + ": " + dp.getPort() + ": " +
Dgram.toString(dp); Dgram.toString(dp);
System.out.println(rcvd); System.out.println(rcvd);
} catch(SocketException e) {
System.err.println("Can't open socket");
throw new RuntimeException(e);
} catch(IOException e) { } catch(IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@Override @Override
public void run() { public void run() {
for(int i = 0; i <= 25; i++) for(int i = 0; i <= 5; i++)
sendAndEcho("Client #" + id + ", message #" + i); sendAndEcho("Client #" + id + ", message #" + i);
} }
public static void main(String[] args) {
new TimedAbort(5); // Terminate after 5 seconds
for(int i = 0; i <= 10; i++)
new ChatterClient(i).start();
}
} }

View File

@ -2,20 +2,18 @@
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// {ValidateByHand}
// A server that echoes datagrams // A server that echoes datagrams
package network; package network;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import onjava.*;
public class ChatterServer { public class ChatterServer implements Runnable {
static final int INPORT = 1711; static final int INPORT = 1711;
private byte[] buf = new byte[1000]; private byte[] buf = new byte[1000];
private DatagramPacket dp = private DatagramPacket dp =
new DatagramPacket(buf, buf.length); new DatagramPacket(buf, buf.length);
public ChatterServer() { public void run() {
// Can listen & send on the same socket: // Can listen & send on the same socket:
try ( try (
DatagramSocket socket = new DatagramSocket(INPORT) DatagramSocket socket = new DatagramSocket(INPORT)
@ -38,13 +36,6 @@ public class ChatterServer {
dp.getAddress(), dp.getPort()); dp.getAddress(), dp.getPort());
socket.send(echo); socket.send(echo);
} }
} catch(IOException e) { } catch(IOException e) { throw new RuntimeException(e); }
System.out.println("Communication error");
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new TimedAbort(5); // Terminate after 5 seconds
new ChatterServer();
} }
} }

View File

@ -1,18 +1,18 @@
// network/MultiSimpleServer.java // network/MultiServer.java
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Uses threads to handle any number of clients. // Uses threads to handle any number of clients.
// {ValidateByHand}
package network; package network;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import onjava.*; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class ServeOneSimple implements Runnable { class ServeOne implements Runnable {
private ServerSocket ss; private ServerSocket ss;
public static final int PORT = 8080;
ServeOneSimple(ServerSocket ss) throws IOException { public ServeOne(ServerSocket ss) throws IOException {
this.ss = ss; this.ss = ss;
} }
@Override @Override
@ -27,33 +27,34 @@ class ServeOneSimple implements Runnable {
new PrintWriter( new PrintWriter(
new BufferedWriter( new BufferedWriter(
new OutputStreamWriter( new OutputStreamWriter(
// Enable auto-flush: // Boolean enables auto-flush
socket.getOutputStream())), true) socket.getOutputStream())), true)
) { ) {
while (true) { in.lines().anyMatch(message -> {
String str = in.readLine(); if (message.equals("END")) {
if(str.equals("END")) break; System.out.println("Received END. Closing Socket.");
System.out.println("Echoing: " + str); return true;
out.println(str);
} }
System.out.println("closing socket..."); System.out.println("Message : " + message);
out.println(message);
return false;
});
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
public class MultiSimpleServer { public class MultiServer implements Runnable {
static final int PORT = 8080; private ExecutorService pool;
public static void public void run() {
main(String[] args) throws IOException { pool = Executors.newFixedThreadPool(30);
new TimedAbort(5); // Terminate after 5 seconds try (ServerSocket ss = new ServerSocket(ServeOne.PORT)) {
System.out.println("Server Started");
try (ServerSocket ss = new ServerSocket(PORT)){
// Block until a connection occurs:
while (true) { while (true) {
new ServeOneSimple(ss); pool.submit(new ServeOne(ss));
} }
} catch (IOException e) {
throw new RuntimeException(e);
} }
} }
} }

View File

@ -4,22 +4,19 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Sends lines to the server and // Sends lines to the server and
// reads lines the server sends. // reads lines the server sends.
// {ValidateByHand}
package network; package network;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
public class SimpleClient { public class SimpleClient implements Runnable {
public static void private InetAddress hostAddress;
main(String[] args) throws IOException { public SimpleClient(InetAddress hostAddress) {
// Produce the "Local Loopback" IP address this.hostAddress = hostAddress;
// for testing on one machine w/o a network: }
InetAddress addr = public void run() {
InetAddress.getLoopbackAddress(); System.out.println("hostAddress = " + hostAddress);
System.out.println("addr = " + addr);
// TWR will sure that the socket is closed:
try ( try (
Socket socket = new Socket(addr, SimpleServer.PORT); Socket socket = new Socket(hostAddress, SimpleServer.PORT);
BufferedReader in = BufferedReader in =
new BufferedReader( new BufferedReader(
new InputStreamReader( new InputStreamReader(
@ -35,9 +32,11 @@ public class SimpleClient {
for(int i = 0; i < 10; i ++) { for(int i = 0; i < 10; i ++) {
out.println("hello " + i); out.println("hello " + i);
String str = in.readLine(); String str = in.readLine();
System.out.println(str); System.out.println("client Message : " + str);
} }
out.println("END"); out.println("END");
} catch (IOException e) {
throw new RuntimeException(e);
} }
} }
} }

View File

@ -1,15 +1,12 @@
// network/MultiSimpleClient.java // network/SimpleClient2.java
// (c)2016 MindView LLC: see Copyright.txt // (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Testing MultiSimpleServer with multiple clients.
// {ValidateByHand}
package network; package network;
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import onjava.*;
class SimpleClientThread implements Runnable { public class SimpleClient2 implements Runnable {
private InetAddress address; private InetAddress address;
private static int counter = 0; private static int counter = 0;
private int id = counter++; private int id = counter++;
@ -17,7 +14,7 @@ class SimpleClientThread implements Runnable {
public static int threadCount() { public static int threadCount() {
return threadcount; return threadcount;
} }
public SimpleClientThread(InetAddress address) { public SimpleClient2(InetAddress address) {
System.out.println("Making client " + id); System.out.println("Making client " + id);
this.address = address; this.address = address;
threadcount++; threadcount++;
@ -26,7 +23,7 @@ class SimpleClientThread implements Runnable {
public void run() { public void run() {
try ( try (
Socket socket = Socket socket =
new Socket(address, MultiSimpleServer.PORT); new Socket(address, ServeOne.PORT);
BufferedReader in = BufferedReader in =
new BufferedReader( new BufferedReader(
new InputStreamReader( new InputStreamReader(
@ -51,18 +48,3 @@ class SimpleClientThread implements Runnable {
} }
} }
} }
public class MultiSimpleClient {
static final int MAX_THREADS = 40;
public static void
main(String[] args) throws IOException,
InterruptedException {
new TimedAbort(5); // Terminate after 5 seconds
InetAddress address = InetAddress.getByName(null);
while(true) {
if(SimpleClientThread.threadCount() < MAX_THREADS)
new SimpleClientThread(address);
Thread.sleep(100);
}
}
}

View File

@ -3,16 +3,15 @@
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Echoes what the client sends. // Echoes what the client sends.
// {ValidateByHand}
package network; package network;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
public class SimpleServer { public class SimpleServer implements Runnable {
// Choose a port outside of the range 1-1024: // Choose a port outside of the range 1-1024:
public static final int PORT = 8080; public static final int PORT = 8080;
public static void
main(String[] args) throws IOException { public void run() {
try ( try (
ServerSocket s = new ServerSocket(PORT); ServerSocket s = new ServerSocket(PORT);
// Blocks until a connection occurs: // Blocks until a connection occurs:
@ -29,12 +28,17 @@ public class SimpleServer {
socket.getOutputStream())), true) socket.getOutputStream())), true)
) { ) {
System.out.println("Connection: " + socket); System.out.println("Connection: " + socket);
while (true) { in.lines().anyMatch(message->{
String str = in.readLine(); if (message.equals("END")) {
if(str.equals("END")) break; System.out.println("Received END. Closing Socket.");
System.out.println("Echoing: " + str); return true;
out.println(str); }
} System.out.println("Server Response: " + message);
out.println(message);
return false;
});
} catch (IOException e) {
throw new RuntimeException(e);
} }
} }
} }

View File

@ -0,0 +1,21 @@
// network/tests/ChatterTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class ChatterTest {
@BeforeAll
static void startMsg() {
System.out.println(">>> ChatterTest");
}
@Test
void chatterTest() throws Exception {
// <* These need to be handed to an executor: *>
new ChatterServer();
new ChatterClient(InetAddress.getLocalHost());
// No exceptions means success
}
}

View File

@ -0,0 +1,26 @@
// network/tests/MultiTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class MultiTest {
@BeforeAll
static void startMsg() {
System.out.println(">>> MultiClientTest");
}
@Test
void multiTest() throws Exception {
final int MAX_THREADS = 40;
new MultiServer();
InetAddress address = InetAddress.getByName(null);
while(true) {
if(SimpleClient2.threadCount() < MAX_THREADS)
new SimpleClient2(address);
Thread.sleep(100);
}
// No exceptions mean success
}
}

View File

@ -1,45 +0,0 @@
// network/tests/SimpleTcpTests.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.util.*;
import java.util.stream.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import onjava.*;
public class SimpleTcpTests {
@BeforeAll
static void startMsg() {
System.out.println(">>> Network Tests <<<");
}
@BeforeEach
void setupServer () { }
@Test
void basicTest() throws Exception {
SimpleServer server = new SimpleServer();
SimpleClient client = new SimpleClient();
client.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
@Test
void multiTest() throws Exception {
MultiSimpleClient client = new MultiSimpleClient();
MultiSimpleServer server = new MultiSimpleServer();
client.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
@Test
void chatterTest() throws Exception {
ChatterServer server = new ChatterServer();
ChatterClient.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
}

View File

@ -0,0 +1,20 @@
// network/tests/TestSimpleServerClient.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class TestSimpleServerClient {
@BeforeAll
static void startMsg() {
System.out.println(">>> TestSimpleServerClient");
}
@Test
void basicTest() throws Exception {
SimpleServer server = new SimpleServer();
SimpleClient client = new SimpleClient(InetAddress.getLocalHost());
// Success if no exceptions happen
}
}

View File

@ -12,13 +12,17 @@ public class BufferToText {
private static final int BSIZE = 1024; private static final int BSIZE = 1024;
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
try(FileChannel fc = new FileOutputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap("Some text".getBytes())); fc.write(ByteBuffer.wrap("Some text".getBytes()));
} }
ByteBuffer buff = ByteBuffer.allocate(BSIZE); ByteBuffer buff = ByteBuffer.allocate(BSIZE);
try(FileChannel fc = new FileInputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff); fc.read(buff);
} }
buff.flip(); buff.flip();
@ -30,15 +34,19 @@ public class BufferToText {
System.out.println("Decoded using " + encoding + ": " System.out.println("Decoded using " + encoding + ": "
+ Charset.forName(encoding).decode(buff)); + Charset.forName(encoding).decode(buff));
// Or, we could encode with something that prints: // Or, we could encode with something that prints:
try(FileChannel fc = new FileOutputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap( fc.write(ByteBuffer.wrap(
"Some text".getBytes("UTF-16BE"))); "Some text".getBytes("UTF-16BE")));
} }
// Now try reading again: // Now try reading again:
buff.clear(); buff.clear();
try(FileChannel fc = new FileInputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff); fc.read(buff);
} }
buff.flip(); buff.flip();
@ -46,14 +54,18 @@ public class BufferToText {
// Use a CharBuffer to write through: // Use a CharBuffer to write through:
buff = ByteBuffer.allocate(24); // More than needed buff = ByteBuffer.allocate(24); // More than needed
buff.asCharBuffer().put("Some text"); buff.asCharBuffer().put("Some text");
try(FileChannel fc = new FileOutputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(buff); fc.write(buff);
} }
// Read and display: // Read and display:
buff.clear(); buff.clear();
try(FileChannel fc = new FileInputStream( try(
"data2.txt").getChannel()) { FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff); fc.read(buff);
} }
buff.flip(); buff.flip();

View File

@ -17,10 +17,12 @@ public class ChannelCopy {
"arguments: sourcefile destfile"); "arguments: sourcefile destfile");
System.exit(1); System.exit(1);
} }
try(FileChannel in = new FileInputStream( try(
FileChannel in = new FileInputStream(
args[0]).getChannel(); args[0]).getChannel();
FileChannel out = new FileOutputStream( FileChannel out = new FileOutputStream(
args[1]).getChannel()) { args[1]).getChannel()
) {
ByteBuffer buffer = ByteBuffer.allocate(BSIZE); ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while(in.read(buffer) != -1) { while(in.read(buffer) != -1) {
buffer.flip(); // Prepare for writing buffer.flip(); // Prepare for writing

View File

@ -9,9 +9,11 @@ import java.io.*;
public class FileLocking { public class FileLocking {
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
try(FileOutputStream fos = try(
FileOutputStream fos =
new FileOutputStream("file.txt"); new FileOutputStream("file.txt");
FileLock fl = fos.getChannel().tryLock()) { FileLock fl = fos.getChannel().tryLock()
) {
if(fl != null) { if(fl != null) {
System.out.println("Locked File"); System.out.println("Locked File");
TimeUnit.MILLISECONDS.sleep(100); TimeUnit.MILLISECONDS.sleep(100);

View File

@ -11,8 +11,10 @@ public class LargeMappedFiles {
static int length = 0x8000000; // 128 MB static int length = 0x8000000; // 128 MB
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
try(RandomAccessFile tdat = try(
new RandomAccessFile("test.dat", "rw")) { RandomAccessFile tdat =
new RandomAccessFile("test.dat", "rw")
) {
MappedByteBuffer out = tdat.getChannel() MappedByteBuffer out = tdat.getChannel()
.map(FileChannel.MapMode.READ_WRITE, 0, length); .map(FileChannel.MapMode.READ_WRITE, 0, length);
for(int i = 0; i < length; i++) for(int i = 0; i < length; i++)

View File

@ -15,10 +15,12 @@ public class TransferTo {
"arguments: sourcefile destfile"); "arguments: sourcefile destfile");
System.exit(1); System.exit(1);
} }
try(FileChannel in = new FileInputStream( try(
FileChannel in = new FileInputStream(
args[0]).getChannel(); args[0]).getChannel();
FileChannel out = new FileOutputStream( FileChannel out = new FileOutputStream(
args[1]).getChannel()) { args[1]).getChannel()
) {
in.transferTo(0, in.size(), out); in.transferTo(0, in.size(), out);
// Or: // Or:
// out.transferFrom(in, 0, in.size()); // out.transferFrom(in, 0, in.size());

View File

@ -13,11 +13,13 @@ public class OSExecute {
try { try {
Process process = Process process =
new ProcessBuilder(command.split(" ")).start(); new ProcessBuilder(command.split(" ")).start();
try(BufferedReader results = new BufferedReader( try(
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream())); new InputStreamReader(process.getInputStream()));
BufferedReader errors = new BufferedReader( BufferedReader errors = new BufferedReader(
new InputStreamReader( new InputStreamReader(
process.getErrorStream()))) { process.getErrorStream()))
) {
String s; String s;
while((s = results.readLine())!= null) while((s = results.readLine())!= null)
System.out.println(s); System.out.println(s);

View File

@ -47,18 +47,22 @@ public class Compete {
for(int i = 0; i < SIZE; i++) for(int i = 0; i < SIZE; i++)
b[i] = new Thing4(); b[i] = new Thing4();
long t1 = System.currentTimeMillis(); long t1 = System.currentTimeMillis();
try(ByteArrayOutputStream buf = try(
ByteArrayOutputStream buf =
new ByteArrayOutputStream(); new ByteArrayOutputStream();
ObjectOutputStream oos = ObjectOutputStream oos =
new ObjectOutputStream(buf)) { new ObjectOutputStream(buf)
) {
for(Thing2 a1 : a) { for(Thing2 a1 : a) {
oos.writeObject(a1); oos.writeObject(a1);
} }
// Now get copies: // Now get copies:
try(ObjectInputStream in = try(
ObjectInputStream in =
new ObjectInputStream( new ObjectInputStream(
new ByteArrayInputStream( new ByteArrayInputStream(
buf.toByteArray()))) { buf.toByteArray()))
) {
Thing2[] c = new Thing2[SIZE]; Thing2[] c = new Thing2[SIZE];
for(int i = 0; i < SIZE; i++) for(int i = 0; i < SIZE; i++)
c[i] = (Thing2)in.readObject(); c[i] = (Thing2)in.readObject();

View File

@ -87,9 +87,11 @@ public class AStoreCADState {
for(int i = 0; i < 10; i++) for(int i = 0; i < 10; i++)
((Shape)shapes.get(i)).setColor(Shape.GREEN); ((Shape)shapes.get(i)).setColor(Shape.GREEN);
// Save the state vector: // Save the state vector:
try(ObjectOutputStream out = try(
ObjectOutputStream out =
new ObjectOutputStream( new ObjectOutputStream(
new FileOutputStream("CADState.dat"))) { new FileOutputStream("CADState.dat"))
) {
out.writeObject(shapeTypes); out.writeObject(shapeTypes);
Line.serializeStaticState(out); Line.serializeStaticState(out);
out.writeObject(shapes); out.writeObject(shapes);

View File

@ -42,15 +42,19 @@ public class Blip3 implements Externalizable {
System.out.println("Constructing objects:"); System.out.println("Constructing objects:");
Blip3 b3 = new Blip3("A String ", 47); Blip3 b3 = new Blip3("A String ", 47);
System.out.println(b3); System.out.println(b3);
try(ObjectOutputStream o = new ObjectOutputStream( try(
new FileOutputStream("Blip3.serialized"))) { ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blip3.serialized"))
) {
System.out.println("Saving object:"); System.out.println("Saving object:");
o.writeObject(b3); o.writeObject(b3);
} }
// Now get it back: // Now get it back:
System.out.println("Recovering b3:"); System.out.println("Recovering b3:");
try(ObjectInputStream in = new ObjectInputStream( try(
new FileInputStream("Blip3.serialized"))) { ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blip3.serialized"))
) {
b3 = (Blip3)in.readObject(); b3 = (Blip3)in.readObject();
} }
System.out.println(b3); System.out.println(b3);

View File

@ -44,16 +44,20 @@ public class Blips {
System.out.println("Constructing objects:"); System.out.println("Constructing objects:");
Blip1 b1 = new Blip1(); Blip1 b1 = new Blip1();
Blip2 b2 = new Blip2(); Blip2 b2 = new Blip2();
try(ObjectOutputStream o = new ObjectOutputStream( try(
new FileOutputStream("Blips.serialized"))) { ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blips.serialized"))
) {
System.out.println("Saving objects:"); System.out.println("Saving objects:");
o.writeObject(b1); o.writeObject(b1);
o.writeObject(b2); o.writeObject(b2);
} }
// Now get them back: // Now get them back:
System.out.println("Recovering b1:"); System.out.println("Recovering b1:");
try(ObjectInputStream in = new ObjectInputStream( try(
new FileInputStream("Blips.serialized"))) { ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.serialized"))
) {
b1 = (Blip1)in.readObject(); b1 = (Blip1)in.readObject();
} }
// OOPS! Throws an exception: // OOPS! Throws an exception:

View File

@ -24,14 +24,18 @@ public class Logon implements Serializable {
main(String[] args) throws Exception { main(String[] args) throws Exception {
Logon a = new Logon("Hulk", "myLittlePony"); Logon a = new Logon("Hulk", "myLittlePony");
System.out.println("logon a = " + a); System.out.println("logon a = " + a);
try(ObjectOutputStream o = new ObjectOutputStream( try(
new FileOutputStream("Logon.dat"))) { ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Logon.dat"))
) {
o.writeObject(a); o.writeObject(a);
} }
TimeUnit.SECONDS.sleep(1); // Delay TimeUnit.SECONDS.sleep(1); // Delay
// Now get them back: // Now get them back:
try(ObjectInputStream in = new ObjectInputStream( try(
new FileInputStream("Logon.dat"))) { ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Logon.dat"))
) {
System.out.println( System.out.println(
"Recovering object at " + new Date()); "Recovering object at " + new Date());
a = (Logon)in.readObject(); a = (Logon)in.readObject();

View File

@ -31,27 +31,33 @@ public class MyWorld {
animals.add(new Animal("Ralph the hamster", house)); animals.add(new Animal("Ralph the hamster", house));
animals.add(new Animal("Molly the cat", house)); animals.add(new Animal("Molly the cat", house));
System.out.println("animals: " + animals); System.out.println("animals: " + animals);
try(ByteArrayOutputStream buf1 = try(
ByteArrayOutputStream buf1 =
new ByteArrayOutputStream(); new ByteArrayOutputStream();
ObjectOutputStream o1 = ObjectOutputStream o1 =
new ObjectOutputStream(buf1)) { new ObjectOutputStream(buf1)
) {
o1.writeObject(animals); o1.writeObject(animals);
o1.writeObject(animals); // Write a 2nd set o1.writeObject(animals); // Write a 2nd set
// Write to a different stream: // Write to a different stream:
try(ByteArrayOutputStream buf2 = try(
ByteArrayOutputStream buf2 =
new ByteArrayOutputStream(); new ByteArrayOutputStream();
ObjectOutputStream o2 = ObjectOutputStream o2 =
new ObjectOutputStream(buf2)) { new ObjectOutputStream(buf2)
) {
o2.writeObject(animals); o2.writeObject(animals);
// Now get them back: // Now get them back:
try(ObjectInputStream in1 = try(
ObjectInputStream in1 =
new ObjectInputStream( new ObjectInputStream(
new ByteArrayInputStream( new ByteArrayInputStream(
buf1.toByteArray())); buf1.toByteArray()));
ObjectInputStream in2 = ObjectInputStream in2 =
new ObjectInputStream( new ObjectInputStream(
new ByteArrayInputStream( new ByteArrayInputStream(
buf2.toByteArray()))) { buf2.toByteArray()))
) {
List List
animals1 = (List)in1.readObject(), animals1 = (List)in1.readObject(),
animals2 = (List)in1.readObject(), animals2 = (List)in1.readObject(),

View File

@ -11,9 +11,11 @@ public class RecoverCADState {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
try(ObjectInputStream in = try(
ObjectInputStream in =
new ObjectInputStream( new ObjectInputStream(
new FileInputStream("CADState.dat"))) { new FileInputStream("CADState.dat"))
) {
// Read in the same order they were written: // Read in the same order they were written:
List<Class<? extends Shape>> shapeTypes = List<Class<? extends Shape>> shapeTypes =
(List<Class<? extends Shape>>)in.readObject(); (List<Class<? extends Shape>>)in.readObject();

View File

@ -51,27 +51,35 @@ public class Worm implements Serializable {
IOException { IOException {
Worm w = new Worm(6, 'a'); Worm w = new Worm(6, 'a');
System.out.println("w = " + w); System.out.println("w = " + w);
try(ObjectOutputStream out = new ObjectOutputStream( try(
new FileOutputStream("worm.dat"))) { ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("worm.dat"))
) {
out.writeObject("Worm storage\n"); out.writeObject("Worm storage\n");
out.writeObject(w); out.writeObject(w);
} }
try(ObjectInputStream in = new ObjectInputStream( try(
new FileInputStream("worm.dat"))) { ObjectInputStream in = new ObjectInputStream(
new FileInputStream("worm.dat"))
) {
String s = (String)in.readObject(); String s = (String)in.readObject();
Worm w2 = (Worm)in.readObject(); Worm w2 = (Worm)in.readObject();
System.out.println(s + "w2 = " + w2); System.out.println(s + "w2 = " + w2);
} }
try(ByteArrayOutputStream bout = try(
ByteArrayOutputStream bout =
new ByteArrayOutputStream(); new ByteArrayOutputStream();
ObjectOutputStream out2 = ObjectOutputStream out2 =
new ObjectOutputStream(bout)) { new ObjectOutputStream(bout)
) {
out2.writeObject("Worm storage\n"); out2.writeObject("Worm storage\n");
out2.writeObject(w); out2.writeObject(w);
out2.flush(); out2.flush();
try(ObjectInputStream in2 = new ObjectInputStream( try(
ObjectInputStream in2 = new ObjectInputStream(
new ByteArrayInputStream( new ByteArrayInputStream(
bout.toByteArray()))) { bout.toByteArray()))
) {
String s = (String)in2.readObject(); String s = (String)in2.readObject();
Worm w3 = (Worm)in2.readObject(); Worm w3 = (Worm)in2.readObject();
System.out.println(s + "w3 = " + w3); System.out.println(s + "w3 = " + w3);

View File

@ -9,11 +9,13 @@ public class Redirecting {
public static void public static void
main(String[] args) throws IOException { main(String[] args) throws IOException {
PrintStream console = System.out; PrintStream console = System.out;
try(BufferedInputStream in = new BufferedInputStream( try(
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java")); new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream( PrintStream out = new PrintStream(
new BufferedOutputStream( new BufferedOutputStream(
new FileOutputStream("Redirecting.txt")))) { new FileOutputStream("Redirecting.txt")))
) {
System.setIn(in); System.setIn(in);
System.setOut(out); System.setOut(out);
System.setErr(out); System.setErr(out);

View File

@ -75,3 +75,27 @@ public class CountedListTest {
"An", "African", "Swallow" }); "An", "African", "Swallow" });
} }
} }
/* Output:
>>> Starting CountedListTest
CountedList #0
Set up for 0
Running testRemove()
Cleaning up 0
CountedList #1
Set up for 1
Running testReplace()
Cleaning up 1
CountedList #2
Set up for 2
Running testAddAll()
Cleaning up 2
CountedList #3
Set up for 3
Running testInsert()
Cleaning up 3
CountedList #4
Set up for 4
Running testOrder()
Cleaning up 4
>>> Finished CountedListTest
*/