This commit is contained in:
Bruce Eckel 2015-05-18 23:05:20 -07:00
parent 94eeca2359
commit 88dbdbbbcb
291 changed files with 1440 additions and 685 deletions

View File

@ -4,6 +4,7 @@
<property name="chapter" value="access"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="Cake" />

View File

@ -1,5 +1,5 @@
//: annotations/ExtractInterface.java
// APT-based annotation processing.
// javac-based annotation processing.
package annotations;
import java.lang.annotation.*;

View File

@ -0,0 +1,68 @@
//: annotations/IfaceExtractorProcessor.java
// javac-based annotation processing.
package annotations;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import java.util.*;
import java.io.*;
@SupportedAnnotationTypes(
"annotations.ExtractInterface")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class IfaceExtractorProcessor
extends AbstractProcessor {
private ArrayList<Element>
interfaceMethods = new ArrayList<>();
private ProcessingEnvironment processingEnv;
@Override public void
init(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override public boolean
process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(Element elem :
env.getElementsAnnotatedWith(ExtractInterface.class)) {
if(elem.getModifiers().contains(Modifier.PUBLIC) &&
!(elem.getModifiers().contains(Modifier.STATIC)))
interfaceMethods.add(elem);
if(interfaceMethods.size() > 0) {
for(Element el : interfaceMethods)
System.out.println(el.getKind() +
" : " + el.getModifiers() +
" : " + el.getSimpleName() +
" : " + el.asType());
try {
try(Writer writer =
processingEnv.getFiler()
.createSourceFile("Filename.txt")
.openWriter()) {
/* writer.write("package " +
typeDecl.getPackage().getQualifiedName() +";");
writer.write("public interface " +
annot.value() + " {");
for(MethodDeclaration m : interfaceMethods) {
writer.print(" public ");
writer.print(m.getReturnType() + " ");
writer.print(m.getSimpleName() + " (");
int i = 0;
for(ParameterDeclaration parm :
m.getParameters()) {
writer.print(parm.getType() + " " +
parm.getSimpleName());
if(++i < m.getParameters().size())
writer.print(", ");
}
writer.write(");");
}
*/ writer.write("}");
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
return false;
}
} ///:~

View File

@ -1,5 +1,5 @@
//: annotations/Multiplier.java
// APT-based annotation processing.
// javac-based annotation processing.
package annotations;
@ExtractInterface("IMultiplier")

View File

@ -2,8 +2,9 @@
<project default="run">
<property name="chapter" value="annotations"/>
<property name="excludedfiles" value="InterfaceExtractorProcessor.java InterfaceExtractorProcessorFactory.java database/TableCreationProcessorFactory.java"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="annotations.AtUnitComposition" dirpath="../annotations" />
@ -18,6 +19,7 @@
<jrun cls="annotations.StackLStringTest" dirpath="../annotations" />
<jrun cls="UseCaseTracker" />
<jrun cls="annotations.database.TableCreator" dirpath="../annotations/database" arguments="annotations.database.Member" />
<jrun cls="annotations.simplest.SimpleTest" dirpath="../annotations/simplest" />
</target>
</project>

View File

@ -0,0 +1,17 @@
//: annotations/simplest/Simple.java
// A bare-bones annotation.
package annotations.simplest;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE, ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE, ElementType.FIELD,
ElementType.LOCAL_VARIABLE})
public @interface Simple {
String value() default "-default-";
} ///:~

View File

@ -0,0 +1,28 @@
//: annotations/simplest/SimpleProcessor.java
// A bare-bones annotation processor.
package annotations.simplest;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import java.util.*;
@SupportedAnnotationTypes(
"annotations.simplest.Simple")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SimpleProcessor
extends AbstractProcessor {
@Override public boolean
process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(TypeElement t : annotations)
System.out.println(t);
for(Element el :
env.getElementsAnnotatedWith(Simple.class)){
System.out.println(el.getKind() +
" : " + el.getModifiers() +
" : " + el.getSimpleName() +
" : " + el.asType());
}
return false;
}
} ///:~

View File

@ -0,0 +1,21 @@
//: annotations/simplest/SimpleTest.java
// Test the "Simple" annotation
package annotations.simplest;
@Simple
public class SimpleTest {
@Simple
int i;
@Simple
public SimpleTest() {}
@Simple
public void foo() {
System.out.println("SimpleTest.foo()");
}
@Simple
public static void main(String[] args) {
@Simple
SimpleTest st = new SimpleTest();
st.foo();
}
} ///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="arrays"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AlphabeticSearch" />

View File

@ -1,6 +1,5 @@
//: assertions/Assert1.java
// Non-informative style of assert
// Compile with: javac -source 1.4 Assert1.java
// {JVMArgs: -ea} // Must run with -ea
// {ThrowsException}

View File

@ -1,6 +1,5 @@
//: assertions/LoaderAssertions.java
// Using the class loader to enable assertions
// Compile with: javac -source 1.4 LoaderAssertions.java
// {ThrowsException}
public class LoaderAssertions {

View File

@ -1,9 +1,12 @@
//: assertions/Queue.java
// Demonstration of Design by Contract (DBC) combined
// with white-box unit testing.
// {Depends: junit.jar}
import junit.framework.*;
// (Install libraries from www.junit.org)
import java.util.*;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class Queue {
private Object[] data;
@ -86,11 +89,10 @@ public class Queue {
}
// JUnit testing.
// As an inner class, this has access to privates:
public static class WhiteBoxTest extends TestCase {
public static class WhiteBoxTest {
private Queue queue = new Queue(10);
private int i = 0;
public WhiteBoxTest(String name) {
super(name);
public WhiteBoxTest() {
while(i < 5) // Preload with some data
queue.put("" + i++);
}
@ -106,7 +108,8 @@ public class Queue {
assertTrue(queue.empty());
System.out.println(queue.dump());
}
public void testFull() {
@Test
public void full() {
System.out.println("testFull");
System.out.println(queue.dump());
System.out.println(queue.get());
@ -123,7 +126,8 @@ public class Queue {
assertEquals(msg, "put() into full Queue");
showFullness();
}
public void testEmpty() {
@Test
public void empty() {
System.out.println("testEmpty");
while(!queue.empty())
System.out.println(queue.get());
@ -137,7 +141,8 @@ public class Queue {
assertEquals(msg, "get() from empty Queue");
showEmptiness();
}
public void testNullPut() {
@Test
public void nullPut() {
System.out.println("testNullPut");
String msg = "";
try {
@ -148,7 +153,8 @@ public class Queue {
}
assertEquals(msg, "put() null item");
}
public void testCircularity() {
@Test
public void circularity() {
System.out.println("testCircularity");
while(!queue.full())
queue.put("" + i++);
@ -167,6 +173,7 @@ public class Queue {
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(Queue.WhiteBoxTest.class);
org.junit.runner.JUnitCore.runClasses(
Queue.WhiteBoxTest.class);
}
} ///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="assertions"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="Assert1" failOnError='false' msg='* Exception was Expected *' />

View File

@ -61,7 +61,7 @@ public class ActiveObjectDemo {
}
d1.shutdown();
}
} /* Output: (85% match)
} /* Output: (85% Match)
All asynch calls made
starting 0.0 + 0.0
starting 0.2 + 0.2

View File

@ -7,7 +7,7 @@ public class BasicThreads {
t.start();
System.out.println("Waiting for LiftOff");
}
} /* Output: (90% match)
} /* Output: (90% Match)
Waiting for LiftOff
#0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!),
*///:~

View File

@ -41,7 +41,7 @@ public class CaptureUncaughtException {
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
} /* Output: (90% match)
} /* Output: (90% Match)
HandlerThreadFactory@de6ced creating new Thread
created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3

View File

@ -25,7 +25,7 @@ public class CloseResource {
print("Closing " + System.in.getClass().getName());
System.in.close(); // Releases blocked thread
}
} /* Output: (85% match)
} /* Output: (85% Match)
Waiting for read():
Waiting for read():
Shutting down all threads

View File

@ -1,7 +1,7 @@
//: concurrency/ExchangerDemo.java
import java.util.concurrent.*;
import java.util.*;
import net.mindview.util.*;
import java.util.*;
class ExchangerProducer<T> implements Runnable {
private Generator<T> generator;

View File

@ -1,5 +1,6 @@
//: concurrency/HorseRace.java
// Using CyclicBarriers.
// {CheckOutputByHand}
import java.util.concurrent.*;
import java.util.*;
import static net.mindview.util.Print.*;

View File

@ -74,7 +74,7 @@ public class Interrupting {
print("Aborting with System.exit(0)");
System.exit(0); // ... since last 2 interrupts failed
}
} /* Output: (95% match)
} /* Output: (95% Match)
Interrupting SleepBlocked
InterruptedException
Exiting SleepBlocked.run()

View File

@ -53,7 +53,7 @@ public class PipedIO {
TimeUnit.SECONDS.sleep(4);
exec.shutdownNow();
}
} /* Output: (65% match)
} /* Output: (65% Match)
Read: A, Read: B, Read: C, Read: D, Read: E, Read: F, Read: G, Read: H, Read: I, Read: J, Read: K, Read: L, Read: M, java.lang.InterruptedException: sleep interrupted Sender sleep interrupted
java.io.InterruptedIOException Receiver read exception
*///:~

View File

@ -24,7 +24,7 @@ public class SimpleDaemons implements Runnable {
print("All daemons started");
TimeUnit.MILLISECONDS.sleep(175);
}
} /* Output: (Sample)
} /* Output: (First 11 Lines)
All daemons started
Thread[Thread-0,5,main] SimpleDaemons@530daa
Thread[Thread-1,5,main] SimpleDaemons@a62fc3

View File

@ -40,7 +40,7 @@ public class SimpleMicroBenchmark {
System.out.printf("Lock/synchronized = %1$.3f",
(double)lockTime/(double)synchTime);
}
} /* Output: (75% match)
} /* Output: (75% Match)
synchronized: 244919117
Lock: 939098964
Lock/synchronized = 3.834

View File

@ -36,7 +36,7 @@ public class SimplePriorities implements Runnable {
new SimplePriorities(Thread.MAX_PRIORITY));
exec.shutdown();
}
} /* Output: (70% match)
} /* Output: (First 10 Lines) (70% Match)
Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-6,10,main]: 4
Thread[pool-1-thread-6,10,main]: 3

View File

@ -167,42 +167,42 @@ public class SynchronizationComparisons {
}
Accumulator.exec.shutdown();
}
} /* Output: (Sample) using JDK6u10
} /* Output: (Sample)
Warmup
synch : 129868038
synch : 94513807
============================
Cycles : 50000
synch : 126407922
Lock : 51207369
Atomic : 141845223
synch/Lock : 2.47
synch/(Atomic-synch) : 8.19
synch : 94514234
Lock : 24976352
Atomic : 98296651
synch/Lock : 3.78
synch/(Atomic-synch) : 24.99
============================
Cycles : 100000
synch : 251174061
Lock : 105338114
Atomic : 279503250
synch/Lock : 2.38
synch/(Atomic-synch) : 8.87
synch : 178531353
Lock : 46007787
Atomic : 192372561
synch/Lock : 3.88
synch/(Atomic-synch) : 12.90
============================
Cycles : 200000
synch : 508778006
Lock : 214398402
Atomic : 574464795
synch/Lock : 2.37
synch/(Atomic-synch) : 7.75
synch : 377107591
Lock : 91051260
Atomic : 394509274
synch/Lock : 4.14
synch/(Atomic-synch) : 21.67
============================
Cycles : 400000
synch : 1027003521
Lock : 428342577
Atomic : 1115667617
synch/Lock : 2.40
synch/(Atomic-synch) : 11.58
synch : 722152518
Lock : 184968090
Atomic : 746950974
synch/Lock : 3.90
synch/(Atomic-synch) : 29.12
============================
Cycles : 800000
synch : 2179255097
Lock : 877216314
Atomic : 2371504710
synch/Lock : 2.48
synch/(Atomic-synch) : 11.34
synch : 1478348925
Lock : 416729956
Atomic : 1559738238
synch/Lock : 3.55
synch/(Atomic-synch) : 18.16
*///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="concurrency"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="ActiveObjectDemo" />

View File

@ -73,7 +73,7 @@ public class WaxOMatic {
TimeUnit.SECONDS.sleep(5); // Run for a while...
exec.shutdownNow(); // Interrupt all tasks
}
} /* Output: (95% match)
} /* Output: (95% Match)
Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt
Ending Wax On task
Exiting via interrupt

View File

@ -94,7 +94,7 @@ public class WaxOMatic2 {
TimeUnit.SECONDS.sleep(5);
exec.shutdownNow();
}
} /* Output: (90% match)
} /* Output: (90% Match)
Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt
Ending Wax Off task
Exiting via interrupt

View File

@ -44,7 +44,7 @@ public class Maps {
test(new ConcurrentHashMap<>());
test(new WeakHashMap<>());
}
} /* Output:
} /* Output: (First 11 Lines)
HashMap
Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 24]
Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, L0, M0, N0, O0, P0, R0, Q0, T0, S0, V0, U0, X0, W0, Y0]

View File

@ -4,6 +4,7 @@
<property name="chapter" value="containers"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AssociativeArray" />

View File

@ -9,7 +9,7 @@ public class ListCharacters {
System.out.println("value: " + (int)c +
" character: " + c);
}
} /* Output:
} /* Output: (First 10 Lines)
value: 97 character: a
value: 98 character: b
value: 99 character: c

View File

@ -23,7 +23,7 @@ public class VowelsAndConsonants {
}
}
}
} /* Output:
} /* Output: (First 13 Lines)
y, 121: Sometimes a vowel
n, 110: consonant
z, 122: consonant

View File

@ -4,6 +4,7 @@
<property name="chapter" value="control"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="BreakAndContinue" />

View File

@ -18,4 +18,13 @@ public class SimpleDebugging {
public static void main(String[] args) {
foo1();
}
} ///:~
} /* Output:
In foo1
In foo2
In foo3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at SimpleDebugging.foo3(SimpleDebugging.java:16)
at SimpleDebugging.foo2(SimpleDebugging.java:10)
at SimpleDebugging.foo1(SimpleDebugging.java:6)
at SimpleDebugging.main(SimpleDebugging.java:19)
*///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="debugging"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="SimpleDebugging" failOnError='false' msg='* Exception was Expected *' />

View File

@ -14,7 +14,7 @@ enum LikeClasses {
public class NotClasses {
// void f1(LikeClasses.WINKEN instance) {} // Nope
} /* Output:
} /* Output: (First 7 Lines)
Compiled from "NotClasses.java"
abstract class LikeClasses extends java.lang.Enum{
public static final LikeClasses WINKEN;

View File

@ -3,7 +3,6 @@
// {Args: VendingMachineInput.txt}
import java.util.*;
import net.mindview.util.*;
import static enumerated.Input.*;
import static net.mindview.util.Print.*;
enum Category {

View File

@ -4,6 +4,7 @@
<property name="chapter" value="enumerated"/>
<property name="excludedfiles" value="VendingMachine.java"/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="BigEnumSet" />

View File

@ -26,7 +26,7 @@ public class LoggingExceptions {
System.err.println("Caught " + e);
}
}
} /* Output: (85% match)
} /* Output: (85% Match)
Aug 30, 2005 4:02:31 PM LoggingException <init>
SEVERE: LoggingException
at LoggingExceptions.main(LoggingExceptions.java:19)

View File

@ -18,7 +18,7 @@ public class LoggingExceptions2 {
logException(e);
}
}
} /* Output: (90% match)
} /* Output: (90% Match)
Aug 30, 2005 4:07:54 PM LoggingExceptions2 logException
SEVERE: java.lang.NullPointerException
at LoggingExceptions2.main(LoggingExceptions2.java:16)

View File

@ -4,6 +4,7 @@
<property name="chapter" value="exceptions"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AlwaysFinally" />

View File

@ -9,7 +9,7 @@ public class ClassCasting {
new FileInputStream(args[0]));
// Won't Compile:
// List<Widget> lw1 =
// List<Widget>.class.cast(in.readObject());
// List<>.class.cast(in.readObject());
List<Widget> lw2 = List.class.cast(in.readObject());
}
} ///:~

View File

@ -14,7 +14,7 @@ class MixinProxy implements InvocationHandler {
String methodName = method.getName();
// The first interface in the map
// implements the method.
if (!delegatesByMethod.containsKey(methodName))
if(!delegatesByMethod.containsKey(methodName))
delegatesByMethod.put(methodName, pair.first);
}
}

View File

@ -4,5 +4,5 @@ import java.util.*;
public class NonCovariantGenerics {
// Compile Error: incompatible types:
List<Fruit> flist = new ArrayList<>();
List<Fruit> flist = new ArrayList<Apple>();
} ///:~

View File

@ -69,7 +69,7 @@ public class Store extends ArrayList<Aisle> {
public static void main(String[] args) {
System.out.println(new Store(14, 5, 10));
}
} /* Output:
} /* Output: (First 8 Lines)
258: Test, price: $400.99
861: Test, price: $160.99
868: Test, price: $417.99

View File

@ -13,7 +13,7 @@ extends ArrayList<FourTuple<A,B,C,D>> {
for(FourTuple<Vehicle,Amphibian,String,Integer> i: tl)
System.out.println(i);
}
} /* Output: (75% match)
} /* Output: (75% Match)
(Vehicle@11b86e7, Amphibian@35ce36, hi, 47)
(Vehicle@757aef, Amphibian@d9f9c3, hi, 47)
*///:~

View File

@ -32,7 +32,7 @@ public class TupleTest {
System.out.println(h());
System.out.println(k());
}
} /* Output: (80% match)
} /* Output: (80% Match)
(hi, 47)
(Amphibian@1f6a7b9, hi, 47)
(Vehicle@35ce36, Amphibian@757aef, hi, 47)

View File

@ -27,7 +27,7 @@ public class TupleTest2 {
System.out.println(h());
System.out.println(k());
}
} /* Output: (80% match)
} /* Output: (80% Match)
(hi, 47)
(hi, 47)
(Amphibian@7d772e, hi, 47)

View File

@ -1,6 +1,5 @@
//: generics/UseList.java
// {CompileTimeError} (Will not compile)
import java.util.*;
public class UseList<W,T> {
void f(List<T> v) {}

View File

@ -4,6 +4,7 @@
<property name="chapter" value="generics"/>
<property name="excludedfiles" value="Erased.java HijackedInterface.java Manipulation.java MultipleInterfaceVariants.java NonCovariantGenerics.java UseList.java"/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="ApplyTest" />

View File

@ -2,7 +2,6 @@
// Using JCheckBoxes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class CheckBoxes extends JFrame {

View File

@ -2,7 +2,6 @@
// Using drop-down lists.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class ComboBoxes extends JFrame {

View File

@ -2,7 +2,6 @@
// Creating and using Dialog Boxes.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
class MyDialog extends JDialog {

View File

@ -2,7 +2,6 @@
// Icon behavior in JButtons.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class Faces extends JFrame {

View File

@ -2,7 +2,6 @@
// Putting HTML text on Swing components.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class HTMLButton extends JFrame {

View File

@ -2,7 +2,6 @@
// Using Callables for long-running tasks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// Long-running tasks in threads.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// A badly designed program.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -136,7 +136,7 @@ public class Menus extends JFrame {
s.setMnemonic(KeyEvent.VK_A);
f.add(s);
f.setMnemonic(KeyEvent.VK_F);
for (JMenuItem file1 : file) {
for(JMenuItem file1 : file) {
file1.addActionListener(ml);
f.add(file1);
}

View File

@ -55,7 +55,7 @@ public class MessageBoxes extends JFrame {
};
public MessageBoxes() {
setLayout(new FlowLayout());
for (JButton b1 : b) {
for(JButton b1 : b) {
b1.addActionListener(al);
add(b1);
}

View File

@ -2,7 +2,6 @@
// Displaying task progress with ProgressMonitors.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// Using sliders, progress bars and progress monitors.
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -1,7 +1,6 @@
//: gui/TabbedPane1.java
// Demonstrates the Tabbed Pane.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// Using the JTextArea control.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// The JTextPane control is a little editor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*;

View File

@ -4,6 +4,7 @@
<property name="chapter" value="gui"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="BorderLayout1" failOnError='false' timeOut='4000' msg='* Timeout for Testing *' />

View File

@ -8,7 +8,7 @@ public class ApplesAndOrangesWithGenerics {
apples.add(new Apple());
// Compile-time error:
// apples.add(new Orange());
for (Apple apple : apples) {
for(Apple apple : apples) {
System.out.println(apple.id());
}
// Using foreach:

View File

@ -19,7 +19,7 @@ public class ApplesAndOrangesWithoutGenerics {
apples.add(new Apple());
// Not prevented from adding an Orange to apples:
apples.add(new Orange());
for (Object apple : apples) {
for(Object apple : apples) {
((Apple) apple).id();
// Orange is detected only at run time
}

View File

@ -4,6 +4,7 @@
<property name="chapter" value="holding"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AdapterMethodIdiom" />

View File

@ -17,7 +17,7 @@ public class NewVarArgs {
printArray((Object[])new Integer[]{ 1, 2, 3, 4 });
printArray(); // Empty list is OK
}
} /* Output: (75% match)
} /* Output: (75% Match)
47 3.14 11.11
47 3.14 11.11
one two three

View File

@ -4,6 +4,7 @@
<property name="chapter" value="initialization"/>
<property name="excludedfiles" value="OverloadingVarargs2.java"/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="ArrayClassObj" />

View File

@ -4,6 +4,7 @@
<property name="chapter" value="innerclasses"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AnonymousConstructor" />

View File

@ -4,6 +4,7 @@
<property name="chapter" value="interfaces"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AdaptedRandomDoubles" />

View File

@ -24,7 +24,7 @@ public class AvailableCharSets {
print();
}
}
} /* Output:
} /* Output: (First 7 Lines)
Big5: csBig5
Big5-HKSCS: big5-hkscs:unicode3.0, Big5_HKSCS, big5-hkscs, big5hkscs, big5hk
EUC-JP: eucjis, Extended_UNIX_Code_Packed_Format_for_Japanese, x-eucjp, eucjp, csEUCPkdFmtjapanese, euc_jp, x-euc-jp

View File

@ -67,7 +67,7 @@ public class MakeDirectories {
fileData(f);
}
}
} /* Output: (80% match)
} /* Output: (80% Match)
created MakeDirectoriesTest
Absolute path: d:\aaa-TIJ4\code\io\MakeDirectoriesTest
Can read: true

View File

@ -103,7 +103,7 @@ public class MappedIO {
for(Tester test : tests)
test.runTest();
}
} /* Output: (90% match)
} /* Output: (90% Match)
Stream Write: 0.56
Mapped Write: 0.12
Stream Read: 0.80

View File

@ -17,7 +17,7 @@ public class ZipCompress {
try (BufferedOutputStream out = new BufferedOutputStream(zos)) {
zos.setComment("A test of Java Zipping");
// No corresponding getComment(), though.
for (String arg : args) {
for(String arg : args) {
print("Writing file " + arg);
try(InputStream in = new BufferedInputStream(
new FileInputStream(arg))) {

View File

@ -4,6 +4,7 @@
<property name="chapter" value="io"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="AStoreCADState" />

View File

@ -1,19 +1,22 @@
//: logging/ConfigureLogging.java
// {JVMArgs: -Djava.util.logging.config.file=log.prop}
// {Clean: java0.log,java0.log.lck}
import java.util.logging.*;
public class ConfigureLogging {
static Logger lgr = Logger.getLogger("com"),
lgr2 = Logger.getLogger("com.bruceeckel"),
util = Logger.getLogger("com.bruceeckel.util"),
test = Logger.getLogger("com.bruceeckel.test"),
static Logger
lgr = Logger.getLogger("net"),
lgr2 = Logger.getLogger("net.mindview"),
util= Logger.getLogger("net.mindview.util"),
test= Logger.getLogger("net.mindview.test"),
rand = Logger.getLogger("random");
public ConfigureLogging() {
/* Set Additional formatters, Filters and Handlers for
the loggers here. You cannot specify the Handlers
for loggers except the root logger from the
configuration file. */
/*
Set Additional formatters, Filters and
Handlers for the loggers here. You cannot
specify the Handlers for loggers except
the root logger from the configuration
file.
*/
}
public static void main(String[] args) {
sendLogMessages(lgr);
@ -22,9 +25,11 @@ public class ConfigureLogging {
sendLogMessages(test);
sendLogMessages(rand);
}
private static void sendLogMessages(Logger logger) {
private static void
sendLogMessages(Logger logger) {
System.out.println(" Logger Name : "
+ logger.getName() + " Level: " + logger.getLevel());
+ logger.getName() + " Level: "
+ logger.getLevel());
logger.finest("Finest");
logger.finer("Finer");
logger.fine("Fine");
@ -33,4 +38,46 @@ public class ConfigureLogging {
logger.warning("Warning");
logger.severe("Severe");
}
} ///:~
} /* Output: (Sample)
Logger Name : net Level: SEVERE
Logger Name : net.mindview Level: FINEST
Logger Name : net.mindview.util Level: INFO
Logger Name : net.mindview.test Level: FINER
Logger Name : random Level: SEVERE
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
SEVERE: Severe
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
FINEST: Finest
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
FINER: Finer
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
FINE: Fine
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
CONFIG: Config
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
INFO: Info
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
WARNING: Warning
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
SEVERE: Severe
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
INFO: Info
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
WARNING: Warning
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
SEVERE: Severe
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
FINER: Finer
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
FINE: Fine
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
CONFIG: Config
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
INFO: Info
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
WARNING: Warning
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
SEVERE: Severe
May 14, 2015 4:43:34 PM ConfigureLogging sendLogMessages
SEVERE: Severe
*///:~

View File

@ -6,15 +6,19 @@ import java.util.*;
public class CustomHandler {
private static Logger logger =
Logger.getLogger("CustomHandler");
private static List<String> trace = new ArrayList<>();
private static List<String> trace =
new ArrayList<>();
public static void main(String[] args) {
logger.addHandler(new Handler() {
@Override
public void publish(LogRecord logRecord) {
trace.add(logRecord.getLevel() + ":");
trace.add(logRecord.getSourceClassName()+":");
trace.add(logRecord.getSourceMethodName()+":");
trace.add("<" + logRecord.getMessage() + ">");
trace.add(logRecord.getSourceClassName()
+ ":");
trace.add(
logRecord.getSourceMethodName() +":");
trace.add("<" + logRecord.getMessage()
+ ">");
trace.add("\n");
}
@Override
@ -26,4 +30,12 @@ public class CustomHandler {
logger.info("Logging Info");
System.out.print(trace);
}
} ///:~
} /* Output:
[WARNING:, CustomHandler:, main:, <Logging Warning>,
, INFO:, CustomHandler:, main:, <Logging Info>,
]
May 14, 2015 3:29:53 PM CustomHandler main
WARNING: Logging Warning
May 14, 2015 3:29:53 PM CustomHandler main
INFO: Logging Info
*///:~

View File

@ -11,7 +11,8 @@ import javax.mail.internet.*;
public class EmailLogger {
private static Logger logger =
Logger.getLogger("EmailLogger");
public static void main(String[] args) throws Exception {
public static void
main(String[] args) throws Exception {
logger.setUseParentHandlers(false);
Handler conHdlr = new ConsoleHandler();
conHdlr.setFormatter(new Formatter() {
@ -28,7 +29,8 @@ public class EmailLogger {
new FileHandler("EmailLoggerOutput.xml"));
logger.addHandler(new MailingHandler());
logger.log(Level.INFO,
"Testing Multiple Handlers", "SendMailTrue");
"Testing Multiple Handlers",
"SendMailTrue");
}
}
@ -59,7 +61,8 @@ class MailInfo {
private String subject;
private String message;
public MailInfo(String from, String[] to,
String server, String subject, String message) {
String server, String subject,
String message) {
fromAddr = from;
toAddr = to;
serverAddr = server;
@ -74,14 +77,17 @@ class MailInfo {
Session.getDefaultInstance(prop, null);
session.setDebug(true);
// Create a message
Message mimeMsg = new MimeMessage(session);
Message mimeMsg= new MimeMessage(session);
// Set the from and to address
Address addressFrom = new InternetAddress(fromAddr);
Address addressFrom =
new InternetAddress(fromAddr);
mimeMsg.setFrom(addressFrom);
Address[] to = new InternetAddress[toAddr.length];
Address[] to =
new InternetAddress[toAddr.length];
for(int i = 0; i < toAddr.length; i++)
to[i] = new InternetAddress(toAddr[i]);
mimeMsg.setRecipients(Message.RecipientType.TO,to);
mimeMsg.setRecipients(
Message.RecipientType.TO,to);
mimeMsg.setSubject(subject);
mimeMsg.setText(message);
Transport.send(mimeMsg);

View File

@ -1,11 +1,13 @@
//: logging/InfoLogging.java
import java.util.logging.*;
import java.io.*;
public class InfoLogging {
private static Logger logger =
Logger.getLogger("InfoLogging");
public static void main(String[] args) {
logger.info("Logging an INFO-level message");
logger.info("Logging: INFO-level message");
}
} ///:~
} /* Output:
May 13, 2015 6:26:41 PM InfoLogging main
INFO: Logging: INFO-level message
*///:~

View File

@ -1,13 +1,15 @@
//: logging/InfoLogging2.java
// Guaranteeing proper class and method names
import java.util.logging.*;
import java.io.*;
public class InfoLogging2 {
private static Logger logger =
Logger.getLogger("InfoLogging2");
public static void main(String[] args) {
logger.logp(Level.INFO, "InfoLogging2", "main",
"Logging an INFO-level message");
logger.logp(Level.INFO, "InfoLogging2",
"main", "Logging an INFO-level message");
}
} ///:~
} /* Output:
May 13, 2015 10:43:36 AM InfoLogging2 main
INFO: Logging an INFO-level message
*///:~

View File

@ -1,12 +1,16 @@
//: logging/LogToFile.java
// {Clean: LogToFile.xml,LogToFile.xml.lck}
import java.util.logging.*;
public class LogToFile {
private static Logger logger =
Logger.getLogger("LogToFile");
public static void main(String[] args) throws Exception {
logger.addHandler(new FileHandler("LogToFile.xml"));
public static void
main(String[] args) throws Exception {
logger.addHandler(
new FileHandler("LogToFile.xml"));
logger.info("A message logged to the file");
}
} ///:~
} /* Output:
May 14, 2015 3:29:53 PM LogToFile main
INFO: A message logged to the file
*///:~

View File

@ -1,14 +1,18 @@
//: logging/LogToFile2.java
// {Clean: LogToFile2.txt,LogToFile2.txt.lck}
import java.util.logging.*;
public class LogToFile2 {
private static Logger logger =
Logger.getLogger("LogToFile2");
public static void main(String[] args) throws Exception {
FileHandler logFile= new FileHandler("LogToFile2.txt");
public static void
main(String[] args) throws Exception {
FileHandler logFile =
new FileHandler("LogToFile2.txt");
logFile.setFormatter(new SimpleFormatter());
logger.addHandler(logFile);
logger.info("A message logged to the file");
}
} ///:~
} /* Output:
May 14, 2015 3:29:53 PM LogToFile2 main
INFO: A message logged to the file
*///:~

View File

@ -1,15 +1,13 @@
//: logging/LoggingLevelManipulation.java
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.LogManager;
public class LoggingLevelManipulation {
private static Logger
lgr = Logger.getLogger("com"),
lgr2 = Logger.getLogger("com.bruceeckel"),
util = Logger.getLogger("com.bruceeckel.util"),
test = Logger.getLogger("com.bruceeckel.test"),
lgr = Logger.getLogger("net"),
lgr2 = Logger.getLogger("net.mindview"),
util= Logger.getLogger("net.mindview.util"),
test= Logger.getLogger("net.mindview.test"),
rand = Logger.getLogger("random");
static void printLogMessages(Logger logger) {
logger.finest(logger.getName() + " Finest");
@ -17,7 +15,7 @@ public class LoggingLevelManipulation {
logger.fine(logger.getName() + " Fine");
logger.config(logger.getName() + " Config");
logger.info(logger.getName() + " Info");
logger.warning(logger.getName() + " Warning");
logger.warning(logger.getName()+" Warning");
logger.severe(logger.getName() + " Severe");
}
static void logMessages() {
@ -29,17 +27,22 @@ public class LoggingLevelManipulation {
}
static void printLevels() {
System.out.println(" -- printing levels -- "
+ lgr.getName() + " : " + lgr.getLevel()
+ " " + lgr2.getName() + " : " + lgr2.getLevel()
+ " " + util.getName() + " : " + util.getLevel()
+ " " + test.getName() + " : " + test.getLevel()
+ " " + rand.getName() + " : " + rand.getLevel());
+ lgr.getName()
+ " : " + lgr.getLevel()
+ " " + lgr2.getName()
+ " : " + lgr2.getLevel()
+ " " + util.getName()
+ " : " + util.getLevel()
+ " " + test.getName()
+ " : " + test.getLevel()
+ " " + rand.getName()
+ " : " + rand.getLevel());
}
public static void main(String[] args) {
printLevels();
lgr.setLevel(Level.SEVERE);
printLevels();
System.out.println("com level: SEVERE");
System.out.println("net level: SEVERE");
logMessages();
util.setLevel(Level.FINEST);
test.setLevel(Level.FINEST);
@ -50,7 +53,81 @@ public class LoggingLevelManipulation {
logMessages();
lgr.setLevel(Level.FINEST);
printLevels();
System.out.println("com level: FINEST");
System.out.println("net level: FINEST");
logMessages();
}
} ///:~
} /* Output:
-- printing levels -- net : null net.mindview : null net.mindview.util : null net.mindview.test : null random : null
-- printing levels -- net : SEVERE net.mindview : null net.mindview.util : null net.mindview.test : null random : null
net level: SEVERE
-- printing levels -- net : SEVERE net.mindview : null net.mindview.util : FINEST net.mindview.test : FINEST random : FINEST
individual loggers set to FINEST
-- printing levels -- net : FINEST net.mindview : null net.mindview.util : FINEST net.mindview.test : FINEST random : FINEST
net level: FINEST
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
SEVERE: net Severe
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview Severe
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.util Severe
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.test Severe
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
INFO: random Info
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
WARNING: random Warning
May 14, 2015 4:21:45 PM LoggingLevelManipulation printLogMessages
SEVERE: random Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net.mindview.util Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net.mindview.util Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.util Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net.mindview.test Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net.mindview.test Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.test Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: random Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: random Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: random Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net.mindview Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net.mindview Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net.mindview.util Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net.mindview.util Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.util Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: net.mindview.test Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: net.mindview.test Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: net.mindview.test Severe
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
INFO: random Info
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
WARNING: random Warning
May 14, 2015 4:21:46 PM LoggingLevelManipulation printLogMessages
SEVERE: random Severe
*///:~

View File

@ -1,15 +1,13 @@
//: logging/LoggingLevels.java
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.LogManager;
public class LoggingLevels {
private static Logger
lgr = Logger.getLogger("com"),
lgr2 = Logger.getLogger("com.bruceeckel"),
util = Logger.getLogger("com.bruceeckel.util"),
test = Logger.getLogger("com.bruceeckel.test"),
util= Logger.getLogger("com.bruceeckel.util"),
test= Logger.getLogger("com.bruceeckel.test"),
rand = Logger.getLogger("random");
private static void logMessages() {
lgr.info("com : info");
@ -25,10 +23,31 @@ public class LoggingLevels {
util.setLevel(Level.FINEST);
test.setLevel(Level.FINEST);
rand.setLevel(Level.FINEST);
System.out.println("individual loggers set to FINEST");
System.out.println(
"individual loggers set to FINEST");
logMessages();
lgr.setLevel(Level.SEVERE);
System.out.println("com level: SEVERE");
logMessages();
}
} ///:~
} /* Output:
com level: SEVERE
individual loggers set to FINEST
com level: SEVERE
May 13, 2015 10:43:36 AM LoggingLevels logMessages
SEVERE: test : severe
May 13, 2015 10:43:36 AM LoggingLevels logMessages
INFO: random : info
May 13, 2015 10:43:36 AM LoggingLevels logMessages
INFO: util : info
May 13, 2015 10:43:36 AM LoggingLevels logMessages
SEVERE: test : severe
May 13, 2015 10:43:36 AM LoggingLevels logMessages
INFO: random : info
May 13, 2015 10:43:36 AM LoggingLevels logMessages
INFO: util : info
May 13, 2015 10:43:36 AM LoggingLevels logMessages
SEVERE: test : severe
May 13, 2015 10:43:36 AM LoggingLevels logMessages
INFO: random : info
*///:~

View File

@ -1,15 +1,21 @@
//: logging/MultipleHandlers.java
// {Clean: MultipleHandlers.xml,MultipleHandlers.xml.lck}
import java.util.logging.*;
public class MultipleHandlers {
private static Logger logger =
Logger.getLogger("MultipleHandlers");
public static void main(String[] args) throws Exception {
public static void
main(String[] args) throws Exception {
FileHandler logFile =
new FileHandler("MultipleHandlers.xml");
logger.addHandler(logFile);
logger.addHandler(new ConsoleHandler());
logger.warning("Output to multiple handlers");
logger.warning(
"Output to multiple handlers");
}
} ///:~
} /* Output:
May 14, 2015 3:29:53 PM MultipleHandlers main
WARNING: Output to multiple handlers
May 14, 2015 3:29:53 PM MultipleHandlers main
WARNING: Output to multiple handlers
*///:~

View File

@ -1,16 +1,20 @@
//: logging/MultipleHandlers2.java
// {Clean: MultipleHandlers2.xml,MultipleHandlers2.xml.lck}
import java.util.logging.*;
public class MultipleHandlers2 {
private static Logger logger =
Logger.getLogger("MultipleHandlers2");
public static void main(String[] args) throws Exception {
public static void
main(String[] args) throws Exception {
FileHandler logFile =
new FileHandler("MultipleHandlers2.xml");
logger.addHandler(logFile);
logger.addHandler(new ConsoleHandler());
logger.setUseParentHandlers(false);
logger.warning("Output to multiple handlers");
logger.warning(
"Output to multiple handlers");
}
} ///:~
} /* Output:
May 14, 2015 3:29:53 PM MultipleHandlers2 main
WARNING: Output to multiple handlers
*///:~

View File

@ -1,15 +1,16 @@
//: logging/PrintableLogRecord.java
// Override LogRecord toString()
import java.util.ResourceBundle;
import java.util.logging.*;
public class PrintableLogRecord extends LogRecord {
public PrintableLogRecord(Level level, String str) {
public class
PrintableLogRecord extends LogRecord {
public
PrintableLogRecord(Level level, String str) {
super(level, str);
}
@Override
public String toString() {
String result = "Level<" + getLevel() + ">\n"
String result = "Level<" + getLevel()+ ">\n"
+ "LoggerName<" + getLoggerName() + ">\n"
+ "Message<" + getMessage() + ">\n"
+ "CurrentMillis<" + getMillis() + ">\n"
@ -19,20 +20,39 @@ public class PrintableLogRecord extends LogRecord {
result += "<null>\n";
else
for(int i = 0; i < objParams.length; i++)
result += " Param # <" + i + " value " +
result += " Param # <" + i + " value "+
objParams[i].toString() + ">\n";
result += "ResourceBundle<" + getResourceBundle()
+ ">\nResourceBundleName<" + getResourceBundleName()
+ ">\nSequenceNumber<" + getSequenceNumber()
+ ">\nSourceClassName<" + getSourceClassName()
+ ">\nSourceMethodName<" + getSourceMethodName()
result += "ResourceBundle<"
+ getResourceBundle()
+ ">\nResourceBundleName<"
+ getResourceBundleName()
+ ">\nSequenceNumber<"
+ getSequenceNumber()
+ ">\nSourceClassName<"
+ getSourceClassName()
+ ">\nSourceMethodName<"
+ getSourceMethodName()
+ ">\nThread Id<" + getThreadID()
+ ">\nThrown<" + getThrown() + ">";
return result;
}
public static void main(String[] args) {
PrintableLogRecord logRecord = new PrintableLogRecord(
PrintableLogRecord logRecord =
new PrintableLogRecord(
Level.FINEST, "Simple Log Record");
System.out.println(logRecord);
}
} ///:~
} /* Output:
Level<FINEST>
LoggerName<null>
Message<Simple Log Record>
CurrentMillis<1431539016784>
Params<null>
ResourceBundle<null>
ResourceBundleName<null>
SequenceNumber<0>
SourceClassName<null>
SourceMethodName<null>
Thread Id<1>
Thrown<null>
*///:~

View File

@ -15,11 +15,14 @@ public class SimpleFilter {
public static void main(String[] args) {
sendLogMessages();
logger.setFilter(new Filter() {
public boolean isLoggable(LogRecord record) {
Object[] params = record.getParameters();
public boolean
isLoggable(LogRecord record) {
Object[] params =
record.getParameters();
if(params == null)
return true; // No parameters
if(record.getParameters()[0] instanceof Duck)
if(record.getParameters()[0]
instanceof Duck)
return true; // Only log Ducks
return false;
}
@ -27,4 +30,13 @@ public class SimpleFilter {
logger.info("After setting filter..");
sendLogMessages();
}
} ///:~
} /* Output:
May 14, 2015 3:29:53 PM SimpleFilter sendLogMessages
WARNING: A duck in the house!
May 14, 2015 3:29:54 PM SimpleFilter sendLogMessages
WARNING: A Wombat at large!
May 14, 2015 3:29:54 PM SimpleFilter main
INFO: After setting filter..
May 14, 2015 3:29:54 PM SimpleFilter sendLogMessages
WARNING: A duck in the house!
*///:~

View File

@ -1,7 +1,5 @@
//: logging/SimpleFormatterExample.java
// {CompileTimeError}
import java.util.logging.*;
import java.util.*;
public class SimpleFormatterExample {
private static Logger logger =
@ -16,12 +14,17 @@ public class SimpleFormatterExample {
conHdlr.setFormatter(new Formatter() {
public String format(LogRecord record) {
return record.getLevel() + " : "
+ record.getSourceClassName() + " -:- "
+ record.getSourceMethodName() + " -:- "
+ record.getSourceClassName()
+ " -:- "
+ record.getSourceMethodName()
+ " -:- "
+ record.getMessage() + "\n";
}
});
logger.addHandler(conHdlr);
logMessages();
}
} ///:~
} /* Output:
INFO : SimpleFormatterExample -:- logMessages -:- Line One
INFO : SimpleFormatterExample -:- logMessages -:- Line Two
*///:~

View File

@ -2,8 +2,9 @@
<project default="run">
<property name="chapter" value="logging"/>
<property name="excludedfiles" value="EmailLogger.java SimpleFormatterExample.java"/>
<property name="excludedfiles" value="EmailLogger.java"/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="ConfigureLogging" />
@ -18,6 +19,7 @@
<jrun cls="MultipleHandlers2" />
<jrun cls="PrintableLogRecord" />
<jrun cls="SimpleFilter" />
<jrun cls="SimpleFormatterExample" />
</target>
</project>

View File

@ -25,9 +25,9 @@ java.util.logging.ConsoleHandler.level = FINEST
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# Set Logger Levels #
com.level=SEVERE
com.bruceeckel.level = FINEST
com.bruceeckel.util.level = INFO
com.bruceeckel.test.level = FINER
net.level=SEVERE
net.mindview.level = FINEST
net.mindview.util.level = INFO
net.mindview.test.level = FINER
random.level= SEVERE
///:~

View File

@ -4,10 +4,10 @@
<property name="chapter" value="net"/>
<property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build">
<jrun cls="net.mindview.atunit.AtUnit" dirpath="../net/mindview/atunit" />
<jrun cls="net.mindview.atunit.AtUnitRemover" dirpath="../net/mindview/atunit" arguments=".." failOnError='false' msg='* Exception was Expected *' />
<jrun cls="net.mindview.atunit.ClassNameFinder" dirpath="../net/mindview/atunit" />
<jrun cls="net.mindview.util.ContainerMethodDifferences" dirpath="../net/mindview/util" />
<jrun cls="net.mindview.util.CountingIntegerList" dirpath="../net/mindview/util" />

View File

@ -25,7 +25,7 @@ public class Hex {
System.out.println(
format(BinaryFile.read(new File(args[0]))));
}
} /* Output: (Sample)
} /* Output: (First 6 Lines)
00000: CA FE BA BE 00 00 00 31 00 52 0A 00 05 00 22 07
00010: 00 23 0A 00 02 00 22 08 00 24 07 00 25 0A 00 26
00020: 00 27 0A 00 28 00 29 0A 00 02 00 2A 08 00 2B 0A

View File

@ -1,6 +1,6 @@
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java 5 static imports:
// qualifiers, using static imports:
package net.mindview.util;
import java.io.*;

View File

@ -1,4 +1,5 @@
//: net/mindview/util/ProcessFiles.java
// {CheckOutputByHand}
package net.mindview.util;
import java.io.*;

View File

@ -1,6 +1,6 @@
//: net/mindview/util/Range.java
// Array creation methods that can be used without
// qualifiers, using Java 5 static imports:
// qualifiers, using static imports:
package net.mindview.util;
public class Range {

View File

@ -3,7 +3,6 @@
// A server that echoes datagrams
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatterServer {
static final int INPORT = 1711;

Some files were not shown because too many files have changed in this diff Show More