edits & improvements

This commit is contained in:
Bruce Eckel 2016-08-31 12:30:03 -06:00
parent ea67cacd65
commit c497c389e3
11 changed files with 198 additions and 62 deletions

View File

@ -4,7 +4,7 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// {ValidateByHand}
// Tests the ChatterServer by starting multiple
// clients, each of which sends datagrams
// clients, each of which sends datagrams.
import java.net.*;
import java.io.*;
import onjava.*;
@ -37,12 +37,11 @@ public class ChatterClient extends Thread {
public void sendAndEcho(String msg) {
try {
// Make and send a datagram:
s.send(Dgram.toDatagram(msg,
hostAddress,
ChatterServer.INPORT));
s.send(Dgram.toDatagram(
msg, hostAddress, ChatterServer.INPORT));
// Block until it echoes back:
s.receive(dp);
// Print out the echoed contents:
// Display the echoed contents:
String rcvd = "Client #" + id +
", rcvd from " +
dp.getAddress() + ", " +

View File

@ -31,7 +31,7 @@ public class ChatterServer {
"Echoed: " + rcvd;
// Extract the address and port from the
// received datagram to find out where to
// send it back:
// send it back to:
DatagramPacket echo =
Dgram.toDatagram(echoString,
dp.getAddress(), dp.getPort());

View File

@ -2,8 +2,7 @@
// (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.
// Converts back and forth
// between Strings and DataGramPackets
// Converts between Strings and DataGramPackets
import java.net.*;
public class Dgram {

View File

@ -46,7 +46,9 @@ class SimpleClientThread extends Thread {
// constructor:
try {
socket.close();
} catch(IOException e2) {}
} catch(IOException e2) {
throw new RuntimeException(e2);
}
}
// Otherwise the socket will be closed by
// the run() method of the thread.
@ -61,11 +63,14 @@ class SimpleClientThread extends Thread {
}
out.println("END");
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
// Always close it:
try {
socket.close();
} catch(IOException e) {}
} catch(IOException e) {
throw new RuntimeException(e);
}
threadcount--; // Ending this thread
}
}
@ -77,11 +82,9 @@ public class MultiSimpleClient {
main(String[] args) throws IOException,
InterruptedException {
new TimedAbort(5); // Terminate after 5 seconds
InetAddress addr =
InetAddress.getByName(null);
InetAddress addr = InetAddress.getByName(null);
while(true) {
if(SimpleClientThread.threadCount()
< MAX_THREADS)
if(SimpleClientThread.threadCount() < MAX_THREADS)
new SimpleClientThread(addr);
Thread.sleep(100);
}

View File

@ -2,7 +2,7 @@
// (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.
// Uses multithreading to handle any number of clients
// Uses threads to handle any number of clients
// {ValidateByHand}
import java.io.*;
import java.net.*;
@ -25,10 +25,9 @@ class ServeOneSimple extends Thread {
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
// If any of the above calls throw an
// exception, the caller is responsible for
// closing the socket. Otherwise the thread
// will close it.
// If any of the above calls throw an exception,
// the caller is responsible for closing the
// socket. Otherwise the thread closes it.
start(); // Calls run()
}
@Override
@ -42,10 +41,13 @@ class ServeOneSimple extends Thread {
}
System.out.println("closing...");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
socket.close();
} catch(IOException e) {}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}

View File

@ -2,8 +2,7 @@
// (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.
// A List that keeps track of how many
// of itself are created.
// Keeps track of how many of itself are created.
package validating;
import java.util.*;

View File

@ -10,6 +10,14 @@ import static org.junit.jupiter.api.Assertions.*;
public class CountedListTest {
private CountedList list;
@BeforeAll
static void beforeAllMsg() {
System.out.println(">>> Starting CountedListTest");
}
@AfterAll
static void afterAllMsg() {
System.out.println(">>> Finished CountedListTest");
}
@BeforeEach
public void initialize() {
list = new CountedList();
@ -21,7 +29,6 @@ public class CountedListTest {
public void cleanup() {
System.out.println("Cleaning up " + list.getId());
}
// All tests are marked with the @Test annotation:
@Test
public void insert() {
System.out.println("Running testInsert()");
@ -38,16 +45,12 @@ public class CountedListTest {
assertEquals(list.size(), 3);
assertEquals(list.get(1), "Replace");
}
// A helper method to reduce code duplication. As long
// as it isn't annotated with @Test, it will not
// be automatically executed by JUnit.
// A helper method to simplify the code. As
// long as it isn't annotated with @Test, it will
// not be automatically executed by JUnit.
private
void compare(List<String> lst, String[] strs) {
String[] array = lst.toArray(new String[0]);
assertTrue(array.length == strs.length,
"Arrays not the same length");
for(int i = 0; i < array.length; i++)
assertEquals(strs[i], array[i]);
assertArrayEquals(lst.toArray(new String[0]), strs);
}
@Test
public void order() {
@ -72,15 +75,3 @@ public class CountedListTest {
"An", "African", "Swallow" });
}
}
/* Output:
CountedList #0
Running testAddAll()
CountedList #1
Running testInsert()
CountedList #2
Running testRemove()
CountedList #3
Running testOrder()
CountedList #4
Running testReplace()
*/

View File

@ -22,13 +22,14 @@ class DynamicStringInverterTests {
inverter -> inverter.getClass().getSimpleName(),
inverter -> {
System.out.println(
inverter.getClass().getSimpleName() + ": " + id
);
inverter.getClass().getSimpleName() +
": " + id);
try {
if(test.apply(inverter) != "fail")
System.out.println("Success");
} catch(Exception | Error e) {
System.out.println("Exception: " + e.getMessage());
System.out.println(
"Exception: " + e.getMessage());
}
}
);

View File

@ -1,15 +0,0 @@
// validating/FirstJUnit5Tests.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 validating;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class FirstJUnit5Tests {
@Test
void myFirstTest() {
System.out.println("FirstJUnit5Tests");
assertEquals(2, 1 + 1);
}
}

View File

@ -0,0 +1,48 @@
// validating/GuavaAssertions.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.
// Assertions that are always enabled.
import com.google.common.base.*;
import static com.google.common.base.Verify.*;
public class GuavaAssertions {
public static void main(String[] args) {
verify(2 + 2 == 4);
try {
verify(1 + 2 == 4);
} catch(VerifyException e) {
System.out.println(e);
}
try {
verify(1 + 2 == 4, "Bad math");
} catch(VerifyException e) {
System.out.println(e.getMessage());
}
try {
verify(1 + 2 == 4, "Bad math: %s", "not 4");
} catch(VerifyException e) {
System.out.println(e.getMessage());
}
String s = "";
s = verifyNotNull(s);
s = null;
try {
verifyNotNull(s);
} catch(VerifyException e) {
System.out.println(e.getMessage());
}
try {
verifyNotNull(s, "Shouldn't be null: %s", "arg s");
} catch(VerifyException e) {
System.out.println(e.getMessage());
}
}
}
/* Output:
com.google.common.base.VerifyException
Bad math
Bad math: not 4
expected a non-null reference
Shouldn't be null: arg s
*/

View File

@ -3,12 +3,121 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Demonstrating Guava Preconditions
import java.util.function.*;
import static com.google.common.base.Preconditions.*;
public class GuavaPreconditions {
void g(String s) {
checkState(s.length() > 6);
System.out.println("Success: " + s);
}
static void test(Consumer<String> c, String s) {
try {
System.out.println(s);
c.accept(s);
System.out.println("Success");
} catch(Exception e) {
String type = e.getClass().getSimpleName();
String msg = e.getMessage();
System.out.println(type +
(msg == null ? "" : ": " + msg));
}
}
public static void main(String[] args) {
test((s) -> s = checkNotNull(s), "X");
test((s) -> s = checkNotNull(s), null);
test((s) -> s = checkNotNull(s, "s was null"), null);
test((s) -> s = checkNotNull(
s, "s was null, %s %s", "arg2", "arg3"), null);
test((s) -> checkArgument(s == "Fozzie"), "Fozzie");
test((s) -> checkArgument(s == "Fozzie"), "X");
test((s) -> checkArgument(s == "Fozzie"), null);
test((s) -> checkArgument(
s == "Fozzie", "Bear Left!"), null);
test((s) -> checkArgument(
s == "Fozzie", "Bear Left! %s Right!", "Frog"),
null);
test((s) -> checkState(s.length() > 6), "Mortimer");
test((s) -> checkState(s.length() > 6), "Mort");
test((s) -> checkState(s.length() > 6), null);
test((s) ->
checkElementIndex(6, s.length()), "Robert");
test((s) ->
checkElementIndex(6, s.length()), "Bob");
test((s) ->
checkElementIndex(6, s.length()), null);
test((s) ->
checkPositionIndex(6, s.length()), "Robert");
test((s) ->
checkPositionIndex(6, s.length()), "Bob");
test((s) ->
checkPositionIndex(6, s.length()), null);
test((s) -> checkPositionIndexes(
0, 6, s.length()), "Hieronymus");
test((s) -> checkPositionIndexes(
0, 10, s.length()), "Hieronymus");
test((s) -> checkPositionIndexes(
0, 11, s.length()), "Hieronymus");
test((s) -> checkPositionIndexes(
-1, 6, s.length()), "Hieronymus");
test((s) -> checkPositionIndexes(
7, 6, s.length()), "Hieronymus");
test((s) -> checkPositionIndexes(
0, 6, s.length()), null);
}
}
/* Output:
X
Success
null
NullPointerException
null
NullPointerException: s was null
null
NullPointerException: s was null, arg2 arg3
Fozzie
Success
X
IllegalArgumentException
null
IllegalArgumentException
null
IllegalArgumentException: Bear Left!
null
IllegalArgumentException: Bear Left! Frog Right!
Mortimer
Success
Mort
IllegalStateException
null
NullPointerException
Robert
IndexOutOfBoundsException: index (6) must be less than size (6)
Bob
IndexOutOfBoundsException: index (6) must be less than size (3)
null
NullPointerException
Robert
Success
Bob
IndexOutOfBoundsException: index (6) must not be greater than size (3)
null
NullPointerException
Hieronymus
Success
Hieronymus
Success
Hieronymus
IndexOutOfBoundsException: end index (11) must not be greater than size (10)
Hieronymus
IndexOutOfBoundsException: start index (-1) must not be negative
Hieronymus
IndexOutOfBoundsException: end index (6) must not be less than start index (7)
null
NullPointerException
*/