├── README.md
└── javacooksrc
├── META-INF
└── MANIFEST.MF
└── javacooksrc
├── DISCLAIMER.txt
├── LICENSE.txt
├── README.txt
├── demo
└── java
│ └── com
│ └── darwinsys
│ ├── io
│ └── FileIoDemo.java
│ └── swingui
│ └── WindowCloserDemo.java
├── main
├── java
│ ├── beans
│ │ ├── BSFAction.java
│ │ └── BSFSample.java
│ ├── chat
│ │ ├── ChatClient.java
│ │ └── ChatServer.java
│ ├── com
│ │ └── darwinsys
│ │ │ ├── csv
│ │ │ ├── CSVImport.java
│ │ │ └── CSVRE.java
│ │ │ ├── io
│ │ │ ├── FileIO.java
│ │ │ ├── FileSaver.java
│ │ │ ├── TextAreaOutputStream.java
│ │ │ └── TextAreaWriter.java
│ │ │ ├── lang
│ │ │ ├── ExecAndPrint.java
│ │ │ ├── GetOpt.java
│ │ │ ├── MutableInteger.java
│ │ │ └── SysDep.java
│ │ │ ├── mail
│ │ │ └── Mailer.java
│ │ │ ├── regex
│ │ │ └── JGrep.java
│ │ │ ├── sql
│ │ │ ├── ResultsDecorator.java
│ │ │ ├── ResultsDecoratorHTML.java
│ │ │ ├── ResultsDecoratorText.java
│ │ │ └── SQLRunner.java
│ │ │ ├── swingui
│ │ │ ├── ErrorUtil.java
│ │ │ ├── FontChooser.java
│ │ │ ├── I18N.java
│ │ │ ├── LabelText.java
│ │ │ ├── UtilGUI.java
│ │ │ ├── WindowCloser.java
│ │ │ └── layout
│ │ │ │ └── EntryLayout.java
│ │ │ ├── tools
│ │ │ ├── KwikLinkChecker.java
│ │ │ └── XrefCheck.java
│ │ │ └── util
│ │ │ └── ArrayIterator.java
│ ├── database
│ │ ├── Address.java
│ │ ├── TextToJDBC.java
│ │ ├── UserDBJDBC.java
│ │ ├── UserQuery.java
│ │ ├── hibernate
│ │ │ └── HibernateSimple.java
│ │ ├── jdbc
│ │ │ ├── CachedRowSetDemo.java
│ │ │ ├── Connect.java
│ │ │ ├── DatabaseMetaDemo.java
│ │ │ └── LoadDriver.java
│ │ └── jpa
│ │ │ └── JPASimple.java
│ ├── datetime
│ │ ├── CurrentDateTime.java
│ │ ├── DateAdd.java
│ │ ├── DateConversions.java
│ │ ├── DateDiff.java
│ │ ├── DateFormatter.java
│ │ ├── DateParse.java
│ │ ├── EndOfTime64Msec.java
│ │ ├── LegacyDates.java
│ │ └── LegacyDatesDIY.java
│ ├── dbm
│ │ ├── DBM.java
│ │ └── Makefile
│ ├── di
│ │ ├── ControllerTightlyCoupled.java
│ │ ├── View.java
│ │ ├── javasecdi
│ │ │ ├── CDIMain.java
│ │ │ ├── ConsoleViewer.java
│ │ │ ├── Model.java
│ │ │ └── MyModel.java
│ │ └── spring
│ │ │ ├── ConsoleViewer.java
│ │ │ ├── Controller.java
│ │ │ ├── ControllerTightlyCoupled.java
│ │ │ └── SimpleModel.java
│ ├── dir_file
│ │ ├── Creat.java
│ │ ├── Delete.java
│ │ ├── Delete2.java
│ │ ├── FNFilter.java
│ │ ├── FNFilterL.java
│ │ ├── FileStatus.java
│ │ ├── Find.java
│ │ ├── FindFilter.java
│ │ ├── ListRoots.java
│ │ ├── Ls.java
│ │ ├── PathsFilesDemo.java
│ │ ├── ReadOnly.java
│ │ ├── Rename.java
│ │ └── TempFiles.java
│ ├── domain
│ │ ├── Address.java
│ │ └── Person.java
│ ├── ejb2
│ │ └── hello
│ │ │ └── Makefile
│ ├── email
│ │ ├── CheckOpenMailRelayGui.java
│ │ ├── MailClient.java
│ │ ├── MailComposeBean.java
│ │ ├── MailComposeFrame.java
│ │ ├── MailConstants.java
│ │ ├── MailLister.java
│ │ ├── MailReaderBean.java
│ │ ├── MailtoButton.java
│ │ ├── MessageNode.java
│ │ ├── SendMime.java
│ │ ├── Sender.java
│ │ └── SmtpTalk.java
│ ├── environ
│ │ ├── GetEnv.java
│ │ ├── GetOptDemoNew.java
│ │ ├── GetOptParseArgs.java
│ │ ├── GetOptParseArgsDemo.java
│ │ ├── GetOptSimple.java
│ │ └── SysPropDemo.java
│ ├── functional
│ │ ├── CameraSearchParallelStream.java
│ │ ├── CameraSearchPredicate.java
│ │ ├── ProcessIntsFunctional.java
│ │ ├── ProcessIntsUsingFunctional.java
│ │ ├── ReferencesDemo.java
│ │ ├── ReferencesDemo2.java
│ │ ├── ReferencesDemo3.java
│ │ ├── ReferencesDemo4.java
│ │ └── SimpleStreamDemo.java
│ ├── graphics
│ │ ├── AudioPlay.java
│ │ ├── DrawStringDemo.java
│ │ ├── DrawStringDemo2.java
│ │ ├── DropShadow.java
│ │ ├── GetImage.java
│ │ ├── Grapher.java
│ │ ├── JMFPlayer.java
│ │ ├── PaintDemo.java
│ │ ├── TTFontDemo.java
│ │ ├── TexturedText.java
│ │ ├── TiledImageComponent.java
│ │ └── VlcjVideo.java
│ ├── gui
│ │ ├── ButtonDemo.java
│ │ ├── ButtonDemo2L.java
│ │ ├── ButtonDemo2a.java
│ │ ├── ButtonDemo2b.java
│ │ ├── CompRunner.java
│ │ ├── ContentPane.java
│ │ ├── JColorChooserDemo.java
│ │ ├── JFileChooserDemo.java
│ │ ├── JFileFilter.java
│ │ ├── JFrameDemo.java
│ │ ├── JFrameDemoSafe.java
│ │ ├── JFrameFlowLayout.java
│ │ ├── JLabelHTMLDemo.java
│ │ ├── LNFSwitcher.java
│ │ ├── MVC
│ │ │ └── MVCDemo.graffle
│ │ ├── MacOsUiHints.java
│ │ ├── RunOnEdt.java
│ │ ├── SpinnerDemo.java
│ │ ├── TabPaneDemo.java
│ │ ├── ThreadBasedCatcher.java
│ │ ├── WindowDemo.java
│ │ └── WindowDemo2.java
│ ├── gui_awt
│ │ └── ButtonDemo2c.java
│ ├── i18n
│ │ ├── BusCard.java
│ │ ├── JOptionDemo.java
│ │ ├── ListLocales.java
│ │ ├── MenuIntl.java
│ │ ├── MessageFormatDemo.java
│ │ ├── MessageFormatDemoIntl.java
│ │ ├── SetLocale.java
│ │ └── UseLocales.java
│ ├── io
│ │ ├── BadNewline.java
│ │ ├── CatStdin.java
│ │ ├── CharMode.java
│ │ ├── ConsoleRead.java
│ │ ├── ContLineReader.java
│ │ ├── FormatterDates.java
│ │ ├── FormatterDemo.java
│ │ ├── GetMark.java
│ │ ├── GoodNewline.java
│ │ ├── IndentContLineReader.java
│ │ ├── MyData.java
│ │ ├── ReadCharsOneAtATime.java
│ │ ├── ReadGZIP.java
│ │ ├── ReadPassword.java
│ │ ├── ReadRandom.java
│ │ ├── ReadStdin.java
│ │ ├── ReadStdinInt.java
│ │ ├── Redirect.java
│ │ ├── ScanStringTok.java
│ │ ├── ScannerDemo.java
│ │ ├── SerialDemoAbstractBase.java
│ │ ├── SerialDemoObjectStream.java
│ │ ├── SerialDemoXML.java
│ │ ├── SimpleCalcScanner.java
│ │ ├── SimpleCalcStreamTok.java
│ │ ├── Stdout.java
│ │ ├── TeePrintStream.java
│ │ ├── UnZip.java
│ │ ├── WriteBinary.java
│ │ └── WriteRandom.c
│ ├── javacomm
│ │ └── CommPortSimple.java
│ ├── javadoc
│ │ └── JavadocDemo.java
│ ├── javafx
│ │ ├── AudioPlay.java
│ │ ├── HelloFx.java
│ │ └── JfxVideo.java
│ ├── jaxwsclient
│ │ └── TinyClientMain.java
│ ├── jaxwsservice
│ │ ├── Calc.java
│ │ └── ServiceMain.java
│ ├── jdb
│ │ └── Problem.java
│ ├── jni
│ │ ├── HelloJni.c
│ │ ├── HelloJni.java
│ │ ├── Makefile
│ │ └── javafromc.c
│ ├── json
│ │ ├── LocalDateToJsonManually.java
│ │ ├── ReadWriteJackson.java
│ │ ├── SoftwareParseJackson.java
│ │ ├── SoftwareParseOrgJson.java
│ │ └── WriteOrgJson.java
│ ├── lang
│ │ ├── AbstractStatic.java
│ │ ├── AnnotationDemo.java
│ │ ├── AnnotationOverrideDemo.java
│ │ ├── ChangeArrayLength.java
│ │ ├── HexNeg.java
│ │ ├── InnerChild.java
│ │ ├── InvokeMain.java
│ │ ├── MixinsDemo.java
│ │ ├── Shifting.java
│ │ └── VarArgsDemo.java
│ ├── logging
│ │ ├── Log14Demo.java
│ │ ├── Log14Demo2.java
│ │ ├── Log4JDemo.java
│ │ ├── Log4JDemo2.java
│ │ ├── NetLogServer.java
│ │ ├── NetLogSimple.java
│ │ ├── Slf4jDemo.java
│ │ └── Slf4jDemo2.java
│ ├── netwatch
│ │ ├── NetFrame.java
│ │ ├── NetPanel.java
│ │ ├── NetWatch.java
│ │ └── RMIPanel.java
│ ├── netweb
│ │ └── URIDemo.java
│ ├── network
│ │ ├── Connect.c
│ │ ├── ConnectFriendly.java
│ │ ├── ConnectSimple.java
│ │ ├── DaytimeObject.java
│ │ ├── DaytimeObjectServer.java
│ │ ├── DaytimeServer.java
│ │ ├── DaytimeText.java
│ │ ├── DaytimeUDP.java
│ │ ├── EchoClientOneLine.java
│ │ ├── EchoServer.java
│ │ ├── EchoServerThreaded.java
│ │ ├── EchoServerThreaded2.java
│ │ ├── InetAddrDemo.java
│ │ ├── JSSEWebServer0.java
│ │ ├── Listen.java
│ │ ├── ListenInside.java
│ │ ├── NetworkInterfaceDemo.java
│ │ ├── RDateClient.java
│ │ ├── RemCat.java
│ │ ├── Telnet.java
│ │ └── WebServer0.java
│ ├── nio
│ │ └── FileWatchServiceDemo.java
│ ├── numbers
│ │ ├── BigNumCalc.java
│ │ ├── BigNums.java
│ │ ├── BinaryDigits.java
│ │ ├── CastNeeded.java
│ │ ├── Complex.java
│ │ ├── ComplexDemo.java
│ │ ├── FloatCmp.java
│ │ ├── FormatPlurals.java
│ │ ├── FormatPluralsChoice.java
│ │ ├── FractMult.java
│ │ ├── GetNumber.java
│ │ ├── Heron.java
│ │ ├── InfNaN.java
│ │ ├── IntFract.java
│ │ ├── IntObject.java
│ │ ├── IntegerBinOctHexEtc.java
│ │ ├── LogBase.java
│ │ ├── LogBaseUse.java
│ │ ├── Logarithm.java
│ │ ├── Matrix.java
│ │ ├── MatrixUse.java
│ │ ├── NumFormat2.java
│ │ ├── NumFormatDemo.java
│ │ ├── NumFormatParse.java
│ │ ├── NumSeries.java
│ │ ├── Palindrome.java
│ │ ├── Random1.java
│ │ ├── Random2.java
│ │ ├── Random3.java
│ │ ├── RandomInt.java
│ │ ├── RomanNumberDemo.java
│ │ ├── RomanNumberFormat.java
│ │ ├── RomanNumberSimple.java
│ │ ├── RomanYear.java
│ │ ├── Round.java
│ │ ├── StringToDouble.java
│ │ ├── TempConverter.java
│ │ ├── TempConverter2.java
│ │ └── Trig.java
│ ├── oo
│ │ ├── AllClasses.java
│ │ ├── ChessMoveException.java
│ │ ├── Clone1.java
│ │ ├── CopyConstructorDemo.java
│ │ ├── EqualsDemo.java
│ │ ├── PrintHashCodes.java
│ │ ├── SerializableUser.java
│ │ ├── ShutdownDemo.java
│ │ ├── Singleton.java
│ │ ├── StringParse.java
│ │ ├── ToStringWith.java
│ │ ├── ToStringWithout.java
│ │ ├── interfaces
│ │ │ └── BuildingManagement.java
│ │ └── shapes
│ │ │ └── ShapeDriver.java
│ ├── otherlang
│ │ ├── ExecDemoFiles.java
│ │ ├── ExecDemoLs.java
│ │ ├── ExecDemoNS.java
│ │ ├── ExecDemoSimple.java
│ │ ├── ExecDemoWait.java
│ │ ├── ProcessBuilderDemo.java
│ │ ├── RenjinScripting.java
│ │ ├── ScriptEnginesDemo.java
│ │ ├── StringDistance.java
│ │ └── calcscriptengine
│ │ │ ├── CalcScriptEngine.java
│ │ │ └── CalcScriptEngineFactory.java
│ ├── packaging
│ │ ├── GetResourceDemo.java
│ │ └── HelloApplet.java
│ ├── patterns
│ │ └── Makefile
│ ├── performance
│ │ ├── Array.java
│ │ ├── ArrayLst.java
│ │ ├── StringPrintA.java
│ │ ├── StringPrintB.java
│ │ └── Time.java
│ ├── plotter
│ │ ├── PlotDriver.java
│ │ ├── Plotter.java
│ │ └── PlotterAWT.java
│ ├── printjdk12printerjob
│ │ └── PrintDemoGfx.java
│ ├── printjdk14printservice
│ │ ├── PrintPostScript.java
│ │ └── PrintServiceDemo.java
│ ├── reflection
│ │ ├── AppletAdapter.java
│ │ ├── AppletViewer.java
│ │ ├── ClassKeyword.java
│ │ ├── ClassesInPackage.java
│ │ ├── CrossRef.java
│ │ ├── CrossRefXML.java
│ │ ├── DefeatPrivacy.java
│ │ ├── FindField.java
│ │ ├── GetAndInvokeMethod.java
│ │ ├── ListMethods.java
│ │ ├── MyJavaP.java
│ │ ├── Packages.java
│ │ ├── PluginsViaAnnotations.java
│ │ └── cooklet
│ │ │ ├── Cookies.java
│ │ │ └── DemoCooklet.java
│ ├── regex
│ │ ├── APIJava.txt
│ │ ├── BookRank.java
│ │ ├── CanonEqDemo.java
│ │ ├── Grep0.java
│ │ ├── GrepNIO.java
│ │ ├── LogRegExp.java
│ │ ├── NLMatch.java
│ │ ├── RESimple.java
│ │ ├── REmatch.java
│ │ ├── REmatchTwoFields.java
│ │ ├── REsubstr.java
│ │ ├── ReaderIter.java
│ │ ├── ReplaceDemo.java
│ │ └── StringConvenience.java
│ ├── rmi
│ │ ├── DateApplet.java
│ │ ├── DateClient.java
│ │ ├── DateServer.java
│ │ ├── RemoteDate.java
│ │ ├── RemoteDateImpl.java
│ │ └── callback
│ │ │ ├── Client.java
│ │ │ ├── ClientProgram.java
│ │ │ ├── TickerServer.java
│ │ │ └── TickerServerImpl.java
│ ├── sched
│ │ └── Appt.java
│ ├── signals
│ │ └── Makefile
│ ├── starting
│ │ ├── Buggy.java
│ │ ├── CheckForSwing.java
│ │ ├── Deprec.java
│ │ └── HelloWorld.java
│ ├── strings
│ │ ├── Case.java
│ │ ├── CheckSum.java
│ │ ├── DeTab.java
│ │ ├── EnTab.java
│ │ ├── Fmt.java
│ │ ├── ForEachChar.java
│ │ ├── Indent.java
│ │ ├── Soundex.java
│ │ ├── SoundexSimple.java
│ │ ├── StrCharAt.java
│ │ ├── StrTokDemo4.java
│ │ ├── StringAlign.java
│ │ ├── StringAlignSimple.java
│ │ ├── StringBuilderCommaList.java
│ │ ├── StringBuilderDemo.java
│ │ ├── StringEscapes.java
│ │ ├── StringRevChar.java
│ │ ├── StringReverse.java
│ │ ├── SubStringDemo.java
│ │ ├── Tabs.java
│ │ ├── Undent.java
│ │ ├── UnicodeChars.java
│ │ └── WolfInStringsClothing.java
│ ├── structure
│ │ ├── Array1.java
│ │ ├── Array2.java
│ │ ├── ArrayHunt.java
│ │ ├── ArrayIteratorDemo.java
│ │ ├── ArrayListDemo.java
│ │ ├── ArrayListGenericDemo.java
│ │ ├── ArrayTwoDObjects.java
│ │ ├── AutoboxDemo.java
│ │ ├── CallTrack.java
│ │ ├── EnumList.java
│ │ ├── ForeachDemo.java
│ │ ├── HashMapDemo.java
│ │ ├── HashMapWithRemoves.java
│ │ ├── IterableForEach.java
│ │ ├── IteratorDemo.java
│ │ ├── LinkList.java
│ │ ├── LinkedListDemo.java
│ │ ├── ListsOldAndNew.java
│ │ ├── MediaFancy.java
│ │ ├── MyStack.java
│ │ ├── MyStackDemo.java
│ │ ├── PrefsDemo.java
│ │ ├── Product.java
│ │ ├── PropsCompanies.java
│ │ ├── PropsDemo.java
│ │ ├── SetDemo.java
│ │ ├── SimpleStack.java
│ │ ├── SortArray.java
│ │ ├── StrSortCase.java
│ │ ├── SubstrCompDemo.java
│ │ ├── SubstringComparator.java
│ │ ├── SubstringComparatorDemo.java
│ │ ├── ToArray.java
│ │ ├── ToyStack.java
│ │ ├── ToyStack2.java
│ │ └── TreeSetDemo.java
│ ├── tar
│ │ └── demo.tar
│ ├── testing
│ │ ├── AssertDemo.java
│ │ ├── Hamcrest.java
│ │ ├── HamcrestDemo.java
│ │ └── PersonTest.java
│ ├── textproc
│ │ └── PSFormatter.java
│ ├── threads
│ │ ├── AutoSave.java
│ │ ├── Bounce.java
│ │ ├── Join.java
│ │ ├── ProdCons1.java
│ │ ├── ProdCons15.java
│ │ ├── ProdCons2.java
│ │ ├── ReadersWriterDemo.java
│ │ ├── RecursiveActionDemo.java
│ │ ├── RecursiveTaskDemo.java
│ │ ├── RunnableLambda.java
│ │ ├── Sprite.java
│ │ ├── StopBoolean.java
│ │ ├── StopClose.java
│ │ ├── Stopwatch.java
│ │ ├── ThreadsDemo1.java
│ │ ├── ThreadsDemo2.java
│ │ ├── ThreadsDemo3.java
│ │ ├── ThreadsDemo4.java
│ │ └── buzzin
│ │ │ └── BuzzInServlet.java
│ ├── webproxy
│ │ └── Handler.java
│ ├── webserver
│ │ ├── Httpd.java
│ │ └── HttpdConcurrent.java
│ ├── webserviceclient
│ │ └── RestClientFreeGeoIp.java
│ ├── xml
│ │ ├── DocWriteDOM.java
│ │ ├── JAXPTransform.java
│ │ ├── SAXLister.java
│ │ ├── XParse.java
│ │ ├── XPathDemo.java
│ │ ├── XTW.java
│ │ └── jaxb
│ │ │ └── Configuration.java
│ └── xmlform
│ │ ├── GenMIF.java
│ │ ├── XmlForm.java
│ │ └── test1.mif
└── resources
│ ├── META-INF
│ └── beans.xml
│ ├── json
│ └── softwareinfo.json
│ └── persistence.xml
└── test
└── java
├── com
└── darwinsys
│ ├── csv
│ └── CSVSimple.java
│ ├── io
│ └── TextAreaWriterTest.java
│ └── swingui
│ └── layout
│ └── EntryLayoutTest.java
├── io
└── IndentContLineReaderTest.java
├── oo
└── EqualsDemoTest.java
└── xml
└── jaxb
└── ConfigTest.java
/README.md:
--------------------------------------------------------------------------------
1 | Java Cookbook, 3e
2 | ================
3 |
4 | This is the example code than accompanies Java Cookbook, 3e by Ian F. Darwin (9781449337049).
5 |
6 | Click the Download Zip button to the right to download example code.
7 |
8 | Visit the catalog page [here](http://shop.oreilly.com/product/0636920026518.do).
9 |
10 | See an error? Report it [here](http://oreilly.com/catalog/errata.csp?isbn=0636920026518), or simply fork and send us a pull request.
11 |
--------------------------------------------------------------------------------
/javacooksrc/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Created-By: 1.8.0 (Oracle Corporation)
3 |
4 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/DISCLAIMER.txt:
--------------------------------------------------------------------------------
1 | Not all of the programs in this package have been adequately tested
2 | (in fact, a few have tests with @Ignore, so beware of those!!).
3 | As with any free open-source software, the user is entirely responsible
4 | for ensuring that the software functions correctly and meets their needs.
5 |
6 | You assume all risk of using this software!
7 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/README.txt:
--------------------------------------------------------------------------------
1 | This is a static snapshot of the code samples for the Java Cookbook, 3rd Edition.
2 |
3 | It was prepared by selecting files from several other repositories:
4 |
5 | http://github.com/IanDarwin/javasrc - the main part;
6 | http://github.com/IanDarwin/darwinsys-api - the "reusable API" parts;
7 | http://github.com/IanDarwin/javasrcee - Java Enterprise stuff, only a few examples.
8 |
9 | If you want to get updates to these files on a regular basis, you should
10 | 'git clone' those repos and 'git pull' periodcally.
11 |
12 | Thanks for reading the Java Cookbook!
13 |
14 | Ian Darwin
15 | http://darwinsys.com/java/
16 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/demo/java/com/darwinsys/io/FileIoDemo.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package com.darwinsys.io;
3 |
4 | import java.io.IOException;
5 |
6 | public class FileIoDemo {
7 | public static void main(String[] av) {
8 | try {
9 | FileIO.copyFile("FileIO.java", "FileIO.bak");
10 | FileIO.copyFile("FileIO.class", "FileIO-class.bak");
11 | } catch (IOException e) {
12 | System.err.println(e);
13 | }
14 | }
15 | }
16 | // END main
17 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/demo/java/com/darwinsys/swingui/WindowCloserDemo.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package com.darwinsys.swingui;
3 |
4 | import java.awt.Frame;
5 | import java.awt.Label;
6 | import com.darwinsys.swingui.WindowCloser;
7 |
8 | /* Example of closing a Window. */
9 | public class WindowCloserDemo {
10 |
11 | /* Main method */
12 | public static void main(String[] argv) {
13 | Frame f = new Frame("Close Me");
14 | f.add(new Label("Try Titlebar Close", Label.CENTER));
15 | f.setSize(100, 100);
16 | f.setVisible(true);
17 | f.addWindowListener(new WindowCloser(f, true));
18 | }
19 | }
20 | // END main
21 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/beans/BSFSample.java:
--------------------------------------------------------------------------------
1 | package beans;
2 |
3 | import org.apache.bsf.BSFManager;
4 |
5 | /** Sample of using Bean Scripting Framework with JPython */
6 | // BEGIN main
7 | public class BSFSample {
8 | public static void main(String[] args) {
9 | BSFManager manager = new BSFManager();
10 |
11 | // register scripting language
12 | String[] fntypes = { ".py" };
13 | BSFManager.registerScriptingEngine("jython",
14 | "org.apache.bsf.engines.jython.JythonEngine", fntypes);
15 |
16 | try {
17 | // try an expression
18 | Object r = manager.eval("jython", "testString", 0, 0, "22.0/7");
19 | System.out.println("Result type is " + r.getClass().getName());
20 | System.out.println("Result value is " + r);
21 | } catch (Exception ex) {
22 | System.err.println(ex.toString());
23 | }
24 | System.out.println("Scripting demo done.");
25 | return;
26 | }
27 | }
28 | // END main
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/com/darwinsys/lang/SysDep.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package com.darwinsys.lang;
3 |
4 | import java.io.File;
5 |
6 | /** Some things that are System Dependent.
7 | * All methods are static.
8 | * @author Ian Darwin
9 | */
10 | public class SysDep {
11 |
12 | final static String UNIX_NULL_DEV = "/dev/null";
13 | final static String WINDOWS_NULL_DEV = "NUL:";
14 | final static String FAKE_NULL_DEV = "jnk";
15 |
16 | /** Return the name of the "Null Device" on platforms which support it,
17 | * or "jnk" (to create an obviously well-named temp file) otherwise.
18 | */
19 | public static String getDevNull() {
20 |
21 | if (new File(UNIX_NULL_DEV).exists()) { // <1>
22 | return UNIX_NULL_DEV;
23 | }
24 |
25 | String sys = System.getProperty("os.name"); // <2>
26 | if (sys==null) { // <3>
27 | return FAKE_NULL_DEV;
28 | }
29 | if (sys.startsWith("Windows")) { // <4>
30 | return WINDOWS_NULL_DEV;
31 | }
32 | return FAKE_NULL_DEV; // <5>
33 | }
34 | }
35 | // END main
36 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/com/darwinsys/swingui/WindowCloser.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package com.darwinsys.swingui;
3 |
4 | import java.awt.Window;
5 | import java.awt.event.WindowAdapter;
6 | import java.awt.event.WindowEvent;
7 |
8 | /** A WindowCloser - watch for Window Closing events, and
9 | * follow them up with setVisible(false), dispose(), and optionally
10 | * ends (it all) with a System.exit(0).
11 | * @deprecated For simple closing, just use JFrame.setDefaultCloseOperation().
12 | */
13 | public class WindowCloser extends WindowAdapter {
14 |
15 | /** The window we are to close */
16 | Window win;
17 |
18 | /** True if we are to exit as well. */
19 | boolean doExit = false;
20 |
21 | /** Construct a WindowCloser that doesn't exit, just closes the window */
22 | public WindowCloser(Window w) {
23 | this(w, false);
24 | }
25 |
26 | /** Construct a WindowCloser with control over whether it exits */
27 | public WindowCloser(Window w, boolean exit) {
28 | win = w;
29 | doExit = exit;
30 | }
31 |
32 | /** Called by AWT when the user tries to close the window */
33 | public void windowClosing(WindowEvent e) {
34 | win.setVisible(false);
35 | win.dispose();
36 | if (doExit)
37 | System.exit(0);
38 | }
39 | }
40 | // END main
41 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/database/Address.java:
--------------------------------------------------------------------------------
1 | package database;
2 |
3 | // BEGIN main
4 | import javax.persistence.*;
5 |
6 | @Entity
7 | public class Address {
8 |
9 | private int id;
10 |
11 | private String streetAddress;
12 | private String city;
13 | private String country;
14 |
15 | @Id @GeneratedValue(strategy=GenerationType.AUTO)
16 | public int getId() {
17 | return id;
18 | }
19 | // Other accessors and methods omitted for brevity
20 | // END main
21 |
22 | public void setId(int id) {
23 | this.id = id;
24 | }
25 |
26 | public String getStreetAddress() {
27 | return streetAddress;
28 | }
29 |
30 | public void setStreetAddress(String streetAddress) {
31 | this.streetAddress = streetAddress;
32 | }
33 |
34 | public String getCity() {
35 | return city;
36 | }
37 |
38 | public void setCity(String city) {
39 | this.city = city;
40 | }
41 |
42 | public String getCountry() {
43 | return country;
44 | }
45 |
46 | public void setCountry(String country) {
47 | this.country = country;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/database/jdbc/LoadDriver.java:
--------------------------------------------------------------------------------
1 | package database.jdbc;
2 |
3 |
4 | /**
5 | * Load some drivers.
6 | */
7 | // BEGIN main
8 | public class LoadDriver {
9 | public static void main(String[] av) {
10 | try {
11 | // Try to load the jdbc-odbc bridge driver
12 | // Should be present on Sun JDK implementations.
13 | Class> c = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
14 | System.out.println("Loaded " + c.getName());
15 | // Try to load an Oracle driver.
16 | Class> d = Class.forName("oracle.jdbc.driver.OracleDriver");
17 | System.out.println("Loaded " + d.getName());
18 | } catch (ClassNotFoundException ex) {
19 | System.err.println(ex);
20 | }
21 | }
22 | }
23 | // END main
24 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/CurrentDateTime.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.LocalDateTime;
5 | import java.time.LocalTime;
6 |
7 | // BEGIN main
8 | public class CurrentDateTime {
9 | public static void main(String[] args) {
10 | LocalDate dNow = LocalDate.now();
11 | System.out.println(dNow);
12 | LocalTime tNow = LocalTime.now();
13 | System.out.println(tNow);
14 | LocalDateTime now = LocalDateTime.now();
15 | System.out.println(now);
16 | }
17 | }
18 | // END main
19 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/DateAdd.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | // BEGIN main
4 | import java.time.LocalDate;
5 | import java.time.Period;
6 |
7 | /** DateAdd -- compute the difference between two dates
8 | * (e.g., today and 700 days from now).
9 | */
10 | public class DateAdd {
11 | public static void main(String[] av) {
12 | /** Today's date */
13 | LocalDate now = LocalDate.now();
14 |
15 | Period p = Period.ofDays(700);
16 | LocalDate then = now.plus(p);
17 |
18 | System.out.printf("Seven hundred days from %s is %s%n", now, then);
19 | }
20 | }
21 | // END main
22 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/DateConversions.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.time.Instant;
4 | import java.time.LocalDateTime;
5 | import java.time.ZoneId;
6 | import java.time.ZonedDateTime;
7 |
8 | public class DateConversions {
9 | public static void main(String[] args) {
10 |
11 | // BEGIN main
12 | // Convert a number of Seconds since the Epoch, to a local date/time
13 | Instant epochSec = Instant.ofEpochSecond(1000000000L);
14 | ZoneId zId = ZoneId.systemDefault();
15 | ZonedDateTime then = ZonedDateTime.ofInstant(epochSec, zId);
16 | System.out.println("The epoch was a billion seconds old on " + then);
17 |
18 | // Convert a date/time to Epoch seconds
19 | long epochSecond = ZonedDateTime.now().toInstant().getEpochSecond();
20 | System.out.println("Current epoch seconds = " + epochSecond);
21 |
22 | LocalDateTime now = LocalDateTime.now();
23 | ZonedDateTime there = now.atZone(ZoneId.of("Canada/Pacific"));
24 | System.out.printf("When it's %s here, it's %s in Vancouver%n",
25 | now, there);
26 | // END main
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/DateDiff.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | // BEGIN main
4 | import java.time.LocalDate;
5 | import java.time.Period;
6 |
7 | public class DateDiff {
8 |
9 | public static void main(String[] args) {
10 | /** The date at the end of the last century */
11 | LocalDate endofCentury = LocalDate.of(2000, 12, 31);
12 | LocalDate now = LocalDate.now();
13 |
14 | Period diff = Period.between(endofCentury, now);
15 |
16 | System.out.printf("The 21st century (up to %s) is %s old%n", now, diff);
17 | System.out.printf(
18 | "The 21st century is %d years, %d months and %d days old",
19 | diff.getYears(), diff.getMonths(), diff.getDays());
20 | }
21 | }
22 | // END main
23 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/DateFormatter.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.ZonedDateTime;
5 | import java.time.format.DateTimeFormatter;
6 |
7 | // BEGIN main
8 | public class DateFormatter {
9 | public static void main(String[] args) {
10 |
11 | // Format a date ISO8601-like but with slashes instead of dashes
12 | DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/LL/dd");
13 | System.out.println(df.format(LocalDate.now()));
14 |
15 | // Parse a String to a date using the same formatter
16 | System.out.println(LocalDate.parse("2014/04/01", df));
17 |
18 | // Format a Date and Time without timezone information
19 | DateTimeFormatter nTZ =
20 | DateTimeFormatter.ofPattern("d MMMM, yyyy h:mm a");
21 | System.out.println(ZonedDateTime.now().format(nTZ));
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/DateParse.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.time.LocalDate;
4 | import java.time.LocalDateTime;
5 | import java.time.format.DateTimeFormatter;
6 |
7 | // BEGIN part1
8 | /** Show some date parses */
9 | public class DateParse {
10 | public static void main(String[] args) {
11 |
12 | String armisticeDate = "1914-11-11";
13 | LocalDate aLD = LocalDate.parse(armisticeDate);
14 | System.out.println("Date: " + aLD);
15 |
16 | String armisticeDateTime = "1914-11-11T11:11";
17 | LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime);
18 | System.out.println("Date/Time: " + aLDT);
19 | // END part1
20 |
21 | // BEGIN part2
22 | DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM uuuu");
23 | String anotherDate = "27 Jan 2011";
24 | LocalDate random = LocalDate.parse(anotherDate, df);
25 | System.out.println(anotherDate + " parses as " + random);
26 | // END part2
27 |
28 | System.out.println(aLD + " formats as " + df.format(aLD));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/EndOfTime64Msec.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.util.Date;
4 |
5 | /** When will a 64-bit timer based in mSec since 1970 come to the end of days?
6 | * Current answer: Sun Aug 17 02:12:55 EST 292278994
7 | * @author Ian Darwin
8 | */
9 | public class EndOfTime64Msec {
10 | public static void main(String[] args) {
11 | // BEGIN ofTime
12 | Date endOfTime = new Date(Long.MAX_VALUE);
13 | System.out.println("Java8 time overflows on " + endOfTime);
14 | // END ofTime
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/datetime/LegacyDates.java:
--------------------------------------------------------------------------------
1 | package datetime;
2 |
3 | import java.time.LocalDateTime;
4 | import java.time.ZoneId;
5 | import java.util.Calendar;
6 | import java.util.Date;
7 |
8 | // BEGIN main
9 | public class LegacyDates {
10 | public static void main(String[] args) {
11 |
12 | // There and back again, via Date
13 | Date legacyDate = new Date();
14 | System.out.println(legacyDate);
15 |
16 | LocalDateTime newDate =
17 | LocalDateTime.ofInstant(legacyDate.toInstant(),
18 | ZoneId.systemDefault());
19 | System.out.println(newDate);
20 |
21 | // And via Calendar
22 | Calendar c = Calendar.getInstance();
23 | System.out.println(c);
24 | LocalDateTime newCal =
25 | LocalDateTime.ofInstant(c.toInstant(),
26 | ZoneId.systemDefault());
27 | System.out.println(newCal);
28 | }
29 | }
30 | // END main
31 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/di/ControllerTightlyCoupled.java:
--------------------------------------------------------------------------------
1 | package di;
2 |
3 | import di.spring.ConsoleViewer;
4 | import di.spring.Model;
5 | import di.spring.SimpleModel;
6 |
7 | // BEGIN main
8 | public class ControllerTightlyCoupled {
9 |
10 | public static void main(String[] args) {
11 | Model m = new SimpleModel();
12 | View v = new ConsoleViewer();
13 | ((ConsoleViewer)v).setModel(m);
14 | v.displayMessage();
15 | }
16 | }
17 | // END main
18 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/di/View.java:
--------------------------------------------------------------------------------
1 | package di;
2 |
3 | // BEGIN main
4 | public interface View {
5 |
6 | void displayMessage();
7 |
8 | }
9 | // END main
10 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/di/javasecdi/CDIMain.java:
--------------------------------------------------------------------------------
1 | package di.javasecdi;
2 |
3 | import javax.enterprise.inject.Instance;
4 |
5 | import org.jboss.weld.environment.se.Weld;
6 |
7 | // BEGIN main
8 | public class CDIMain {
9 | public static void main(String[] args) {
10 | final Instance
");
9 | }
10 | }
11 | }
12 | // END main
13 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/performance/StringPrintB.java:
--------------------------------------------------------------------------------
1 | package performance;
2 |
3 | // BEGIN main
4 | public class StringPrintB {
5 | public static void main(String[] argv) {
6 | Object o = "Hello World";
7 | for (int i=0; i<100000; i++) {
8 | System.out.print("");
9 | System.out.print(o.toString());
10 | System.out.print("
");
11 | System.out.println();
12 | }
13 | }
14 | }
15 | // END main
16 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/ClassKeyword.java:
--------------------------------------------------------------------------------
1 | package reflection;
2 |
3 | import java.util.Calendar;
4 | /**
5 | * Show the class keyword and getClass() method in action.
6 | * The class keyword can be applied to any type known at compile time.
7 | *
8 | * @author Ian F. Darwin, http://www.darwinsys.com/
9 | */
10 | public class ClassKeyword {
11 | public static void main(String[] argv) {
12 | // BEGIN main
13 | System.out.println("Trying the ClassName.class keyword:");
14 | System.out.println("Object class: " + Object.class);
15 | System.out.println("String class: " + String.class);
16 | System.out.println("String[] class: " + String[].class);
17 | System.out.println("Calendar class: " + Calendar.class);
18 | System.out.println("Current class: " + ClassKeyword.class);
19 | System.out.println("Class for int: " + int.class);
20 | System.out.println();
21 |
22 | System.out.println("Trying the instance.getClass() method:");
23 | System.out.println("Sir Robin the Brave".getClass());
24 | System.out.println(Calendar.getInstance().getClass());
25 | // END main
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/CrossRefXML.java:
--------------------------------------------------------------------------------
1 | package reflection;
2 |
3 | import java.io.IOException;
4 | import java.lang.reflect.Field;
5 | import java.lang.reflect.Method;
6 |
7 | /** This class subclasss CrossRef to output the information in XML.
8 | */
9 | // BEGIN main
10 | public class CrossRefXML extends CrossRef {
11 |
12 | public static void main(String[] argv) throws IOException {
13 | CrossRef xref = new CrossRefXML();
14 | xref.doArgs(argv);
15 | }
16 |
17 | /** Print the start of a class.
18 | */
19 | protected void startClass(Class> c) {
20 | println("" + c.getName() + "");
21 | }
22 |
23 | protected void putField(Field fld, Class> c) {
24 | println("" + fld + "");
25 | }
26 |
27 | /** put a Method's information to the standard output.
28 | * Marked protected so you can override it (hint, hint).
29 | */
30 | protected void putMethod(Method method, Class> c) {
31 | println("" + method + "");
32 | }
33 |
34 | /** Print the end of a class.
35 | */
36 | protected void endClass() {
37 | println("");
38 | }
39 | }
40 | // END main
41 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/DefeatPrivacy.java:
--------------------------------------------------------------------------------
1 | package reflection;
2 |
3 | import java.lang.reflect.Field;
4 |
5 | // BEGIN main
6 | class X {
7 | @SuppressWarnings("unused") // Used surreptitiously below.
8 | private int p = 42;
9 | int q = 3;
10 | }
11 |
12 | /**
13 | * Demonstrate that it is, in fact, all too easy to access private members
14 | * of an object using Reflection, using the default SecurityManager (so this
15 | * will probably not work in an Applet, for example...).
16 | */
17 | public class DefeatPrivacy {
18 |
19 | public static void main(String[] args) throws Exception {
20 | new DefeatPrivacy().process();
21 | }
22 |
23 | private void process() throws Exception {
24 | X x = new X();
25 | System.out.println(x);
26 | // System.out.println(x.p); // Won't compile
27 | System.out.println(x.q);
28 | Class extends X> class1 = x.getClass();
29 | Field[] flds = class1.getDeclaredFields();
30 | for (Field f : flds) {
31 | f.setAccessible(true); // bye-bye "private"
32 | System.out.println(f + "==" + f.get(x));
33 | f.setAccessible(false); // reset to "correct" state
34 | }
35 | }
36 | }
37 | // END main
38 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/FindField.java:
--------------------------------------------------------------------------------
1 | package reflection;
2 |
3 | import java.lang.reflect.Field;
4 | import java.util.Calendar;
5 |
6 | /** This class shows using Reflection to get a field from another class. */
7 | // BEGIN main
8 | public class FindField {
9 |
10 | public static void main(String[] unused)
11 | throws NoSuchFieldException, IllegalAccessException {
12 |
13 | // Create instance of FindField
14 | FindField gf = new FindField();
15 |
16 | // Create instance of target class (YearHolder defined below).
17 | Object o = new YearHolder();
18 |
19 | // Use gf to extract a field from o.
20 | System.out.println("The value of 'currentYear' is: " +
21 | gf.intFieldValue(o, "currentYear"));
22 | }
23 |
24 | int intFieldValue(Object o, String name)
25 | throws NoSuchFieldException, IllegalAccessException {
26 | Class> c = o.getClass();
27 | Field fld = c.getField(name);
28 | int value = fld.getInt(o);
29 | return value;
30 | }
31 | }
32 |
33 | /** This is just a class that we want to get a field from */
34 | class YearHolder {
35 | /** Just a field that is used to show getting a field's value. */
36 | public int currentYear = Calendar.getInstance().get(Calendar.YEAR);
37 | }
38 | // END main
39 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/ListMethods.java:
--------------------------------------------------------------------------------
1 | package reflection;
2 |
3 | import java.lang.reflect.Constructor;
4 | import java.lang.reflect.Method;
5 |
6 | /**
7 | * List the Constructors and methods
8 | * @author Ian F. Darwin, http://www.darwinsys.com/
9 | */
10 | // BEGIN main
11 | public class ListMethods {
12 | public static void main(String[] argv) throws ClassNotFoundException {
13 | if (argv.length == 0) {
14 | System.err.println("Usage: ListMethods className");
15 | return;
16 | }
17 | Class> c = Class.forName(argv[0]);
18 | Constructor>[] cons = c.getConstructors();
19 | printList("Constructors", cons);
20 | Method[] meths = c.getMethods();
21 | printList("Methods", meths);
22 | }
23 | static void printList(String s, Object[] o) {
24 | System.out.println("*** " + s + " ***");
25 | for (int i=0; i cookletClass =
16 | (Class) Class.forName(cookletClassName);
17 | cooklet = cookletClass.newInstance();
18 | } catch (Exception e) {
19 | System.err.println("Error " + cookletClassName + e);
20 | }
21 | cooklet.initialize();
22 | cooklet.work();
23 | cooklet.terminate();
24 | }
25 | }
26 | // END main
27 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/reflection/cooklet/DemoCooklet.java:
--------------------------------------------------------------------------------
1 | package reflection.cooklet;
2 |
3 | // BEGIN main
4 | public class DemoCooklet extends Cooklet {
5 | public void work() {
6 | System.out.println("I am busy baking cookies.");
7 | }
8 | public void terminate() {
9 | System.out.println("I am shutting down my ovens now.");
10 | }
11 | }
12 | // END main
13 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/CanonEqDemo.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /**
6 | * CanonEqDemo - show use of Pattern.CANON_EQ, by comparing varous ways of
7 | * entering the Spanish word for "equal" and see if they are considered equal
8 | * by the RE-matching engine.
9 | *
10 | */
11 | // BEGIN main
12 | public class CanonEqDemo {
13 | public static void main(String[] args) {
14 | String pattStr = "\u00e9gal"; // egal
15 | String[] input = {
16 | "\u00e9gal", // egal - this one had better match :-)
17 | "e\u0301gal", // e + "Combining acute accent"
18 | "e\u02cagal", // e + "modifier letter acute accent"
19 | "e'gal", // e + single quote
20 | "e\u00b4gal", // e + Latin-1 "acute"
21 | };
22 | Pattern pattern = Pattern.compile(pattStr, Pattern.CANON_EQ);
23 | for (int i = 0; i < input.length; i++) {
24 | if (pattern.matcher(input[i]).matches()) {
25 | System.out.println(
26 | pattStr + " matches input " + input[i]);
27 | } else {
28 | System.out.println(
29 | pattStr + " does not match input " + input[i]);
30 | }
31 | }
32 | }
33 | }
34 | // END main
35 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/Grep0.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.io.*;
4 | import java.util.regex.*;
5 |
6 | /** Grep0 - Match lines from stdin against the pattern on the command line.
7 | */
8 | // BEGIN main
9 | public class Grep0 {
10 | public static void main(String[] args) throws IOException {
11 | BufferedReader is =
12 | new BufferedReader(new InputStreamReader(System.in));
13 | if (args.length != 1) {
14 | System.err.println("Usage: MatchLines pattern");
15 | System.exit(1);
16 | }
17 | Pattern patt = Pattern.compile(args[0]);
18 | Matcher matcher = patt.matcher("");
19 | String line = null;
20 | while ((line = is.readLine()) != null) {
21 | matcher.reset(line);
22 | if (matcher.find()) {
23 | System.out.println("MATCH: " + line);
24 | }
25 | }
26 | }
27 | }
28 | // END main
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/NLMatch.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /**
6 | * Show line ending matching using RE class.
7 | * @author Ian F. Darwin, http://www.darwinsys.com/
8 | */
9 | // BEGIN main
10 | public class NLMatch {
11 | public static void main(String[] argv) {
12 |
13 | String input = "I dream of engines\nmore engines, all day long";
14 | System.out.println("INPUT: " + input);
15 | System.out.println();
16 |
17 | String[] patt = {
18 | "engines.more engines",
19 | "ines\nmore",
20 | "engines$"
21 | };
22 |
23 | for (int i = 0; i < patt.length; i++) {
24 | System.out.println("PATTERN " + patt[i]);
25 |
26 | boolean found;
27 | Pattern p1l = Pattern.compile(patt[i]);
28 | found = p1l.matcher(input).find();
29 | System.out.println("DEFAULT match " + found);
30 |
31 | Pattern pml = Pattern.compile(patt[i],
32 | Pattern.DOTALL|Pattern.MULTILINE);
33 | found = pml.matcher(input).find();
34 | System.out.println("MultiLine match " + found);
35 | System.out.println();
36 | }
37 | }
38 | }
39 | // END main
40 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/RESimple.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /**
6 | * Simple example of using RE class.
7 | * @author Ian F. Darwin, http://www.darwinsys.com/
8 | */
9 | // BEGIN main
10 | public class RESimple {
11 | public static void main(String[] argv) {
12 | String pattern = "^Q[^u]\\d+\\.";
13 | String[] input = {
14 | "QA777. is the next flight. It is on time.",
15 | "Quack, Quack, Quack!"
16 | };
17 |
18 | Pattern p = Pattern.compile(pattern);
19 |
20 | for (String in : input) {
21 | boolean found = p.matcher(in).lookingAt();
22 |
23 | System.out.println("'" + pattern + "'" +
24 | (found ? " matches '" : " doesn't match '") + in + "'");
25 | }
26 | }
27 | }
28 | // END main
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/REmatch.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /**
6 | * REmatch -- demonstrate RE Match -> group()
7 | * @author Ian F. Darwin, http://www.darwinsys.com/
8 | */
9 | // BEGIN main
10 | public class REmatch {
11 | public static void main(String[] argv) {
12 |
13 | String patt = "Q[^u]\\d+\\.";
14 | Pattern r = Pattern.compile(patt);
15 | String line = "Order QT300. Now!";
16 | Matcher m = r.matcher(line);
17 | if (m.find()) {
18 | System.out.println(patt + " matches \"" +
19 | m.group(0) +
20 | "\" in \"" + line + "\"");
21 | } else {
22 | System.out.println("NO MATCH");
23 | }
24 | }
25 | }
26 | // END main
27 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/REmatchTwoFields.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /*
6 | * Reverse the order of two fields.
7 | * Input:
8 | * Adams, John Quincy
9 | * Output:
10 | * John Quincy Adams
11 | */
12 | // BEGIN main
13 | public class REmatchTwoFields {
14 | public static void main(String[] args) {
15 | String inputLine = "Adams, John Quincy";
16 | // Construct an RE with parens to "grab" both field1 and field2
17 | Pattern r = Pattern.compile("(.*), (.*)");
18 | Matcher m = r.matcher(inputLine);
19 | if (!m.matches())
20 | throw new IllegalArgumentException("Bad input");
21 | System.out.println(m.group(2) + ' ' + m.group(1));
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/REsubstr.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | import java.util.regex.*;
4 |
5 | /**
6 | * REsubstr -- demonstrate RE Match -> String.substring()
7 | * @author Ian F. Darwin, http://www.darwinsys.com/
8 | */
9 | public class REsubstr {
10 | public static void main(String[] argv) {
11 | // BEGIN main
12 | String patt = "Q[^u]\\d+\\.";
13 | Pattern r = Pattern.compile(patt);
14 | String line = "Order QT300. Now!";
15 | Matcher m = r.matcher(line);
16 | if (m.find()) {
17 | System.out.println(patt + " matches \"" +
18 | line.substring(m.start(0), m.end(0)) +
19 | "\" in \"" + line + "\"");
20 | } else {
21 | System.out.println("NO MATCH");
22 | }
23 | // END main
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/regex/StringConvenience.java:
--------------------------------------------------------------------------------
1 | package regex;
2 |
3 | /**
4 | * StringConvenience -- demonstrate java.lang.String convenience routine
5 | * @author Ian F. Darwin
6 | */
7 | // BEGIN main
8 | public class StringConvenience {
9 | public static void main(String[] argv) {
10 |
11 | String pattern = ".*Q[^u]\\d+\\..*";
12 | String line = "Order QT300. Now!";
13 | if (line.matches(pattern)) {
14 | System.out.println(line + " matches \"" + pattern + "\"");
15 | } else {
16 | System.out.println("NO MATCH");
17 | }
18 | }
19 | }
20 | // END main
21 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/DateClient.java:
--------------------------------------------------------------------------------
1 | package rmi;
2 |
3 | import java.rmi.Naming;
4 | import java.util.Date;
5 |
6 | // BEGIN main
7 | /* A very simple client for the RemoteDate service. */
8 | public class DateClient {
9 |
10 | /** The local proxy for the service. */
11 | protected static RemoteDate netConn = null;
12 |
13 | public static void main(String[] args) {
14 | try {
15 | netConn = (RemoteDate)Naming.lookup(RemoteDate.LOOKUPNAME);
16 | Date today = netConn.getRemoteDate();
17 | System.out.println(today.toString()); // Could use a DateFormat...
18 | } catch (Exception e) {
19 | System.err.println("RemoteDate exception: " + e.getMessage());
20 | e.printStackTrace();
21 | }
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/DateServer.java:
--------------------------------------------------------------------------------
1 | package rmi;
2 |
3 | import java.rmi.Naming;
4 |
5 | // BEGIN main
6 | public class DateServer {
7 | public static void main(String[] args) {
8 |
9 | // You may want a SecurityManager for downloading of classes:
10 | // System.setSecurityManager(new RMISecurityManager());
11 |
12 | try {
13 | // Create an instance of the server object
14 | RemoteDateImpl im = new RemoteDateImpl();
15 |
16 | System.out.println("DateServer starting...");
17 |
18 | // Publish it in the RMI registry.
19 | // Of course you have to have rmiregistry or equivalent running!
20 | Naming.rebind(RemoteDate.LOOKUPNAME, im);
21 |
22 | System.out.println("DateServer ready.");
23 | } catch (Exception e) {
24 | System.err.println(e);
25 | System.exit(1);
26 | }
27 | }
28 | }
29 | // END main
30 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/RemoteDate.java:
--------------------------------------------------------------------------------
1 | package rmi;
2 |
3 | import java.util.Date;
4 |
5 | // BEGIN main
6 | /** A statement of what the client & server must agree upon. */
7 | public interface RemoteDate extends java.rmi.Remote {
8 |
9 | /** The method used to get the current date on the remote */
10 | public Date getRemoteDate() throws java.rmi.RemoteException;
11 |
12 | /** The name used in the RMI registry service. */
13 | public final static String LOOKUPNAME = "RemoteDate";
14 | }
15 | // END main
16 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/RemoteDateImpl.java:
--------------------------------------------------------------------------------
1 | package rmi;
2 |
3 | import java.rmi.RemoteException;
4 | import java.rmi.server.UnicastRemoteObject;
5 | import java.util.Date;
6 |
7 | // BEGIN main
8 | public class RemoteDateImpl extends UnicastRemoteObject implements RemoteDate {
9 |
10 | /** Construct the object that implements the remote server.
11 | * Called from main, after it has the SecurityManager in place.
12 | */
13 | public RemoteDateImpl() throws RemoteException {
14 | super(); // sets up networking
15 | }
16 |
17 | /** The remote method that "does all the work". This won't get
18 | * called until the client starts up.
19 | */
20 | public Date getRemoteDate() throws RemoteException {
21 | return new Date();
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/callback/Client.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package rmi.callback;
3 |
4 | import java.rmi.*;
5 |
6 | /** Client -- the interface for the client callback */
7 | public interface Client extends Remote {
8 | public void alert(String mesg) throws RemoteException;
9 | }
10 | // END main
11 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/rmi/callback/TickerServer.java:
--------------------------------------------------------------------------------
1 | package rmi.callback;
2 |
3 | import java.rmi.Remote;
4 | import java.rmi.RemoteException;
5 |
6 | // BEGIN main
7 | public interface TickerServer extends Remote {
8 | public static final String LOOKUP_NAME = "Ticker_Service";
9 | public void connect(Client d) throws RemoteException;
10 | }
11 | // END main
12 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/starting/Buggy.java:
--------------------------------------------------------------------------------
1 | package starting;
2 |
3 | // BEGIN main
4 | /** This program exhibits some bugs, so we can use a debugger */
5 | public class Buggy {
6 | static String name;
7 |
8 | public static void main(String[] args) {
9 | int n = name.length(); // bug # 1
10 | System.out.println(n);
11 |
12 | name += "; The end."; // bug #2
13 | System.out.println(name); // #3
14 | }
15 | }
16 | // END main
17 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/starting/CheckForSwing.java:
--------------------------------------------------------------------------------
1 | package starting;
2 |
3 | /** Test for presence of Swing on classpath at runtime.
4 | */
5 | // BEGIN main
6 | public class CheckForSwing {
7 | public static void main(String[] args) {
8 | try {
9 | Class.forName("javax.swing.JButton");
10 | } catch (ClassNotFoundException e) {
11 | String failure =
12 | "Sorry, but this version of MyApp needs \n" +
13 | "a Java Runtime with JFC/Swing components\n" +
14 | "having the final names (javax.swing.*)";
15 | // Better to make something appear in the GUI. Either a
16 | // JOptionPane, or: myPanel.add(new Label(failure));
17 | System.err.println(failure);
18 | }
19 | // No need to print anything here - the GUI should work...
20 | }
21 | }
22 | // END main
23 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/starting/Deprec.java:
--------------------------------------------------------------------------------
1 | package starting;
2 |
3 | // BEGIN main
4 | import java.util.Date;
5 |
6 | /** Demonstrate deprecation warning */
7 | public class Deprec {
8 |
9 | public static void main(String[] av) {
10 |
11 | // Create a Date object for May 5, 1986
12 | Date d =
13 | new Date(86, 04, 05); // EXPECT DEPRECATION WARNING
14 | System.out.println("Date is " + d);
15 | }
16 | }
17 | // END main
18 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/starting/HelloWorld.java:
--------------------------------------------------------------------------------
1 | package starting;
2 |
3 | /**
4 | * Your basic, minimal, Hello World type program in Java.
5 | */
6 | // BEGIN main
7 | public class HelloWorld {
8 | public static void main(String[] argv) {
9 | System.out.println("Hello, World");
10 |
11 | }
12 | }
13 | // END main
14 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/Case.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /**
4 | * Control case.
5 | * @author Ian F. Darwin, http://www.darwinsys.com/
6 | */
7 | public class Case {
8 | public static void main(String[] argv) {
9 | // BEGIN main
10 | String name = "Java Cookbook";
11 | System.out.println("Normal:\t" + name);
12 | System.out.println("Upper:\t" + name.toUpperCase());
13 | System.out.println("Lower:\t" + name.toLowerCase());
14 | String javaName = "java cookBook"; // If it were Java identifiers :-)
15 | if (!name.equals(javaName))
16 | System.err.println("equals() correctly reports false");
17 | else
18 | System.err.println("equals() incorrectly reports true");
19 | if (name.equalsIgnoreCase(javaName))
20 | System.err.println("equalsIgnoreCase() correctly reports true");
21 | else
22 | System.err.println("equalsIgnoreCase() incorrectly reports false");
23 | // END main
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/ForEachChar.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | // BEGIN main
4 | public class ForEachChar {
5 | public static void main(String[] args) {
6 | String s = "Hello world";
7 | // for (char ch : s) {...} Does not work, in Java 7
8 | for (char ch : s.toCharArray()) {
9 | System.out.println(ch);
10 | }
11 | }
12 | }
13 | // END main
14 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/SoundexSimple.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /** Simple demonstration of Soundex. */
4 | // BEGIN main
5 | public class SoundexSimple {
6 |
7 | /** main */
8 | public static void main(String[] args) {
9 | String[] names = {
10 | "Darwin, Ian",
11 | "Davidson, Greg",
12 | "Darwent, William",
13 | "Derwin, Daemon"
14 | };
15 | for (String name : names) {
16 | System.out.println(Soundex.soundex(name) + ' ' + name);
17 | }
18 | }
19 | }
20 | // END main
21 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StrCharAt.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /** StrCharAt - show String.charAt()
4 | * @author Ian F. Darwin, http://www.darwinsys.com/
5 | */
6 | // BEGIN main
7 | public class StrCharAt {
8 | public static void main(String[] av) {
9 | String a = "A quick bronze fox lept a lazy bovine";
10 | for (int i=0; i < a.length(); i++) // Don't use foreach
11 | System.out.println("Char " + i + " is " + a.charAt(i));
12 | }
13 | }
14 | // END main
15 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringAlignSimple.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /* Align a page number on a 70-character line. */
4 | // BEGIN main
5 | public class StringAlignSimple {
6 |
7 | public static void main(String[] args) {
8 | // Construct a "formatter" to center strings.
9 | StringAlign formatter = new StringAlign(70, StringAlign.Justify.CENTER);
10 | // Try it out, for page "i"
11 | System.out.println(formatter.format("- i -"));
12 | // Try it out, for page 4. Since this formatter is
13 | // optimized for Strings, not specifically for page numbers,
14 | // we have to convert the number to a String
15 | System.out.println(formatter.format(Integer.toString(4)));
16 | }
17 | }
18 | // END main
19 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringBuilderCommaList.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | import java.util.StringTokenizer;
4 |
5 | public class StringBuilderCommaList {
6 | public static final String SAMPLE_STRING = "Alpha Bravo Charlie";
7 | public static void main(String[] args) {
8 |
9 | // BEGIN main
10 | // Method using regexp split
11 | StringBuilder sb1 = new StringBuilder();
12 | for (String word : SAMPLE_STRING.split(" ")) {
13 | if (sb1.length() > 0) {
14 | sb1.append(", ");
15 | }
16 | sb1.append(word);
17 | }
18 | System.out.println(sb1);
19 |
20 | // Method using a StringTokenizer
21 | StringTokenizer st = new StringTokenizer(SAMPLE_STRING);
22 | StringBuilder sb2 = new StringBuilder();
23 | while (st.hasMoreElements()) {
24 | sb2.append(st.nextToken());
25 | if (st.hasMoreElements()) {
26 | sb2.append(", ");
27 | }
28 | }
29 | System.out.println(sb2);
30 | // END main
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringBuilderDemo.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /**
4 | * StringBuilderDemo: construct the same String three different ways.
5 | */
6 | // BEGIN main
7 | public class StringBuilderDemo {
8 |
9 | public static void main(String[] argv) {
10 |
11 | String s1 = "Hello" + ", " + "World";
12 | System.out.println(s1);
13 |
14 | // Build a StringBuilder, and append some things to it.
15 | StringBuilder sb2 = new StringBuilder();
16 | sb2.append("Hello");
17 | sb2.append(',');
18 | sb2.append(' ');
19 | sb2.append("World");
20 |
21 | // Get the StringBuilder's value as a String, and print it.
22 | String s2 = sb2.toString();
23 | System.out.println(s2);
24 |
25 | // Now do the above all over again, but in a more
26 | // concise (and typical "real-world" Java) fashion.
27 |
28 | System.out.println(
29 | new StringBuilder()
30 | .append("Hello")
31 | .append(',')
32 | .append(' ')
33 | .append("World"));
34 | }
35 | }
36 | // END main
37 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringEscapes.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /**
4 | * StringEscapes.java - show string escapes.
5 | * Note that they may not print correctly on all platforms.
6 | */
7 | // BEGIN main
8 | public class StringEscapes {
9 | public static void main(String[] argv) {
10 | System.out.println("Java Strings in action:");
11 | // System.out.println("An alarm or alert: \a"); // not supported
12 | System.out.println("An alarm entered in Octal: \007");
13 | System.out.println("A tab key: \t(what comes after)");
14 | System.out.println("A newline: \n(what comes after)");
15 | System.out.println("A UniCode character: \u0207");
16 | System.out.println("A backslash character: \\");
17 | }
18 | }
19 | // END main
20 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringRevChar.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /**
4 | * Reverse a string by character
5 | * @author Ian F. Darwin, http://www.darwinsys.com/
6 | */
7 | public class StringRevChar {
8 | public static void main(String[] argv) {
9 | // BEGIN main
10 | String sh = "FCGDAEB";
11 | System.out.println(sh + " -> " + new StringBuilder(sh).reverse());
12 | // END main
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/StringReverse.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | import java.util.Stack;
4 | import java.util.StringTokenizer;
5 |
6 | /**
7 | * Reverse a string by word.
8 | */
9 | public class StringReverse {
10 | public static void main(String[] argv) {
11 | // BEGIN main
12 | String s = "Father Charles Goes Down And Ends Battle";
13 |
14 | // Put it in the stack frontwards
15 | Stack myStack = new Stack<>();
16 | StringTokenizer st = new StringTokenizer(s);
17 | while (st.hasMoreTokens()) {
18 | myStack.push(st.nextToken());
19 | }
20 |
21 | // Print the stack backwards
22 | System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
23 | while (!myStack.empty()) {
24 | System.out.print(myStack.pop());
25 | System.out.print(' ');
26 | }
27 | System.out.println('"');
28 | // END main
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/SubStringDemo.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | // BEGIN main
4 | public class SubStringDemo {
5 | public static void main(String[] av) {
6 | String a = "Java is great.";
7 | System.out.println(a);
8 | String b = a.substring(5); // b is the String "is great."
9 | System.out.println(b);
10 | String c = a.substring(5,7);// c is the String "is"
11 | System.out.println(c);
12 | String d = a.substring(5,a.length());// d is "is great."
13 | System.out.println(d);
14 | }
15 | }
16 | // END main
17 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/strings/UnicodeChars.java:
--------------------------------------------------------------------------------
1 | package strings;
2 |
3 | /**
4 | * Conversion between Unicode characters and Strings.
5 | * @author Ian F. Darwin, http://www.darwinsys.com/
6 | */
7 | public class UnicodeChars {
8 | public static void main(String[] argv) {
9 | // BEGIN main
10 | // UnicodeChars.java
11 | StringBuffer b = new StringBuffer();
12 | for (char c = 'a'; c<'d'; c++) {
13 | b.append(c);
14 | }
15 | b.append('\u00a5'); // Japanese Yen symbol
16 | b.append('\u01FC'); // Roman AE with acute accent
17 | b.append('\u0391'); // GREEK Capital Alpha
18 | b.append('\u03A9'); // GREEK Capital Omega
19 |
20 | for (int i=0; i arrayIterator = new ArrayIterator<>(names);
14 |
15 | // Java 5, 6 way
16 | for (String s : arrayIterator) {
17 | System.out.println(s);
18 | }
19 |
20 | // Java 8 way
21 | arrayIterator.forEach(s->System.out.println(s));
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ArrayListDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Date;
5 |
6 | /**
7 | * ArrayList Demo.
8 | */
9 | // BEGIN main
10 | public class ArrayListDemo {
11 | public static void main(String[] argv) {
12 | ArrayList al = new ArrayList<>();
13 |
14 | // Create a source of Objects
15 | StructureDemo source = new StructureDemo(15);
16 |
17 | // Add lots of elements to the ArrayList...
18 | al.add(source.getDate());
19 | al.add(source.getDate());
20 | al.add(source.getDate());
21 |
22 | // Print them out using old-style for loop to index number.
23 | System.out.println("Retrieving by index:");
24 | for (int i = 0; i data = new ArrayList<>();
9 | data.add("hello");
10 | data.add("goodbye");
11 |
12 | // data.add(new Date()); This won't compile!
13 |
14 | data.forEach(s -> System.out.println(s));
15 | }
16 | }
17 | // END main
18 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/AutoboxDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | public class AutoboxDemo {
5 |
6 | /** Shows autoboxing (in the call to foo(i), i is wrapped automatically)
7 | * and auto-unboxing (the return value is automatically unwrapped).
8 | */
9 | public static void main(String[] args) {
10 | int i = 42;
11 | int result = foo(i); // <1>
12 | System.out.println(result);
13 | }
14 |
15 | public static Integer foo(Integer i) {
16 | System.out.println("Object = " + i);
17 | return Integer.valueOf(123); // <2>
18 | }
19 | }
20 | // END main
21 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/EnumList.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | /** Simple demo to print all the types of an enum. */
4 | // BEGIN main
5 | public class EnumList {
6 | enum State {
7 | ON, OFF, UNKNOWN
8 | }
9 | public static void main(String[] args) {
10 | for (State i : State.values()) {
11 | System.out.println(i);
12 | }
13 | }
14 | }
15 | // END main
16 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ForeachDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | public class ForeachDemo {
7 |
8 | public static void main(String args[]) {
9 |
10 | // BEGIN main
11 | String[] data = { "Toronto", "Stockholm" };
12 | for (String s : data) {
13 | System.out.println(s);
14 | }
15 |
16 | // Show the Java 5 foreach loop - do not modernize to Java 8
17 | List list = Arrays.asList(data);
18 | for (String s : list) {
19 | System.out.println(s);
20 | }
21 | // END main
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/IterableForEach.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collection;
5 |
6 | // BEGIN main
7 | public class IterableForEach {
8 |
9 | public static void main(String[] args) {
10 | Collection c = // <1>
11 | Arrays.asList("One", "Two", "Three"); // <2>
12 | c.forEach(s -> System.out.println(s)); // <3>
13 | }
14 | }
15 | // END main
16 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/IteratorDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Date;
5 | import java.util.Iterator;
6 | import java.util.List;
7 |
8 | /** Iterator used to walk through a List.
9 | */
10 | // BEGIN main
11 | public class IteratorDemo {
12 |
13 | public static void main(String[] argv) {
14 |
15 | List l = new ArrayList<>();
16 | StructureDemo source = new StructureDemo(15);
17 |
18 | // Add lots of elements to the list...
19 | l.add(source.getDate());
20 | l.add(source.getDate());
21 | l.add(source.getDate());
22 |
23 | int i = 0;
24 |
25 | Iterator it = l.iterator();
26 |
27 | // Process the data structure using an iterator.
28 | // This part of the code does not know or care
29 | // if the data is an an array, a List, a Vector, or whatever.
30 | while (it.hasNext()) {
31 | Object o = it.next();
32 | System.out.println("Element " + i++ + " = " + o);
33 | }
34 | }
35 | }
36 | // END main
37 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/LinkedListDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.LinkedList;
4 | import java.util.ListIterator;
5 |
6 | /**
7 | * Demo of java.util.LinkedList class
8 | * using same example as my older LinkList class.
9 | * @author Ian Darwin, http://www.darwinsys.com/
10 | */
11 | // BEGIN main
12 | public class LinkedListDemo {
13 | public static void main(String[] argv) {
14 | System.out.println("Here is a demo of Java's LinkedList class");
15 | LinkedList l = new LinkedList<>();
16 | l.add(new Object().toString());
17 | l.add("Hello");
18 | l.add("end of the list");
19 |
20 | System.out.println("Here is a list of all the elements");
21 | ListIterator li = l.listIterator(0);
22 | while (li.hasNext())
23 | System.out.println("Next to: " + li.next());
24 |
25 | if (l.indexOf("Hello") < 0)
26 | System.err.println("Lookup does not work");
27 | else
28 | System.err.println("Lookup works");
29 |
30 | // Now, for added fun, let's walk the linked list backwards.
31 | while (li.hasPrevious()) {
32 | System.out.println("Back to: " + li.previous());
33 | }
34 | }
35 | }
36 | // END main
37 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ListsOldAndNew.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Demo of list processing pre- and post-Java 5.
7 | * Indentation is deliberately short, to fit the book formatting.
8 | */
9 | public class ListsOldAndNew {
10 |
11 | @SuppressWarnings("unchecked")
12 | public void oldWay() {
13 | @SuppressWarnings("rawtypes")
14 | // BEGIN oldWay
15 | List myList = new ArrayList();
16 | myList.add("hello");
17 | myList.add("goodbye");
18 |
19 | // myList.add(new Date()); This would compile but cause failures later
20 |
21 | for (int i = 0; i < myList.size(); i++) {
22 | String s = (String)myList.get(i);
23 | System.out.println(s);
24 | }
25 | // END oldWay
26 | }
27 |
28 | public void newWay() {
29 | // BEGIN newWay
30 | List myList = new ArrayList<>(); // Java 6: new ArrayList();
31 | myList.add("hello");
32 | myList.add("goodbye");
33 |
34 | // myList.add(new Date()); This would not compile!
35 |
36 | for (String s : myList) { // Look Ma, no downcast!
37 | System.out.println(s);
38 | }
39 | // END newWay
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/MediaFancy.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | /** An example of an enum with method overriding */
5 | public enum MediaFancy {
6 | /** The enum constant for a book, with a method override */
7 | BOOK {
8 | public String toString() { return "Book"; }
9 | },
10 | /** The enum constant for a Music CD */
11 | MUSIC_CD,
12 | /** ... */
13 | MUSIC_VINYL,
14 | MOVIE_VHS,
15 | MOVIE_DVD;
16 |
17 | /** It is generally disparaged to have a main() in an enum;
18 | * please forgive this tiny demo class for doing so.
19 | */
20 | public static void main(String[] args) {
21 | MediaFancy[] data = { BOOK, MOVIE_DVD, MUSIC_VINYL };
22 | for (MediaFancy mf : data) {
23 | System.out.println(mf);
24 | }
25 | }
26 | }
27 | // END main
28 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/MyStackDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | public class MyStackDemo {
5 | public static void main(String[] args) {
6 | MyStack ms1 = new MyStack<>();
7 | ms1.push("billg");
8 | ms1.push("scottm");
9 |
10 | while (ms1.hasNext()) {
11 | String name = ms1.pop();
12 | System.out.println(name);
13 | }
14 |
15 | // Old way of using Collections: not type safe.
16 | // DO NOT GENERICIZE THIS
17 | MyStack ms2 = new MyStack();
18 | ms2.push("billg"); // EXPECT WARNING
19 | ms2.push("scottm"); // EXPECT WARNING
20 | ms2.push(new java.util.Date()); // EXPECT WARNING
21 |
22 | // Show that it is broken
23 | try {
24 | String bad = (String)ms2.pop();
25 | System.err.println("Didn't get expected exception, popped " + bad);
26 | } catch (ClassCastException ex) {
27 | System.out.println("Did get expected exception.");
28 | }
29 |
30 | // Removed the brokenness, print rest of it.
31 | while (ms2.hasNext()) {
32 | String name = (String)ms2.pop();
33 | System.out.println(name);
34 | }
35 | }
36 | }
37 | // END main
38 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/Product.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | public class Product {
5 | String title;
6 | String artist;
7 | Media media;
8 |
9 | public Product(String artist, String title, Media media) {
10 | this.title = title;
11 | this.artist = artist;
12 | this.media = media;
13 | }
14 |
15 | @Override
16 | public String toString() {
17 | switch (media) {
18 | case BOOK:
19 | return title + " is a book";
20 | case MUSIC_CD:
21 | return title + " is a CD";
22 | case MUSIC_VINYL:
23 | return title + " is a relic of the age of vinyl";
24 | case MOVIE_VHS:
25 | return title + " is on old video tape";
26 | case MOVIE_DVD:
27 | return title + " is on DVD";
28 | default:
29 | return title + ": Unknown media " + media;
30 | }
31 | }
32 | }
33 | // END main
34 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/PropsCompanies.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Properties;
4 |
5 | /**
6 | * Demonstrate Properties reading/writing.
7 | * @see HashTableDemo, for the older Hashtable.
8 | */
9 | // BEGIN main
10 | public class PropsCompanies {
11 |
12 | public static void main(String[] argv) throws java.io.IOException {
13 |
14 | Properties props = new Properties();
15 |
16 | // Get my data
17 | props.put("Adobe", "Mountain View, CA");
18 | props.put("IBM", "White Plains, NY");
19 | props.put("Learning Tree", "Los Angeles, CA");
20 | props.put("Microsoft", "Redmond, WA");
21 | props.put("Netscape", "Mountain View, CA");
22 | props.put("O'Reilly", "Sebastopol, CA");
23 | props.put("Sun", "Mountain View, CA");
24 |
25 | // Now load additional properties
26 | props.load(System.in);
27 |
28 | // List merged properties, using System.out
29 | props.list(System.out);
30 | }
31 | }
32 | // END main
33 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/PropsDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Properties;
4 |
5 | /**
6 | * Demonstrate the Properties class
7 | */
8 | public class PropsDemo {
9 | public static void main(String[] argv) {
10 | Properties ian = new Properties();
11 |
12 | // Set my data.
13 | ian.setProperty("name", "Ian Darwin");
14 | ian.setProperty("favorite popsicle", "cherry");
15 | ian.setProperty("favorite rock group", "Fleetwood Mac");
16 | ian.setProperty("favorite programming language", "Java");
17 | ian.setProperty("pencil_color", "green");
18 |
19 | // should return the string "green".
20 | String ianColor = ian.getProperty("pencil_color");
21 |
22 | // Don't know what it will return.
23 | // BEGIN pencil.color
24 | String sysColor = System.getProperty("pencil_color");
25 | // END pencil.color
26 |
27 | // Now list the Properties, using System.out
28 | ian.list(System.out);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/SetDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Demonstrate the Set interface
8 | * @author Ian F. Darwin, http://www.darwinsys.com/
9 | */
10 | public class SetDemo {
11 | public static void main(String[] argv) {
12 | // BEGIN main
13 | Set hashSet = new HashSet<>();
14 | hashSet.add("One");
15 | hashSet.add("Two");
16 | hashSet.add("One"); // DUPLICATE
17 | hashSet.add("Three");
18 | hashSet.forEach(s -> System.out.println(s));
19 | // END main
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/SimpleStack.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | public interface SimpleStack {
5 |
6 | /** empty - return true if the stack is empty */
7 | abstract boolean empty();
8 |
9 | /** push - add an element onto the stack */
10 | abstract void push(T n);
11 |
12 | /** pop - return and remove the top element */
13 | abstract T pop();
14 |
15 | /** peek - return the top element but don't remove it */
16 | abstract T peek();
17 | }
18 | // END main
19 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/SortArray.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Arrays;
4 |
5 | /** Demonstrate use of Arrays.sort()
6 | */
7 | // BEGIN main
8 | public class SortArray {
9 | public static void main(String[] unused) {
10 | String[] strings = {
11 | "painful",
12 | "mainly",
13 | "gaining",
14 | "raindrops"
15 | };
16 | Arrays.sort(strings);
17 | for (int i=0; i {
9 | @Override
10 | public int compare(String s1, String s2) {
11 | s1 = s1.substring(1);
12 | s2 = s2.substring(1);
13 | return s1.compareTo(s2);
14 | // or, more concisely:
15 | // return s1.substring(1).compareTo(s2.substring(1));
16 | }
17 | }
18 | // END main
19 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/SubstringComparatorDemo.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.Arrays;
4 |
5 | /** Demonstrate use of SubstringComparator.
6 | */
7 | // BEGIN main
8 | public class SubstringComparatorDemo {
9 | public static void main(String[] unused) {
10 | String[] strings = {
11 | "painful",
12 | "mainly",
13 | "gaining",
14 | "raindrops"
15 | };
16 | Arrays.sort(strings);
17 | dump(strings, "Using Default Sort");
18 | Arrays.sort(strings, new SubstringComparator());
19 | dump(strings, "Using SubstringComparator");
20 | }
21 |
22 | static void dump(String[] args, String title) {
23 | System.out.println(title);
24 | for (String s : args)
25 | System.out.println(s);
26 | }
27 | }
28 | // END main
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ToArray.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /** List to array */
7 | public class ToArray {
8 | public static void main(String[] args) {
9 | // BEGIN main
10 | List list = new ArrayList<>();
11 | list.add("Blobbo");
12 | list.add("Cracked");
13 | list.add("Dumbo");
14 |
15 | // Convert a collection to Object[], which can store objects
16 | // of any type.
17 | Object[] ol = list.toArray();
18 | System.out.println("Array of Object has length " + ol.length);
19 |
20 | String[] sl = (String[]) list.toArray(new String[0]);
21 | System.out.println("Array of String has length " + sl.length);
22 | // END main
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ToyStack.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | /** Toy Stack.
4 | */
5 | // BEGIN main
6 | public class ToyStack {
7 |
8 | /** The maximum stack depth */
9 | protected int MAX_DEPTH = 10;
10 | /** The current stack depth */
11 | protected int depth = 0;
12 | /* The actual stack */
13 | protected int[] stack = new int[MAX_DEPTH];
14 |
15 | /** push - add an element onto the stack */
16 | protected void push(int n) {
17 | stack[depth++] = n;
18 | }
19 | /** pop - return and remove the top element */
20 | protected int pop() {
21 | return stack[--depth];
22 | }
23 | /** peek - return the top element but don't remove it */
24 | protected int peek() {
25 | return stack[depth-1];
26 | }
27 | }
28 | // END main
29 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/structure/ToyStack2.java:
--------------------------------------------------------------------------------
1 | package structure;
2 |
3 | // BEGIN main
4 | /** Toy Stack, converted to SimpleStack interface.
5 | */
6 | public class ToyStack2 implements SimpleStack {
7 |
8 | /** The maximum stack depth */
9 | protected int MAX_DEPTH = 10;
10 | /** The current stack depth */
11 | protected int depth = 0;
12 | /* The actual stack */
13 | protected int[] stack = new int[MAX_DEPTH];
14 |
15 | @Override
16 | public boolean empty() {
17 | return depth == 0;
18 | }
19 |
20 | @Override
21 | public void push(Integer n) {
22 | stack[depth++] = n;
23 | }
24 |
25 | @Override
26 | public Integer pop() {
27 | return stack[--depth];
28 | }
29 |
30 | @Override
31 | public Integer peek() {
32 | return stack[depth-1];
33 | }
34 | }
35 | // END main
36 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/tar/demo.tar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oreillymedia/java_cookbook_3e/59067b9fef99ca8d65d348a7445fc86db40319e4/javacooksrc/javacooksrc/main/java/tar/demo.tar
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/testing/AssertDemo.java:
--------------------------------------------------------------------------------
1 | package testing;
2 |
3 | /**
4 | * Demonstrate the new-in-1.4 "assert" facility.
5 | *
6 | * Java assertions are not enabled by default;
7 | * you must run with "java -enableassertions|-ea ...".
8 | * @since 1.4
9 | */
10 | // BEGIN main
11 | public class AssertDemo {
12 | public static void main(String[] args) {
13 | int i = 4;
14 | if (args.length == 1) {
15 | i = Integer.parseInt(args[0]);
16 | }
17 | assert i > 0 : "i is non-positive";
18 | System.out.println("Hello after an assertion");
19 | }
20 | }
21 | // END main
22 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/testing/Hamcrest.java:
--------------------------------------------------------------------------------
1 | package testing;
2 |
3 | import org.junit.*;
4 | import static org.junit.Assert.*;
5 |
6 | // BEGIN main
7 | public class HamcrestDemo {
8 |
9 | @Test
10 | public void testNameConcat() {
11 | Person p = new Person("Ian", "Darwin");
12 | String f = p.getFullName();
13 | assertThat("Name concatenation", f, equals("Ian Darwin"));
14 | }
15 | }
16 | // END main
17 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/testing/HamcrestDemo.java:
--------------------------------------------------------------------------------
1 | package testing;
2 |
3 | import static org.hamcrest.Matchers.containsString;
4 | import static org.hamcrest.Matchers.equalTo;
5 | import static org.hamcrest.Matchers.not;
6 | import static org.junit.Assert.assertThat;
7 |
8 | import org.junit.Test;
9 |
10 | // BEGIN main
11 | public class HamcrestDemo {
12 |
13 | @Test
14 | public void testNameConcat() {
15 | Person p = new Person("Ian", "Darwin");
16 | String f = p.getFullName();
17 | assertThat(f, containsString("Ian"));
18 | assertThat(f, equalTo("Ian Darwin"));
19 | assertThat(f, not(containsString("/"))); // contrived, to show syntax
20 | }
21 | }
22 | // END main
23 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/testing/PersonTest.java:
--------------------------------------------------------------------------------
1 | package testing;
2 |
3 | import org.junit.*;
4 | import static org.junit.Assert.*;
5 |
6 | /** A simple test case for Person */
7 | // BEGIN main
8 | public class PersonTest {
9 |
10 | @Test
11 | public void testNameConcat() {
12 | Person p = new Person("Ian", "Darwin");
13 | String f = p.getFullName();
14 | assertEquals("Name concatenation", "Ian Darwin", f);
15 | }
16 | }
17 | // END main
18 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/threads/RunnableLambda.java:
--------------------------------------------------------------------------------
1 | package threads;
2 |
3 | // BEGIN main
4 | public class RunnableLambda {
5 | public static void main(String[] args) {
6 | new Thread(() -> System.out.println("Hello from a thread")).start();
7 | }
8 | }
9 | // END main
10 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/webserver/HttpdConcurrent.java:
--------------------------------------------------------------------------------
1 | package webserver;
2 |
3 | import java.net.Socket;
4 | import java.util.concurrent.*;
5 |
6 | // BEGIN main
7 | /**
8 | * HttpConcurrent - Httpd Subclass using java.lang.concurrent
9 | */
10 | public class HttpdConcurrent extends Httpd {
11 |
12 | private final Executor myThreadPool;
13 |
14 | public HttpdConcurrent() throws Exception {
15 | super();
16 | myThreadPool = Executors.newFixedThreadPool(5);
17 | }
18 |
19 | public static void main(String[] argv) throws Exception {
20 | System.out.println("DarwinSys JavaWeb Server 0.1 starting...");
21 | HttpdConcurrent w = new HttpdConcurrent();
22 | if (argv.length == 2 && argv[0].equals("-p")) {
23 | w.startServer(Integer.parseInt(argv[1]));
24 | } else {
25 | w.startServer(HTTP);
26 | }
27 | w.runServer();
28 | }
29 | public void runServer() throws Exception {
30 | while (true) {
31 | final Socket clientSocket = sock.accept();
32 | myThreadPool.execute(new Runnable() {
33 | public void run() {
34 | new Handler(HttpdConcurrent.this).process(clientSocket);
35 | }
36 | });
37 | }
38 | }
39 | }
40 | // END main
41 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/webserviceclient/RestClientFreeGeoIp.java:
--------------------------------------------------------------------------------
1 | package webserviceclient;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.InputStreamReader;
5 | import java.net.URL;
6 | import java.net.URLConnection;
7 |
8 | // BEGIN main
9 | public class RestClientFreeGeoIp {
10 | public static void main(String[] args) throws Exception {
11 | URLConnection conn = new URL(
12 | "http://freegeoip.net/json/www.oreilly.com")
13 | .openConnection();
14 | try (BufferedReader is =
15 | new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
16 |
17 | String line;
18 | while ((line = is.readLine()) != null) {
19 | System.out.println(line);
20 | }
21 | }
22 | }
23 | }
24 | // END main
25 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/java/xml/JAXPTransform.java:
--------------------------------------------------------------------------------
1 | package xml;
2 |
3 | import java.io.File;
4 | import javax.xml.transform.Transformer;
5 | import javax.xml.transform.TransformerFactory;
6 | import javax.xml.transform.stream.StreamResult;
7 | import javax.xml.transform.stream.StreamSource;
8 |
9 | /** Illustrate simplest use of JAXP to transform using XSL.
10 | */
11 | // BEGIN main
12 | public class JAXPTransform {
13 |
14 | /**
15 | * @param args three filenames: XML, XSL, and Output (this order is historical).
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 |
20 | // Require three input args
21 | if (args.length != 3) {
22 | System.out.println(
23 | "Usage: java JAXPTransform inputFile.xml inputFile.xsl outputFile");
24 | System.exit(1);
25 | }
26 |
27 | // Create a transformer object
28 | Transformer tx = TransformerFactory.newInstance().newTransformer(
29 | new StreamSource(new File(args[1]))); // not 0
30 |
31 | // Use its transform() method to perform the transformation
32 | tx.transform(new StreamSource(new File(args[0])), // not 1
33 | new StreamResult(new File(args[2])));
34 | }
35 | }
36 | // END main
37 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/resources/META-INF/beans.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/resources/json/softwareinfo.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "robinparse",
3 | "version": "1.2.3",
4 | "description": "Another Parser for JSON",
5 | "className": "RobinParse",
6 | "contributors": [
7 | "Robin Smythe",
8 | "Jon Jenz",
9 | "Jan Ardann"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/main/resources/persistence.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 | org.hibernate.ejb.HibernatePersistence
10 | java:/jssurveyDatasource
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/test/java/com/darwinsys/csv/CSVSimple.java:
--------------------------------------------------------------------------------
1 | // BEGIN main
2 | package com.darwinsys.csv;
3 |
4 | import java.util.List;
5 |
6 | /* Simple demo of CSV parser class. */
7 | public class CSVSimple {
8 | public static void main(String[] args) {
9 | CSVImport parser = new CSVImport();
10 | List list = parser.parse(
11 | "\"LU\",86.25,\"11/4/1998\",\"2:19PM\",+4.0625");
12 | for (String word : list) {
13 | System.out.println(word);
14 | }
15 |
16 | // Now try with a non-default separator
17 | parser = new CSVImport('|');
18 | list = parser.parse(
19 | "\"LU\"|86.25|\"11/4/1998\"|\"2:19PM\"|+4.0625");
20 | for (String word : list) {
21 | System.out.println(word);
22 | }
23 | }
24 | }
25 | // END main
26 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/test/java/com/darwinsys/io/TextAreaWriterTest.java:
--------------------------------------------------------------------------------
1 | package com.darwinsys.io;
2 |
3 | import java.io.PrintWriter;
4 |
5 | import javax.swing.JTextArea;
6 |
7 | import junit.framework.TestCase;
8 |
9 | // BEGIN main
10 | public class TextAreaWriterTest extends TestCase {
11 |
12 | private static final String HELLO_WORLD = "Hello World";
13 |
14 | JTextArea ta = new JTextArea();
15 |
16 | public void testOne() {
17 | PrintWriter x = new PrintWriter(new TextAreaWriter(ta));
18 | x.print("Hello");
19 | x.print(' ');
20 | x.print("World");
21 | x.close();
22 | assertEquals(HELLO_WORLD, ta.getText());
23 | }
24 | }
25 | // END main
26 |
--------------------------------------------------------------------------------
/javacooksrc/javacooksrc/test/java/oo/EqualsDemoTest.java:
--------------------------------------------------------------------------------
1 | package oo;
2 |
3 | import static org.junit.Assert.assertTrue;
4 |
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | // BEGIN main
9 | /** Some JUnit test cases for EqualsDemo.
10 | * Writing a full set is left as "an exercise for the reader".
11 | */
12 | public class EqualsDemoTest {
13 |
14 | /** an object being tested */
15 | EqualsDemo d1;
16 | /** another object being tested */
17 | EqualsDemo d2;
18 |
19 | /** Method to be invoked before each test method */
20 | @Before
21 | public void setUp() {
22 | d1 = new EqualsDemo();
23 | d2 = new EqualsDemo();
24 | }
25 |
26 | @Test
27 | public void testSymmetry() {
28 | assertTrue(d1.equals(d1));
29 | }
30 |
31 | @Test
32 | public void testSymmetric() {
33 | assertTrue(d1.equals(d2) && d2.equals(d1));
34 | }
35 |
36 | @Test
37 | public void testCaution() {
38 | assertTrue(!d1.equals(null));
39 | }
40 | }
41 | // END main
42 |
--------------------------------------------------------------------------------