├── 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 weldInstance = new Weld().initialize().instance(); 11 | weldInstance.select(ConsoleViewer.class).get().displayMessage(); 12 | } 13 | } 14 | // END main 15 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/javasecdi/ConsoleViewer.java: -------------------------------------------------------------------------------- 1 | package di.javasecdi; 2 | 3 | import javax.inject.Inject; 4 | 5 | import di.View; 6 | 7 | // BEGIN main 8 | public class ConsoleViewer implements View { 9 | @Inject @MyModel 10 | private String message; 11 | 12 | @Override 13 | public void displayMessage() { 14 | System.out.println(message); 15 | } 16 | } 17 | // END main 18 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/javasecdi/Model.java: -------------------------------------------------------------------------------- 1 | package di.javasecdi; 2 | 3 | import java.io.IOException; 4 | import java.util.ResourceBundle; 5 | 6 | import javax.enterprise.inject.Produces; 7 | import javax.enterprise.inject.spi.InjectionPoint; 8 | 9 | // BEGIN main 10 | public class Model { 11 | 12 | public @Produces @MyModel String getModelData(InjectionPoint ip) 13 | throws IOException { 14 | 15 | ResourceBundle props = ResourceBundle.getBundle("messages"); 16 | return props.getString( 17 | ip.getMember().getDeclaringClass().getSimpleName() + "." + 18 | ip.getMember().getName()); 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/javasecdi/MyModel.java: -------------------------------------------------------------------------------- 1 | package di.javasecdi; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | import javax.inject.Qualifier; 8 | 9 | // BEGIN main 10 | @Qualifier 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) 13 | public @interface MyModel { 14 | } 15 | // END main 16 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/spring/ConsoleViewer.java: -------------------------------------------------------------------------------- 1 | package di.spring; 2 | 3 | import javax.annotation.Resource; 4 | 5 | import org.springframework.stereotype.Component; 6 | 7 | import di.View; 8 | 9 | // BEGIN main 10 | @Component("myView") 11 | public class ConsoleViewer implements View { 12 | 13 | Model messageProvider; 14 | 15 | @Override 16 | public void displayMessage() { 17 | System.out.println(messageProvider.getMessage()); 18 | } 19 | 20 | @Resource(name="myModel") 21 | public void setModel(Model messageProvider) { 22 | this.messageProvider = messageProvider; 23 | } 24 | 25 | } 26 | // END main 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/spring/Controller.java: -------------------------------------------------------------------------------- 1 | package di.spring; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 5 | 6 | import di.View; 7 | 8 | // BEGIN main 9 | public class Controller { 10 | 11 | public static void main(String[] args) { 12 | ApplicationContext ctx = 13 | new AnnotationConfigApplicationContext( "di.spring"); 14 | View v = ctx.getBean("myView", View.class); 15 | v.displayMessage(); 16 | } 17 | } 18 | // END main 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/spring/ControllerTightlyCoupled.java: -------------------------------------------------------------------------------- 1 | package di.spring; 2 | 3 | import di.View; 4 | 5 | // BEGIN main 6 | public class ControllerTightlyCoupled { 7 | 8 | public static void main(String[] args) { 9 | Model m = new SimpleModel(); 10 | View v = new ConsoleViewer(); 11 | ((ConsoleViewer)v).setModel(m); 12 | v.displayMessage(); 13 | } 14 | } 15 | // END main 16 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/di/spring/SimpleModel.java: -------------------------------------------------------------------------------- 1 | package di.spring; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | // BEGIN main 6 | @Component("myModel") 7 | public class SimpleModel implements Model { 8 | 9 | @Override 10 | public String getMessage() { 11 | return "This is some simple model data"; 12 | } 13 | } 14 | // END main 15 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/Creat.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | /** 7 | * Create one or more files by name. 8 | * The final "e" is omitted in homage to the underlying UNIX system call. 9 | * @author Ian F. Darwin, http://www.darwinsys.com/ 10 | */ 11 | // BEGIN main 12 | public class Creat { 13 | public static void main(String[] argv) throws IOException { 14 | 15 | // Ensure that a filename (or something) was given in argv[0] 16 | if (argv.length == 0) { 17 | System.err.println("Usage: Creat filename"); 18 | System.exit(1); 19 | } 20 | 21 | for (String a : argv) { 22 | // Constructing a File object doesn't affect the disk, but 23 | // the createNewFile() method does. 24 | new File(a).createNewFile(); 25 | } 26 | } 27 | } 28 | // END main 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/Delete.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | /** 7 | * Delete a file from within Java 8 | * @author Ian F. Darwin, http://www.darwinsys.com/ 9 | */ 10 | // BEGIN main 11 | public class Delete { 12 | public static void main(String[] argv) throws IOException { 13 | 14 | // Construct a File object for the backup created by editing 15 | // this source file. The file probably already exists. 16 | // Some text editors create backups by putting ~ at end of filename. 17 | File bkup = new File("Delete.java~"); 18 | // Now, delete it: 19 | bkup.delete(); 20 | } 21 | } 22 | // END main 23 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/Delete2.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * Delete a file from within Java, with error handling. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | // BEGIN main 10 | public class Delete2 { 11 | 12 | public static void main(String[] argv) { 13 | for (String a : argv) { 14 | delete(a); 15 | } 16 | } 17 | 18 | public static void delete(String fileName) { 19 | try { 20 | // Construct a File object for the file to be deleted. 21 | File target = new File(fileName); 22 | 23 | if (!target.exists()) { 24 | System.err.println("File " + fileName + 25 | " not present to begin with!"); 26 | return; 27 | } 28 | 29 | // Now, delete it: 30 | if (target.delete()) 31 | System.err.println("** Deleted " + fileName + " **"); 32 | else 33 | System.err.println("Failed to delete " + fileName); 34 | } catch (SecurityException e) { 35 | System.err.println("Unable to delete " + fileName + 36 | "(" + e.getMessage() + ")"); 37 | } 38 | } 39 | } 40 | // END main 41 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/FNFilter.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.*; 4 | import java.util.Arrays; 5 | 6 | /** 7 | * FNFilter - Ls directory lister modified to use FilenameFilter 8 | * @author Ian Darwin 9 | */ 10 | // BEGIN main 11 | public class FNFilter { 12 | public static void main(String argh_my_aching_fingers[]) { 13 | 14 | // Generate the selective list, with a one-use File object. 15 | String[] dirs = new java.io.File(".").list(new OnlyJava()); 16 | Arrays.sort(dirs); // Sort it (Data Structuring chapter)) 17 | for (String d : dirs) { 18 | System.out.println(d); // Print the list 19 | } 20 | } 21 | 22 | /** This class implements the FilenameFilter interface. 23 | * The Accept method returns true for .java, .class and .jar files. 24 | */ 25 | private static class OnlyJava implements FilenameFilter { 26 | public boolean accept(File dir, String s) { 27 | if (s.endsWith(".java") || 28 | s.endsWith(".class") || 29 | s.endsWith(".jar")) { 30 | 31 | return true; 32 | } 33 | // others: projects, ... ? 34 | return false; 35 | } 36 | } 37 | } 38 | // END main 39 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/FNFilterL.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.File; 4 | import java.util.Arrays; 5 | 6 | /** 7 | * FNFilter - Ls directory lister with a Lambda FilenameFilter 8 | * @author Ian Darwin 9 | */ 10 | public class FNFilterL { 11 | public static void main(String args[]) { 12 | 13 | String dirName = args.length > 0 ? args[0] : "."; 14 | if (!new File(dirName).exists()) { 15 | System.err.printf("File %s does not exist", dirName); 16 | System.exit(1); 17 | } 18 | 19 | // BEGIN main 20 | // Generate the selective list, with a Lambda Expression 21 | String[] dirs = new java.io.File(dirName).list( 22 | (dir, s) -> { 23 | return s.endsWith(".java") || 24 | s.endsWith(".class") || 25 | s.endsWith(".jar"); 26 | } 27 | ); 28 | Arrays.sort(dirs); // Sort it (see Data Structuring chapter)) 29 | for (String d : dirs) { 30 | System.out.println(d); // Print the list 31 | } 32 | // END main 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/ListRoots.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.*; 4 | 5 | // BEGIN main 6 | public class ListRoots { 7 | public static void main(String argh_my_aching_fingers[]) { 8 | File[] drives = File.listRoots(); // Get list of names 9 | for (File dr : drives) { 10 | System.out.println(dr); // Print the list 11 | } 12 | } 13 | } 14 | // END main 15 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/Ls.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.util.Arrays; 4 | 5 | /** Simple directory lister. 6 | * @author Ian Darwin, http://www.darwinsys.com/ 7 | */ 8 | // BEGIN main 9 | public class Ls { 10 | public static void main(String args[]) { 11 | String[] dirs = new java.io.File(".").list(); // Get list of names 12 | Arrays.sort(dirs); // Sort it (see <>) 13 | for (String dir : dirs) { 14 | System.out.println(dir); // Print the list 15 | } 16 | } 17 | } 18 | // END main 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/PathsFilesDemo.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.InputStream; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class PathsFilesDemo { 9 | public static void main(String[] args) throws Exception { 10 | // BEGIN main 11 | Path p = Paths.get("my_junk_file"); // <1> 12 | boolean deleted = Files.deleteIfExists(p); // <2> 13 | InputStream is = // <3> 14 | PathsFilesDemo.class.getResourceAsStream("/demo.txt"); 15 | long newFileSize = Files.copy(is, p); // <4> 16 | System.out.println(newFileSize); // <5> 17 | final Path realPath = p.toRealPath(); // <6> 18 | System.out.println(realPath); 19 | realPath.forEach(pc-> System.out.println(pc)); // <7> 20 | Files.delete(p); // <8> 21 | // END main 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/ReadOnly.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.*; 4 | 5 | // BEGIN main 6 | public class ReadOnly { 7 | public static void main(String[] a) throws IOException { 8 | 9 | File f = new File("f"); 10 | 11 | if (!f.createNewFile()) { 12 | System.out.println("Can't create new file."); 13 | return; 14 | } 15 | 16 | if (!f.canWrite()) { 17 | System.out.println("Can't write new file!"); 18 | return; 19 | } 20 | 21 | if (!f.setReadOnly()) { 22 | System.out.println("Grrr! Can't set file read-only."); 23 | return; 24 | } 25 | 26 | if (f.canWrite()) { 27 | System.out.println("Most immutable, captain!"); 28 | System.out.println("But it still says canWrite() after setReadOnly"); 29 | return; 30 | } else { 31 | System.out.println("Logical, captain!"); 32 | System.out.println( 33 | "canWrite() correctly returns false after setReadOnly"); 34 | } 35 | } 36 | } 37 | // END main 38 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/dir_file/Rename.java: -------------------------------------------------------------------------------- 1 | package dir_file; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * Rename a file in Java 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | // BEGIN main 10 | public class Rename { 11 | public static void main(String[] argv) throws IOException { 12 | 13 | // Construct the file object. Does NOT create a file on disk! 14 | File f = new File("Rename.java~"); // backup of this source file. 15 | 16 | // Rename the backup file to "junk.dat" 17 | // Renaming requires a File object for the target. 18 | f.renameTo(new File("junk.dat")); 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/domain/Address.java: -------------------------------------------------------------------------------- 1 | package domain; 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/ejb2/hello/Makefile: -------------------------------------------------------------------------------- 1 | CLASSES= Hello.class HelloEJB.class HelloHome.class 2 | 3 | hello.jar: $(CLASSES) 4 | jar cvf hello.jar META-INF $(CLASSES) 5 | 6 | install: hello.jar 7 | cp hello.jar /home/ian/jboss/jboss/deploy 8 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/email/MailConstants.java: -------------------------------------------------------------------------------- 1 | package email; 2 | 3 | // BEGIN main 4 | /** Simple list of Properties keys for the Mail System. */ 5 | public class MailConstants { 6 | public static final String PROPS_FILE_NAME = "MailClient.properties"; 7 | 8 | public static final String SEND_PROTO = "Mail.send.protocol"; 9 | public static final String SEND_USER = "Mail.send.user"; 10 | public static final String SEND_PASS = "Mail.send.password"; 11 | public static final String SEND_ROOT = "Mail.send.root"; 12 | public static final String SEND_HOST = "Mail.send.host"; 13 | public static final String SEND_DEBUG = "Mail.send.debug"; 14 | 15 | public static final String RECV_PROTO = "Mail.receive.protocol"; 16 | public static final String RECV_PORT = "Mail.receive.port"; 17 | public static final String RECV_USER = "Mail.receive.user"; 18 | public static final String RECV_PASS = "Mail.receive.password"; 19 | public static final String RECV_ROOT = "Mail.receive.root"; 20 | public static final String RECV_HOST = "Mail.receive.host"; 21 | public static final String RECV_DEBUG = "Mail.receive.debug"; 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/environ/GetEnv.java: -------------------------------------------------------------------------------- 1 | package environ; 2 | 3 | /** 4 | * Demo of System.getenv(). 5 | * This very basic OS-dependent method worked in 1.1 (and 1.2?), was 6 | * deprecated in 1.3, throws an exception in 1.4, and WORKS AGAIN in 1.5. 7 | */ 8 | // BEGIN main 9 | public class GetEnv { 10 | public static void main(String[] argv) { 11 | System.out.println("System.getenv(\"PATH\") = " + System.getenv("PATH")); 12 | } 13 | } 14 | // END main 15 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/environ/GetOptParseArgs.java: -------------------------------------------------------------------------------- 1 | package environ; 2 | 3 | import com.darwinsys.bleah.GetOpt; 4 | 5 | public class GetOptParseArgsDemo { 6 | public static void main(String[] args) { 7 | // BEGIN main 8 | GetOptDesc[] options = { 9 | new GetOptDesc('n', "numeric", false), 10 | new GetOptDesc('o', "output-file", true), 11 | }; 12 | Map optionsFound = new GetOpt(options).parseArguments(argv); 13 | if (optionsFound.get("n") != null) { 14 | System.out.println("sortType = NUMERIC;") 15 | } 16 | String outputFile = null; 17 | if ((outputFile = optionsFound.get("o") != null) { 18 | System.out.println("output file specified as " + outputFile) 19 | } else { 20 | System.out.println("Output to System.out"); 21 | } 22 | // END main 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/environ/GetOptParseArgsDemo.java: -------------------------------------------------------------------------------- 1 | package environ; 2 | 3 | import java.util.Map; 4 | import com.darwinsys.lang.GetOpt; 5 | import com.darwinsys.lang.GetOptDesc; 6 | 7 | public class GetOptParseArgsDemo { 8 | public static void main(String[] args) { 9 | // BEGIN main 10 | GetOptDesc[] options = { 11 | new GetOptDesc('n', "numeric", false), 12 | new GetOptDesc('o', "output-file", true), 13 | }; 14 | Map optionsFound = new GetOpt(options).parseArguments(args); 15 | if (optionsFound.get("n") != null) { 16 | System.out.println("sortType = NUMERIC;"); 17 | } 18 | String outputFile = null; 19 | if ((outputFile = optionsFound.get("o")) != null) { 20 | System.out.println("output file specified as " + outputFile); 21 | } else { 22 | System.out.println("Output to System.out"); 23 | } 24 | // END main 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/environ/GetOptSimple.java: -------------------------------------------------------------------------------- 1 | package environ; 2 | 3 | import com.darwinsys.lang.GetOpt; 4 | 5 | /** Trivial demonstration of GetOpt, the old way. If -h present, print help. 6 | * @author Ian F. Darwin, http://www.darwinsys.com/ 7 | */ 8 | // BEGIN main 9 | public class GetOptSimple { 10 | public static void main(String[] args) { 11 | GetOpt go = new GetOpt("h"); 12 | char c; 13 | while ((c = go.getopt(args)) != 0) { 14 | switch(c) { 15 | case 'h': 16 | helpAndExit(0); 17 | break; 18 | default: 19 | System.err.println("Unknown option in " + 20 | args[go.getOptInd()-1]); 21 | helpAndExit(1); 22 | } 23 | } 24 | System.out.println(); 25 | } 26 | 27 | /** Stub for providing help on usage 28 | * You can write a longer help than this, certainly. 29 | */ 30 | static void helpAndExit(int returnValue) { 31 | System.err.println("This would tell you how to use this program"); 32 | System.exit(returnValue); 33 | } 34 | } 35 | // END main 36 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/environ/SysPropDemo.java: -------------------------------------------------------------------------------- 1 | package environ; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * List one or more item(s) from System Properties 7 | */ 8 | // BEGIN main 9 | public class SysPropDemo { 10 | public static void main(String[] argv) throws IOException { 11 | if (argv.length == 0) 12 | // BEGIN sysprops 13 | System.getProperties().list(System.out); 14 | // END sysprops 15 | else { 16 | for (String s : argv) { 17 | System.out.println(s + " = " + 18 | System.getProperty(s)); 19 | } 20 | } 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/CameraSearchParallelStream.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | import java.util.List; 4 | 5 | public class CameraSearchParallelStream { 6 | 7 | static List privateListOfCameras = CameraUtils.getList(); 8 | 9 | // BEGIN search 10 | public static void main(String[] args) { 11 | for (Object camera : privateListOfCameras.parallelStream(). // <1> 12 | filter(c -> c.isIlc() && c.getPrice() < 500). // <2> 13 | toArray()) { // <3> 14 | System.out.println(camera); // <4> 15 | } 16 | } 17 | // END search 18 | } 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/CameraSearchPredicate.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Predicate; 6 | 7 | public class CameraSearchPredicate { 8 | 9 | List privateListOfCameras = CameraUtils.getList(); 10 | 11 | // BEGIN search 12 | public List search(Predicate tester) { 13 | List results = new ArrayList<>(); 14 | privateListOfCameras.forEach(c -> { 15 | if (tester.test(c)) 16 | results.add(c); 17 | }); 18 | return results; 19 | } 20 | // END search 21 | 22 | public static void main(String[] args) { 23 | CameraSearchPredicate searchApp = new CameraSearchPredicate(); 24 | List results = searchApp.search(c -> c.isIlc() && c.getPrice() < 500); 25 | System.out.println(results); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/ProcessIntsFunctional.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * A very silly demo of using a Functional Interface 7 | * @author Ian Darwin 8 | */ 9 | // BEGIN main 10 | public class ProcessIntsFunctional { 11 | static int[] integers = { 0, 1, 2, 3, 4, 5 }; 12 | 13 | /** Function to be called with an int and a Function; 14 | * just apply the function to the int and return the result 15 | */ 16 | static int doTheMath(int n, Function func) { 17 | return func.apply(n); 18 | } 19 | 20 | public static void main(String[] args) { 21 | 22 | int total = 0; 23 | for (int i : integers) { 24 | // Call doTheMath with 'i' and a Lambda for n^2 +1 25 | total += doTheMath(i, k -> k * k + 1 ); 26 | } 27 | System.out.println(total); 28 | } 29 | } 30 | // END main 31 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/ProcessIntsUsingFunctional.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | @FunctionalInterface 4 | // BEGIN define 5 | interface MyFunctionalInterface { 6 | int compute(int x); 7 | } 8 | // END define 9 | 10 | public class ProcessIntsUsingFunctional { 11 | // BEGIN use 12 | static int[] integers = {1, 2, 3}; 13 | 14 | public static void main(String[] args) { 15 | int total = 0; 16 | for (int i : integers) 17 | total += process(i, x -> x * x + 1); 18 | System.out.println("The total is " + total); 19 | } 20 | 21 | private static int process(int i, MyFunctionalInterface o) { 22 | return o.compute(i); 23 | } 24 | // END use 25 | } 26 | 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/ReferencesDemo.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | // BEGIN main 4 | /** "Walk, don't run" */ 5 | public class ReferencesDemo { 6 | 7 | // Assume this is an existing method we don't want to rename 8 | public void walk() { 9 | System.out.println("ReferencesDemo.walk(): Stand-in run method called"); 10 | } 11 | 12 | // This is our main processing method; it runs "walk" in a Thread 13 | public void doIt() { 14 | Runnable r = this::walk; 15 | new Thread(r).start(); 16 | } 17 | 18 | // The usual simple main method to start things off 19 | public static void main(String[] args) { 20 | new ReferencesDemo().doIt(); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/ReferencesDemo2.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | // BEGIN main 4 | public class ReferencesDemo2 { 5 | void cloz() { 6 | System.out.println("Stand-in close() method called"); 7 | } 8 | 9 | public static void main(String[] args) throws Exception { 10 | ReferencesDemo2 rd2 = new ReferencesDemo2(); 11 | 12 | // Use a method reference to assign the AutoCloseable interface 13 | // variable "ac" to the matching method signature "c" (obviously 14 | // short for close, but just to she the method name isn't what matters). 15 | try (AutoCloseable autoCloseable = rd2::cloz) { 16 | System.out.println("Some action happening here."); 17 | } 18 | } 19 | } 20 | // END main 21 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/functional/ReferencesDemo3.java: -------------------------------------------------------------------------------- 1 | package functional; 2 | 3 | // BEGIN main 4 | public class ReferencesDemo3 { 5 | 6 | interface FunInterface { 7 | void process(int i, String j, char c, double d); 8 | } 9 | 10 | public static void work(int i, String j, char c, double d){ 11 | System.out.println("Moo"); 12 | } 13 | 14 | public static void main(String[] args) { 15 | FunInterface sample = ReferencesDemo3::work; 16 | System.out.println("My process method is " + sample); 17 | } 18 | } 19 | // END main 20 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/graphics/AudioPlay.java: -------------------------------------------------------------------------------- 1 | package graphics; 2 | 3 | import java.net.URL; 4 | 5 | import javax.sound.sampled.AudioInputStream; 6 | import javax.sound.sampled.AudioSystem; 7 | import javax.sound.sampled.Clip; 8 | 9 | /** 10 | * Simple program to play sound files 11 | */ 12 | // BEGIN main 13 | public class AudioPlay { 14 | 15 | static String defSounds[] = { 16 | "/audio/test.wav", 17 | "/music/midi/Beet5th.mid", 18 | }; 19 | 20 | public static void main(String[] av) { 21 | if (av.length == 0) 22 | main(defSounds); 23 | else for (String a : av) { 24 | System.out.println("Playing " + a); 25 | try { 26 | URL snd = AudioPlay.class.getResource(a); 27 | if (snd == null) { 28 | System.err.println("Cannot getResource " + a); 29 | continue; 30 | } 31 | AudioInputStream audioInputStream = 32 | AudioSystem.getAudioInputStream(snd); 33 | final Clip clip = AudioSystem.getClip(); 34 | clip.open(audioInputStream); 35 | clip.start(); 36 | } catch (Exception e) { 37 | System.err.println(e); 38 | } 39 | } 40 | } 41 | } 42 | // END main 43 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/graphics/DrawStringDemo.java: -------------------------------------------------------------------------------- 1 | package graphics; 2 | 3 | import java.awt.*; 4 | import javax.swing.*; 5 | 6 | // BEGIN main 7 | public class DrawStringDemo extends JComponent { 8 | 9 | private static final long serialVersionUID = -7199469682507443122L; 10 | 11 | int textX = 10, textY = 20; 12 | 13 | @Override 14 | public void paintComponent(Graphics g) { 15 | g.drawString("Hello Java", textX, textY); 16 | } 17 | 18 | public Dimension getPreferredSize() { 19 | return new Dimension(100, 100); 20 | } 21 | } 22 | 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/graphics/PaintDemo.java: -------------------------------------------------------------------------------- 1 | package graphics; 2 | 3 | import java.awt.Color; 4 | import java.awt.Component; 5 | import java.awt.Dimension; 6 | import java.awt.Graphics; 7 | 8 | // BEGIN main 9 | public class PaintDemo extends Component { 10 | 11 | private static final long serialVersionUID = -5595189404659801913L; 12 | int rectX = 20, rectY = 30; 13 | int rectWidth = 50, rectHeight = 50; 14 | 15 | /** 16 | * Component subclasses can override paint(), but 17 | * JComponent subclasses should normally use paintComponent() 18 | * instead, to avoid clobbering border painting and the like. 19 | */ 20 | @Override 21 | public void paint(Graphics g) { 22 | g.setColor(Color.red); 23 | g.fillRect(rectX, rectY, rectWidth, rectHeight); 24 | } 25 | 26 | @Override 27 | public Dimension getPreferredSize() { 28 | return new Dimension(100, 100); 29 | } 30 | } 31 | 32 | // END main 33 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/ButtonDemo.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.FlowLayout; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | 7 | import javax.swing.JButton; 8 | import javax.swing.JFrame; 9 | 10 | // BEGIN main 11 | /** Demonstrate simple use of Button */ 12 | public class ButtonDemo extends JFrame implements ActionListener { 13 | JButton b1; 14 | 15 | public ButtonDemo() { 16 | setLayout(new FlowLayout()); 17 | add(b1 = new JButton("A button")); 18 | b1.addActionListener(this); 19 | setSize(300, 200); 20 | } 21 | 22 | public void actionPerformed(ActionEvent event) { 23 | System.out.println("Thanks for pushing my button!"); 24 | } 25 | 26 | public static void main(String[] unuxed) { 27 | new ButtonDemo().setVisible(true); 28 | } 29 | } 30 | // END main 31 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/ButtonDemo2L.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.FlowLayout; 4 | 5 | import javax.swing.JButton; 6 | import javax.swing.JFrame; 7 | import javax.swing.JOptionPane; 8 | 9 | // BEGIN main 10 | /** Demonstrate a JButton with Lambda Action Listeners */ 11 | public class ButtonDemo2L extends JFrame { 12 | 13 | private static final long serialVersionUID = 1L; 14 | 15 | public ButtonDemo2L() { 16 | super("ButtonDemo Lambda"); 17 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 | setLayout(new FlowLayout()); 19 | JButton b; 20 | add(b = new JButton("A button")); 21 | // Minimalist style 22 | b.addActionListener(e -> JOptionPane.showMessageDialog(this, 23 | "Thanks for pushing my first button!")); 24 | 25 | add(b = new JButton("Another button")); 26 | // Longer style, with { } around body. 27 | b.addActionListener(e -> { 28 | JOptionPane.showMessageDialog(this, 29 | "Thanks for pushing my second button!"); 30 | } 31 | ); 32 | 33 | pack(); 34 | } 35 | 36 | public static void main(String[] args) { 37 | new ButtonDemo2L().setVisible(true); 38 | } 39 | } 40 | // END main 41 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/ButtonDemo2a.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.applet.Applet; 4 | import java.awt.Button; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | /** Demonstrate use of two buttons, using a single ActionListener, 9 | * being the class itself. 10 | */ 11 | // BEGIN main 12 | public class ButtonDemo2a extends Applet implements ActionListener { 13 | Button b1, b2; 14 | 15 | public void init() { 16 | add(b1 = new Button("A button")); 17 | b1.addActionListener(this); 18 | 19 | add(b2 = new Button("Another button")); 20 | b2.addActionListener(this); 21 | } 22 | 23 | public void actionPerformed(ActionEvent e) { 24 | if (e.getSource() == b1) 25 | showStatus("Thanks for pushing my first button!"); 26 | else 27 | showStatus("Thanks for pushing my second button!"); 28 | } 29 | } 30 | // END main 31 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/ButtonDemo2b.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.applet.Applet; 4 | import java.awt.Button; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | /** Demonstrate use of two buttons, using a single ActionListener 9 | * made of a named inner class 10 | */ 11 | // BEGIN main 12 | public class ButtonDemo2b extends Applet { 13 | Button b1, b2; 14 | ActionListener handler = new ButtonHandler(); 15 | 16 | public void init() { 17 | add(b1 = new Button("A button")); 18 | b1.addActionListener(handler); 19 | 20 | add(b2 = new Button("Another button")); 21 | b2.addActionListener(handler); 22 | } 23 | 24 | class ButtonHandler implements ActionListener { 25 | public void actionPerformed(ActionEvent e) { 26 | if (e.getSource() == b1) 27 | showStatus("Thanks for pushing my first button!"); 28 | else 29 | showStatus("Thanks for pushing my second button!"); 30 | } 31 | } 32 | } 33 | // END main 34 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/ContentPane.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.Container; 4 | 5 | import javax.swing.JFrame; 6 | import javax.swing.JLabel; 7 | 8 | // BEGIN main 9 | public class ContentPane extends JFrame { 10 | public ContentPane() { 11 | Container cp = getContentPane(); 12 | // now add Components to "cp"... 13 | cp.add(new JLabel("A Really Simple Demo", JLabel.CENTER)); 14 | } 15 | } 16 | // END main 17 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/JFrameDemoSafe.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.EventQueue; 4 | 5 | import javax.swing.JFrame; 6 | 7 | /** Create a JFrame class in a thread-safe way. 8 | *
9 | * See http://java.sun.com/developer/JDCTechTips/2003/tt1208.html. 10 | */ 11 | // BEGIN main 12 | public class JFrameDemoSafe { 13 | // We need a main program to instantiate and show. 14 | public static void main(String[] args) { 15 | 16 | // Create the GUI (variable is final because used by inner class). 17 | final JFrame demo = new JFrameDemo(); 18 | 19 | // Create a Runnable to set the main visible, and get Swing to invoke. 20 | EventQueue.invokeLater(new Runnable() { 21 | public void run() { 22 | demo.setVisible(true); 23 | } 24 | }); 25 | } 26 | } 27 | // END main 28 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/JFrameFlowLayout.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.Container; 4 | import java.awt.FlowLayout; 5 | 6 | import javax.swing.JButton; 7 | import javax.swing.JFrame; 8 | import javax.swing.JLabel; 9 | 10 | // BEGIN main 11 | public class JFrameFlowLayout extends JFrame { 12 | public JFrameFlowLayout() { 13 | Container cp = getContentPane(); 14 | 15 | // Make sure it has a FlowLayout layoutmanager. 16 | cp.setLayout(new FlowLayout()); 17 | 18 | // now add Components to "cp"... 19 | cp.add(new JLabel("Wonderful?")); 20 | cp.add(new JButton("Yes!")); 21 | pack(); 22 | } 23 | 24 | // We need a main program to instantiate and show. 25 | public static void main(String[] args) { 26 | new JFrameFlowLayout().setVisible(true); 27 | } 28 | } 29 | // END main 30 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/RunOnEdt.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import javax.swing.JOptionPane; 4 | import javax.swing.SwingUtilities; 5 | 6 | // BEGIN main 7 | public class RunOnEdt { 8 | public static void main(String[] args) throws Exception { 9 | System.out.println("RunOnEdt.main()"); 10 | SwingUtilities.invokeLater(new Runnable() { 11 | public void run() { 12 | try { 13 | JOptionPane.showMessageDialog(null, "Hello Java"); 14 | } catch (Exception e) { 15 | e.printStackTrace(); 16 | } 17 | } 18 | }); 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/SpinnerDemo.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.Container; 4 | import java.awt.GridLayout; 5 | 6 | import javax.swing.JFrame; 7 | import javax.swing.JSpinner; 8 | import javax.swing.SpinnerDateModel; 9 | import javax.swing.SpinnerListModel; 10 | 11 | /** 12 | * Demonstrate the Swing "Spinner" control. 13 | * @author ian 14 | */ 15 | // BEGIN main 16 | public class SpinnerDemo { 17 | 18 | public static void main(String[] args) { 19 | JFrame jf = new JFrame("It Spins"); 20 | Container cp = jf.getContentPane(); 21 | cp.setLayout(new GridLayout(0,1)); 22 | 23 | // Create a JSpinner using one of the pre-defined SpinnerModels 24 | JSpinner dates = new JSpinner(new SpinnerDateModel()); 25 | cp.add(dates); 26 | 27 | // Create a JSPinner using a SpinnerListModel. 28 | String[] data = { "One", "Two", "Three" }; 29 | JSpinner js = new JSpinner(new SpinnerListModel(data)); 30 | cp.add(js); 31 | 32 | jf.setSize(100, 80); 33 | jf.setVisible(true); 34 | } 35 | } 36 | 37 | // END main 38 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/TabPaneDemo.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import javax.swing.JFrame; 4 | import javax.swing.JLabel; 5 | import javax.swing.JTabbedPane; 6 | 7 | // BEGIN main 8 | public class TabPaneDemo { 9 | protected JTabbedPane tabPane; 10 | public TabPaneDemo() { 11 | tabPane = new JTabbedPane(); 12 | tabPane.add(new JLabel("One", JLabel.CENTER), "First"); 13 | tabPane.add(new JLabel("Two", JLabel.CENTER), "Second"); 14 | } 15 | 16 | public static void main(String[] a) { 17 | JFrame f = new JFrame("Tab Demo"); 18 | f.getContentPane().add(new TabPaneDemo().tabPane); 19 | f.setSize(120, 100); 20 | f.setVisible(true); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui/WindowDemo.java: -------------------------------------------------------------------------------- 1 | package gui; 2 | 3 | import java.awt.Frame; 4 | import java.awt.event.WindowAdapter; 5 | import java.awt.event.WindowEvent; 6 | 7 | /* Show an example of closing an AWT Frame. 8 | * @author Ian Darwin 9 | */ 10 | // BEGIN main 11 | public class WindowDemo extends Frame { 12 | 13 | public static void main(String[] argv) { 14 | Frame f = new WindowDemo(); 15 | f.setVisible(true); 16 | } 17 | public WindowDemo() { 18 | setSize(200, 100); 19 | addWindowListener(new WindowDemoAdapter()); 20 | } 21 | 22 | /** Named Inner class that closes a Window. */ 23 | class WindowDemoAdapter extends WindowAdapter { 24 | public void windowClosing(WindowEvent e) { 25 | // whimsy - close randomly, ~ 1 times in 3 26 | if (Math.random() > 0.666) { 27 | System.out.println("Goodbye!"); 28 | WindowDemo.this.setVisible(false); // window will close 29 | WindowDemo.this.dispose(); // and be freed up. 30 | System.exit(0); 31 | } 32 | System.out.println("You asked me to close, but not to I chose."); 33 | } 34 | } 35 | } 36 | // END main 37 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/gui_awt/ButtonDemo2c.java: -------------------------------------------------------------------------------- 1 | package gui_awt; 2 | 3 | import java.applet.Applet; 4 | import java.awt.Button; 5 | import java.awt.event.ActionEvent; 6 | import java.awt.event.ActionListener; 7 | 8 | /** Demonstrate use of Button */ 9 | // BEGIN main 10 | public class ButtonDemo2c extends Applet { 11 | Button b; 12 | 13 | public void init() { 14 | add(b = new Button("A button")); 15 | b.addActionListener(new ActionListener() { 16 | public void actionPerformed(ActionEvent e) { 17 | showStatus("Thanks for pushing my first button!"); 18 | } 19 | }); 20 | add(b = new Button("Another button")); 21 | b.addActionListener(new ActionListener() { 22 | public void actionPerformed(ActionEvent e) { 23 | showStatus("Thanks for pushing my second button!"); 24 | } 25 | }); 26 | } 27 | } 28 | // END main 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/i18n/ListLocales.java: -------------------------------------------------------------------------------- 1 | package i18n; 2 | 3 | import java.util.Locale; 4 | 5 | public class ListLocales { 6 | public static void main(String[] args) { 7 | // BEGIN main 8 | Locale[] list = Locale.getAvailableLocales(); 9 | for (Locale loc : list) { 10 | System.out.println(loc); 11 | } 12 | // END main 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/i18n/MessageFormatDemo.java: -------------------------------------------------------------------------------- 1 | package i18n; 2 | 3 | import java.text.*; 4 | 5 | // BEGIN main 6 | public class MessageFormatDemo { 7 | 8 | static Object[] data = { 9 | new java.util.Date(), 10 | "myfile.txt", 11 | "could not be opened" 12 | }; 13 | 14 | public static void main(String[] args) { 15 | String result = MessageFormat.format( 16 | "At {0,time} on {0,date}, {1} {2}.", data); 17 | System.out.println(result); 18 | } 19 | } 20 | // END main 21 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/i18n/MessageFormatDemoIntl.java: -------------------------------------------------------------------------------- 1 | package i18n; 2 | 3 | import java.text.*; 4 | import java.util.*; 5 | 6 | // BEGIN main 7 | public class MessageFormatDemoIntl { 8 | 9 | private static Date date = new Date(); 10 | private static String fileName = "myfile.txt"; 11 | 12 | public static void main(String[] args) { 13 | ResourceBundle rb = ResourceBundle.getBundle("Widgets"); 14 | String format = rb.getString("filedialogs.cantopen.format"); 15 | String result = MessageFormat.format(format, date, fileName); 16 | System.out.println(result); 17 | } 18 | } 19 | // END main 20 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/i18n/SetLocale.java: -------------------------------------------------------------------------------- 1 | package i18n; 2 | 3 | import java.text.*; 4 | import java.util.*; 5 | 6 | /** Change the default locale */ 7 | // BEGIN main 8 | public class SetLocale { 9 | public static void main(String[] args) { 10 | 11 | switch (args.length) { 12 | case 0: 13 | Locale.setDefault(Locale.FRANCE); 14 | break; 15 | case 1: 16 | throw new IllegalArgumentException(); 17 | case 2: 18 | Locale.setDefault(new Locale(args[0], args[1])); 19 | break; 20 | default: 21 | System.out.println("Usage: SetLocale [language [country]]"); 22 | // FALLTHROUGH 23 | } 24 | 25 | DateFormat df = DateFormat.getInstance(); 26 | NumberFormat nf = NumberFormat.getInstance(); 27 | 28 | System.out.println(df.format(new Date())); 29 | System.out.println(nf.format(123.4567)); 30 | } 31 | } 32 | // END main 33 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/i18n/UseLocales.java: -------------------------------------------------------------------------------- 1 | package i18n; 2 | 3 | import java.text.*; 4 | import java.util.*; 5 | 6 | /** Use some locales 7 | * choices or -Duser.lang= or -Duser.region=. 8 | */ 9 | // BEGIN main 10 | public class UseLocales { 11 | public static void main(String[] args) { 12 | 13 | Locale frLocale = Locale.FRANCE; // predefined 14 | Locale ukLocale = new Locale("en", "UK"); // English, UK version 15 | 16 | DateFormat defaultDateFormatter = DateFormat.getDateInstance( 17 | DateFormat.MEDIUM); 18 | DateFormat frDateFormatter = DateFormat.getDateInstance( 19 | DateFormat.MEDIUM, frLocale); 20 | DateFormat ukDateFormatter = DateFormat.getDateInstance( 21 | DateFormat.MEDIUM, ukLocale); 22 | 23 | Date now = new Date(); 24 | System.out.println("Default: " + ' ' + 25 | defaultDateFormatter.format(now)); 26 | System.out.println(frLocale.getDisplayName() + ' ' + 27 | frDateFormatter.format(now)); 28 | System.out.println(ukLocale.getDisplayName() + ' ' + 29 | ukDateFormatter.format(now)); 30 | } 31 | } 32 | // END main 33 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/BadNewline.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | /** 4 | * DON'T DO THIS. THIS IS BAD CODE. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class BadNewline { 8 | // BEGIN main 9 | String myName; 10 | public static void main(String[] argv) { 11 | BadNewline jack = new BadNewline("Jack Adolphus Schmidt, III"); 12 | System.out.println(jack); 13 | } 14 | /** 15 | * DON'T DO THIS. THIS IS BAD CODE. 16 | */ 17 | public String toString() { 18 | return "BadNewlineDemo@" + hashCode() + "\n" + myName; 19 | } 20 | 21 | // The obvious Constructor is not shown for brevity; it's in the code 22 | // END main 23 | /* Constructor */ 24 | public BadNewline(String s) { 25 | myName = s; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/CatStdin.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * Read and print, using BufferedReader from System.in, onto System.out 7 | */ 8 | // BEGIN main 9 | public class CatStdin { 10 | 11 | public static void main(String[] av) { 12 | try { 13 | BufferedReader is = 14 | new BufferedReader(new InputStreamReader(System.in)); 15 | String inputLine; 16 | 17 | while ((inputLine = is.readLine()) != null) { 18 | System.out.println(inputLine); 19 | } 20 | is.close(); 21 | } catch (IOException e) { 22 | System.out.println("IOException: " + e); 23 | } 24 | } 25 | } 26 | // END main 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/CharMode.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * Read a file in character mode - maximally inefficient. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | public class CharMode { 10 | public static void main(String[] argv) throws IOException { 11 | // BEGIN main 12 | BufferedReader is = new BufferedReader( 13 | new InputStreamReader(System.in)); 14 | 15 | int c; 16 | while ((c=is.read()) != -1) { 17 | System.out.print((char)c); 18 | } 19 | // END main 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ConsoleRead.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | /** 4 | * Read a name from the user; Requires Java 6 or later; does not run under Eclipse. 5 | */ 6 | // BEGIN main 7 | public class ConsoleRead { 8 | public static void main(String[] args) { 9 | String name = System.console().readLine("What is your name?"); 10 | System.out.println("Hello, " + name.toUpperCase()); 11 | } 12 | } 13 | // END main 14 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/FormatterDates.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | 6 | /** Demonstrate some usage patterns and format-code examples 7 | * of the Formatter class. 8 | */ 9 | // BEGIN main 10 | public class FormatterDates { 11 | public static void main(String[] args) { 12 | 13 | // Format number as dates e.g., 2014-06-28 14 | System.out.printf("%4d-%02d-%2d%n", 2014, 6, 28); 15 | 16 | // Format fields directly from a Date object: multiple fields from "1$" 17 | // (hard-coded formatting for Date not advisable; see I18N chapter) 18 | Date today = Calendar.getInstance().getTime(); 19 | // Might print e.g., July 4, 2015: 20 | System.out.printf("Today is %1$tB %1$td, %1$tY%n", today); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/GoodNewline.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * Multiple lines output from one method. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | public class GoodNewline { 10 | // BEGIN main 11 | String myName; 12 | public static void main(String[] argv) { 13 | GoodNewline jack = new GoodNewline("Jack Adolphus Schmidt, III"); 14 | jack.print(System.out); 15 | } 16 | 17 | protected void print(PrintStream out) { 18 | out.println(toString()); // classname and hashcode 19 | out.println(myName); // print name on next line 20 | } 21 | 22 | // END main 23 | /* Constructor */ 24 | public GoodNewline(String s) { 25 | myName = s; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ReadCharsOneAtATime.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.IOException; 4 | import java.io.Reader; 5 | 6 | /** This works, but is likely to be very slow. */ 7 | // BEGIN main 8 | public class ReadCharsOneAtATime { 9 | 10 | void doFile(Reader is) throws IOException { 11 | int c; 12 | while ((c=is.read( )) != -1) { 13 | System.out.print((char)c); 14 | } 15 | } 16 | } 17 | // END main 18 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ReadGZIP.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | import java.util.zip.*; 5 | 6 | /** 7 | * Read some data from a gzip file. 8 | * @author Ian F. Darwin, http://www.darwinsys.com/ 9 | */ 10 | // BEGIN main 11 | public class ReadGZIP { 12 | public static void main(String[] argv) throws IOException { 13 | String FILENAME = "file.txt.gz"; 14 | 15 | // Since there are 4 constructor calls here, I wrote them out in full. 16 | // In real life you would probably nest these constructor calls. 17 | FileInputStream fin = new FileInputStream(FILENAME); 18 | GZIPInputStream gzis = new GZIPInputStream(fin); 19 | InputStreamReader xover = new InputStreamReader(gzis); 20 | BufferedReader is = new BufferedReader(xover); 21 | 22 | String line; 23 | // Now read lines of text: the BufferedReader puts them in lines, 24 | // the InputStreamReader does Unicode conversion, and the 25 | // GZipInputStream "gunzip"s the data from the FileInputStream. 26 | while ((line = is.readLine()) != null) 27 | System.out.println("Read: " + line); 28 | } 29 | } 30 | // END main 31 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ReadPassword.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.Console; 4 | 5 | /** 6 | * Read a password from the user. 7 | * REQUIRES JAVA 6 or later. 8 | */ 9 | // BEGIN main 10 | public class ReadPassword { 11 | public static void main(String[] args) { 12 | Console cons; 13 | if ((cons = System.console()) != null) { 14 | char[] passwd = null; 15 | try { 16 | passwd = cons.readPassword("Password:"); 17 | // In real life you would send the password into authentication code 18 | System.out.println("Your password was: " + new String(passwd)); 19 | } finally { 20 | // Shred this in-memory copy for security reasons 21 | if (passwd != null) { 22 | java.util.Arrays.fill(passwd, ' '); 23 | } 24 | } 25 | } else { 26 | throw new RuntimeException("No console, can't get password"); 27 | } 28 | } 29 | } 30 | // END main 31 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ReadStdin.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | /** 4 | * Read one byte from Standard Input - hardly useful on its own. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class ReadStdin { 8 | /** Simple test case */ 9 | public static void main(String[] ap) { 10 | // BEGIN main 11 | int b = 0; 12 | try { 13 | b = System.in.read(); 14 | System.out.println("Read this data: " + (char)b); 15 | } catch (Exception e) { 16 | System.out.println("Caught " + e); 17 | } 18 | // END main 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ReadStdinInt.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | /** 5 | * Read an int from Standard Input 6 | * @author Ian F. Darwin, http://www.darwinsys.com/ 7 | */ 8 | // BEGIN main 9 | public class ReadStdinInt { 10 | public static void main(String[] ap) { 11 | String line = null; 12 | int val = 0; 13 | try { 14 | BufferedReader is = new BufferedReader( 15 | new InputStreamReader(System.in)); 16 | line = is.readLine(); 17 | val = Integer.parseInt(line); 18 | System.out.println("I read this number: " + val); 19 | } catch (NumberFormatException ex) { 20 | System.err.println("Not a valid number: " + line); 21 | } catch (IOException e) { 22 | System.err.println("Unexpected IO ERROR: " + e); 23 | } 24 | } 25 | } 26 | // END main 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/Redirect.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * "Redirect" or reassign some standard descriptors. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | public class Redirect { 10 | public static void main(String[] argv) throws IOException { 11 | // BEGIN main 12 | String LOGFILENAME = "error.log"; 13 | System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME))); 14 | System.out.println("Please look for errors in " + LOGFILENAME); 15 | // Now assume this is somebody else's code; you'll see it 16 | // writing to stderr... 17 | int[] a = new int[5]; 18 | a[10] = 0; // here comes an ArrayIndexOutOfBoundsException 19 | // END main 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/ScannerDemo.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ScannerDemo { 6 | 7 | public static void main(String[] args) { 8 | // BEGIN main 9 | String sampleDate = "25 Dec 1988"; 10 | 11 | try (Scanner sDate = new Scanner(sampleDate)) { 12 | int dayOfMonth = sDate.nextInt(); 13 | String month = sDate.next(); 14 | int year = sDate.nextInt(); 15 | System.out.printf("%d-%s-%02d%n", year, month, dayOfMonth); 16 | } 17 | // END main 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/SerialDemoAbstractBase.java: -------------------------------------------------------------------------------- 1 | // BEGIN main 2 | package io; 3 | 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** Demonstrate use of Serialization. Typical Subclass main will be: 9 | * public static void main(String[] s) throws Exception { 10 | * new SerialDemoXXX().save(); // in parent class; calls write 11 | * new SerialDemoXXX().dump(); 12 | * } 13 | */ 14 | public abstract class SerialDemoAbstractBase { 15 | 16 | /** The save method in an application */ 17 | public void save() throws IOException { 18 | List l = new ArrayList<>(); 19 | // Gather the data 20 | l.add(new MyData("Ian Darwin", "secret_java_cook")); 21 | l.add(new MyData("Abby Brant", "dujordian")); 22 | write(l); 23 | } 24 | 25 | /** Does the actual serialization */ 26 | public abstract void write(Object theGraph) throws IOException; 27 | 28 | /** Reads the file and displays it. */ 29 | public abstract void dump() throws IOException, ClassNotFoundException; 30 | } 31 | // END main 32 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/Stdout.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | /** 4 | * All the examples for the Standard output recipe. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class Stdout { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | Object anObject = new Object(); 11 | String myAnswer = "no"; 12 | int i = 42; 13 | 14 | System.out.println("Hello, World of Java"); 15 | System.out.println("An object is " + anObject); 16 | System.out.println("The answer is " + myAnswer + " at this time."); 17 | System.out.println("The answer is " + i + '.'); 18 | System.out.println("The answer is " + i + "."); 19 | System.out.println(i + '=' + " the answer."); 20 | System.out.println(new StringBuffer("The answer is ").append(i).append('.')); 21 | // END main 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/io/WriteBinary.java: -------------------------------------------------------------------------------- 1 | package io; 2 | 3 | import java.io.*; 4 | 5 | /** 6 | * Write some data in binary. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | // BEGIN main 10 | public class WriteBinary { 11 | public static void main(String[] argv) throws IOException { 12 | int i = 42; 13 | double d = Math.PI; 14 | String FILENAME = "binary.dat"; 15 | DataOutputStream os = new DataOutputStream( 16 | new FileOutputStream(FILENAME)); 17 | os.writeInt(i); 18 | os.writeDouble(d); 19 | os.close(); 20 | System.out.println("Wrote " + i + ", " + d + " to file " + FILENAME); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/javafx/AudioPlay.java: -------------------------------------------------------------------------------- 1 | package javafx; 2 | 3 | import javafx.scene.media.Media; 4 | import javafx.scene.media.MediaPlayer; 5 | 6 | // BEGIN main 7 | /** Simple Audio Playing with JavaFX */ 8 | public class AudioPlay { 9 | public static void main(String[] args) { 10 | String clipName = "demo.mp3"; 11 | Media clip = new Media(clipName); 12 | MediaPlayer mediaPlayer = new MediaPlayer(clip); 13 | mediaPlayer.play(); 14 | } 15 | } 16 | // END main 17 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/javafx/HelloFx.java: -------------------------------------------------------------------------------- 1 | package javafx; 2 | 3 | // BEGIN main 4 | import javafx.application.Application; // <1> 5 | import javafx.event.ActionEvent; 6 | import javafx.event.EventHandler; 7 | import javafx.scene.Scene; 8 | import javafx.scene.control.Button; 9 | import javafx.scene.layout.StackPane; 10 | import javafx.stage.Stage; 11 | 12 | public class HelloFx extends Application { // <2> 13 | 14 | @Override 15 | public void start(Stage stage) { // <3> 16 | stage.setTitle("JavaFX Hello!"); 17 | Button btn = new Button(); 18 | btn.setText("Run Greeting"); 19 | btn.setOnAction(new EventHandler() { // <4> 20 | @Override 21 | public void handle(ActionEvent e) { 22 | System.out.println("Hello from JavaFX"); 23 | } 24 | }); 25 | 26 | StackPane rootPane = new StackPane(); // <5> 27 | rootPane.getChildren().add(btn); 28 | stage.setScene(new Scene(rootPane, 300, 200)); 29 | stage.show(); 30 | } 31 | 32 | public static void main(String[] args) { // <6> 33 | launch(args); 34 | } 35 | } 36 | // END main 37 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jaxwsclient/TinyClientMain.java: -------------------------------------------------------------------------------- 1 | package jaxwsclient; 2 | 3 | // BEGIN main 4 | // no imports! 5 | 6 | /** Two-line client for Calc Service, complete code. */ 7 | public class TinyClientMain { 8 | public static void main(String[] args) { 9 | Calc client = new CalcService().getCalcPort(); 10 | System.out.println(client.add(2, 2)); 11 | } 12 | } 13 | // END main 14 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jaxwsservice/Calc.java: -------------------------------------------------------------------------------- 1 | package jaxwsservice; 2 | 3 | // BEGIN main 4 | import javax.jws.WebService; 5 | 6 | @WebService(targetNamespace="http://toy.service/") 7 | public class Calc { 8 | 9 | public int add(int a, int b) { 10 | System.out.println("CalcImpl.add()"); 11 | return a + b; 12 | } 13 | // The other three methods are pretty simple too 14 | // END main 15 | 16 | public int subtract(int a, int b) { 17 | System.out.println("CalcImpl.subtract()"); 18 | return a - b; 19 | } 20 | 21 | public int multiply(int a, int b) { 22 | System.out.println("CalcImpl.multiply()"); 23 | return a * b; 24 | } 25 | 26 | public int divide(int a, int b) { 27 | System.out.println("CalcImpl.divide()"); 28 | if (b == 0) { 29 | // slightly better-than-average message 30 | throw new ArithmeticException( 31 | "You tried to divide " + a + " by 0"); 32 | } 33 | return a / b; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jaxwsservice/ServiceMain.java: -------------------------------------------------------------------------------- 1 | package jaxwsservice; 2 | 3 | import javax.xml.ws.Endpoint; 4 | 5 | /** Java 6 and later allow simple web services to be 6 | * "deployed" using just the Java SE. So just run this! 7 | * No need to make up a war structure, two config files, 8 | * jar up and deploy. 9 | */ 10 | public class ServiceMain { 11 | 12 | public static void main(String[] args) { 13 | // BEGIN main 14 | // Create the "service stub" 15 | Calc impl = new Calc(); 16 | // Start the service running 17 | Endpoint ep = 18 | Endpoint.publish("http://localhost:9090/calc", impl); 19 | System.out.println("Endpoint running: " + ep); 20 | // END main 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jdb/Problem.java: -------------------------------------------------------------------------------- 1 | package jdb; 2 | 3 | /** 4 | * A Program with a Problem 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class Problem { 8 | public static void main(String argv[]) { 9 | // BEGIN main 10 | System.out.println(System.getproperties()); // EXPECT COMPILE ERROR 11 | // END main 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jni/HelloJni.c: -------------------------------------------------------------------------------- 1 | /* BEGIN main */ 2 | #include 3 | #include "HelloJni.h" 4 | #include 5 | /* 6 | * This is the Java Native implementation of displayHelloJni. 7 | */ 8 | JNIEXPORT void JNICALL Java_HelloJni_displayHelloJni(JNIEnv *env, jobject this) { 9 | jfieldID fldid; 10 | jint n, nn; 11 | 12 | (void)printf("Hello from a Native Method\n"); 13 | 14 | if (this == NULL) { 15 | fprintf(stderr, "'this.' pointer is null!\n"); 16 | return; 17 | } 18 | if ((fldid = (*env)->GetFieldID(env, 19 | (*env)->GetObjectClass(env, this), "myNumber", "I")) == NULL) { 20 | fprintf(stderr, "GetFieldID failed"); 21 | return; 22 | } 23 | 24 | n = (*env)->GetIntField(env, this, fldid);/* retrieve myNumber */ 25 | printf("\"myNumber\" value is %d\n", n); 26 | 27 | (*env)->SetIntField(env, this, fldid, ++n);/* increment it! */ 28 | nn = (*env)->GetIntField(env, this, fldid); 29 | 30 | printf("\"myNumber\" value now %d\n", nn); /* make sure */ 31 | return; 32 | } 33 | /* END main */ 34 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/jni/HelloJni.java: -------------------------------------------------------------------------------- 1 | package jni; 2 | 3 | // BEGIN main 4 | /** 5 | * A trivial class to show Java Native Interface 1.1 usage from Java. 6 | */ 7 | public class HelloJni { 8 | int myNumber = 42; // used to show argument passing 9 | 10 | // declare native class 11 | public native void displayHelloJni(); 12 | 13 | // Application main, call its display method 14 | public static void main(String[] args) { 15 | System.out.println("HelloJni starting; args.length="+ 16 | args.length+"..."); 17 | for (int i=0; i 14 | 15 | String jsonInput = // <2> 16 | "{\"id\":0,\"firstName\":\"Robin\",\"lastName\":\"Wilson\"}"; 17 | Person q = mapper.readValue(jsonInput, Person.class); 18 | System.out.println("Read and parsed Person from JSON: " + q); 19 | 20 | Person p = new Person("Roger", "Rabbit"); // <3> 21 | System.out.print("Person object " + p +" as JSON = "); 22 | mapper.writeValue(System.out, p); 23 | } 24 | } 25 | // END main 26 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/json/SoftwareParseJackson.java: -------------------------------------------------------------------------------- 1 | package json; 2 | 3 | import java.io.InputStream; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | // BEGIN main 8 | public class SoftwareParseJackson { 9 | final static String FILE_NAME = "/json/softwareinfo.json"; 10 | 11 | public static void main(String[] args) throws Exception { 12 | ObjectMapper mapper = new ObjectMapper(); // <1> 13 | 14 | InputStream jsonInput = 15 | SoftwareParseJackson.class.getResourceAsStream(FILE_NAME); 16 | if (jsonInput == null) { 17 | throw new NullPointerException("can't find" + FILE_NAME); 18 | } 19 | SoftwareInfo sware = mapper.readValue(jsonInput, SoftwareInfo.class); 20 | System.out.println(sware); 21 | } 22 | 23 | } 24 | // END main 25 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/json/SoftwareParseOrgJson.java: -------------------------------------------------------------------------------- 1 | package json; 2 | 3 | import java.io.InputStream; 4 | 5 | import org.json.JSONArray; 6 | import org.json.JSONObject; 7 | import org.json.JSONTokener; 8 | 9 | // BEGIN main 10 | public class SoftwareParseOrgJson { 11 | final static String FILE_NAME = "/json/softwareinfo.json"; 12 | 13 | public static void main(String[] args) throws Exception { 14 | 15 | InputStream jsonInput = 16 | SoftwareParseOrgJson.class.getResourceAsStream(FILE_NAME); 17 | if (jsonInput == null) { 18 | throw new NullPointerException("can't find" + FILE_NAME); 19 | } 20 | JSONObject obj = new JSONObject(new JSONTokener(jsonInput)); // <1> 21 | System.out.println("Software Name: " + obj.getString("name")); // <2> 22 | System.out.println("Version: " + obj.getString("version")); 23 | System.out.println("Description: " + obj.getString("description")); 24 | System.out.println("Class: " + obj.getString("className")); 25 | JSONArray contribs = obj.getJSONArray("contributors"); // <3> 26 | for (int i = 0; i < contribs.length(); i++) { // <4> 27 | System.out.println("Contributor Name: " + contribs.get(i)); 28 | } 29 | } 30 | 31 | } 32 | // END main 33 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/json/WriteOrgJson.java: -------------------------------------------------------------------------------- 1 | package json; 2 | 3 | import org.json.JSONObject; 4 | 5 | // BEGIN main 6 | public class WriteOrgJson { 7 | public static void main(String[] args) { 8 | JSONObject jsonObject = new JSONObject(); 9 | jsonObject.put("Name", "robinParse"). // <1> 10 | put("Version", "1.2.3"). 11 | put("Class", "RobinParse"); 12 | String printable = jsonObject.toString(); // <2> 13 | System.out.println(printable); 14 | } 15 | } 16 | // END main 17 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/lang/AbstractStatic.java: -------------------------------------------------------------------------------- 1 | package lang; 2 | 3 | /** 4 | * Can you call a static method of an abstract class? 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public abstract class AbstractStatic { 8 | 9 | public static void main(String[] argv) { 10 | // BEGIN main 11 | System.out.println("Hello. The answer is yes."); 12 | // The following is redundant, since we got in here! 13 | AbstractStatic.foo(); 14 | // END main 15 | } 16 | 17 | public static void foo() { 18 | System.out.println("Hello from foo. The answer is still yes."); 19 | } 20 | 21 | /* And if you think about it, of course non-abstract static 22 | * methods of an abstract class can be called. Isn't this 23 | * how most "factory methods" work? 24 | */ 25 | } 26 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/lang/AnnotationOverrideDemo.java: -------------------------------------------------------------------------------- 1 | package lang; 2 | 3 | // BEGIN main 4 | /** 5 | * AnnotationOverrideDemo - Simple demonstation of Metadata being used to 6 | * verify that a method does in fact override (not overload) a method 7 | * from the parent class. This class provides the method. 8 | */ 9 | abstract class Top { 10 | public abstract void myMethod(Object o); 11 | } 12 | 13 | /** Simple demonstation of Metadata being used to verify 14 | * that a method does in fact override (not overload) a method 15 | * from the parent class. This class is supposed to do the overriding, 16 | * but deliberately introduces an error to show how the modern compiler 17 | * behaves 18 | */ 19 | class Bottom { 20 | 21 | @Override 22 | public void myMethod(String s) { // EXPECT COMPILE ERROR 23 | // Do something here... 24 | } 25 | } 26 | // END main 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/lang/ChangeArrayLength.java: -------------------------------------------------------------------------------- 1 | package lang; 2 | 3 | /** 4 | * Can you change the .length of an array? 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class ChangeArrayLength { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | int[] a = new int[4]; 11 | System.out.println(a.length); 12 | a.length = 5; // EXPECT COMPILE ERROR 13 | // END main 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/lang/HexNeg.java: -------------------------------------------------------------------------------- 1 | package lang; 2 | 3 | /** 4 | * Are all hex integers negative? 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class HexNeg { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | long data[] = { 0, 0x01, 0xff, 0x100, 0xffff, 0xffffff, 11 | 0x7fffffff, 0xffffffff }; 12 | for (int i=0; i 0 ? args[0] : "Hello"; 20 | String output = new MixinsDemo().process(input); 21 | System.out.println(output); 22 | } 23 | 24 | private String process(String s) { 25 | return filter(convolve(s)); // methods mixed in! 26 | } 27 | } 28 | // END main 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/lang/Shifting.java: -------------------------------------------------------------------------------- 1 | package lang; 2 | 3 | /** 4 | * Show some effects of shifting on ints and longs 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class Shifting { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | System.out.println(" 2<<4 = " + (2<<4)); 11 | System.out.println(" 2<<8 = " + (2<<8)); 12 | System.out.println("2<<16 = " + (2<<16)); 13 | System.out.println("2<<24 = " + (2<<24)); 14 | System.out.println("2<<31 = " + (2<<31)); 15 | System.out.println("2<<32 = " + (2<<32)); 16 | 17 | // Now try those last two as longs 18 | System.out.println("2<<31 = " + ((long)2<<31)); 19 | System.out.println("2<<32 = " + ((long)2<<32)); 20 | // END main 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Log14Demo.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import java.util.logging.Logger; 4 | 5 | // BEGIN main 6 | public class Log14Demo { 7 | public static void main(String[] args) { 8 | 9 | Logger myLogger = Logger.getLogger("com.darwinsys"); 10 | 11 | Object o = new Object(); 12 | myLogger.info("I created an object: " + o); 13 | } 14 | } 15 | // END main 16 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Log14Demo2.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import java.util.logging.Level; 4 | import java.util.logging.Logger; 5 | 6 | // BEGIN main 7 | public class Log14Demo2 { 8 | public static void main(String[] args) { 9 | 10 | System.setProperty("java.util.logging.config.file", 11 | "logging/logging.properties"); 12 | 13 | Logger logger = Logger.getLogger("com.darwinsys"); 14 | 15 | try { 16 | Object o = new Object(); 17 | logger.info("I created an object: " + o); 18 | if (o != null) { // bogus, just to show logging 19 | throw new IllegalArgumentException("Just testing"); 20 | } 21 | } catch (Exception t) { 22 | // All-in-one call: 23 | logger.log(Level.SEVERE, "Caught Exception", t); 24 | // Alternate: Long form, more control. 25 | // LogRecord msg = new LogRecord(Level.SEVERE, "Caught exception"); 26 | // msg.setThrown(t); 27 | // logger.log(msg); 28 | } 29 | } 30 | } 31 | // END main 32 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Log4JDemo.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | // BEGIN main 6 | public class Log4JDemo { 7 | public static void main(String[] args) { 8 | 9 | Logger myLogger = Logger.getLogger("com.darwinsys"); 10 | 11 | // PropertyConfigurator.configure("log4j.properties"); 12 | 13 | Object o = new Object(); 14 | myLogger.info("I created an object: " + o); 15 | 16 | } 17 | } 18 | // END main 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Log4JDemo2.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | // BEGIN main 6 | public class Log4JDemo2 { 7 | public static void main(String[] args) { 8 | 9 | Logger theLogger = Logger.getLogger("com.darwinsys"); 10 | 11 | try { 12 | Object o = new Object(); 13 | theLogger.info("I created an object: " + o); 14 | if (o != null) { // bogus, just to show logging 15 | throw new IllegalArgumentException("Just testing"); 16 | } 17 | } catch (Exception ex) { 18 | theLogger.error("Caught Exception: " + ex, ex); 19 | } 20 | } 21 | } 22 | // END main 23 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/NetLogSimple.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import java.io.IOException; 4 | 5 | /* A simple example of using the NetLog program. 6 | * Unrealistic in that it's standalone; this API is 7 | * intended for use inside another program, possibly 8 | * a servlet or EJB. 9 | */ 10 | // BEGIN main 11 | public class NetLogSimple { 12 | 13 | public static void main(String[] args) throws IOException { 14 | 15 | System.out.println("NetLogSimple: Starting..."); 16 | 17 | // Get the connection to the NetLog 18 | NetLog nl = new NetLog(); 19 | 20 | // Show sending a String 21 | nl.log("Hello Java"); 22 | 23 | // Show sending Objects 24 | nl.log(new java.util.Date()); 25 | nl.log(nl); 26 | 27 | // Show sending null and "" (normally an accident...) 28 | nl.log(null); 29 | nl.log(""); 30 | 31 | // All done, close the log 32 | nl.close(); 33 | 34 | System.out.println("NetLogSimple: Done..."); 35 | } 36 | } 37 | // END main 38 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Slf4jDemo.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | // BEGIN main 7 | public class Slf4jDemo { 8 | 9 | final static Logger theLogger = LoggerFactory.getLogger(Slf4jDemo.class); 10 | 11 | public static void main(String[] args) { 12 | 13 | Object o = new Object(); 14 | theLogger.info("I created an object: " + o); 15 | 16 | } 17 | } 18 | // END main 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/logging/Slf4jDemo2.java: -------------------------------------------------------------------------------- 1 | package logging; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import domain.Person; 7 | 8 | // BEGIN main 9 | public class Slf4jDemo2 { 10 | 11 | final static Logger theLogger = LoggerFactory.getLogger(Slf4jDemo2.class); 12 | 13 | public static void main(String[] args) { 14 | 15 | try { 16 | Person p = new Person(); 17 | // populate person's fields here... 18 | theLogger.info("I created an object {}", p); 19 | 20 | if (p != null) { // bogus, just to show logging 21 | throw new IllegalArgumentException("Just testing"); 22 | } 23 | } catch (Exception ex) { 24 | theLogger.error("Caught Exception: " + ex, ex); 25 | } 26 | } 27 | } 28 | // END main 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/netweb/URIDemo.java: -------------------------------------------------------------------------------- 1 | package netweb; 2 | 3 | import java.net.URI; 4 | import java.net.URL; 5 | import java.net.URISyntaxException; 6 | import java.net.MalformedURLException; 7 | 8 | // BEGIN main 9 | public class URIDemo { 10 | public static void main(String[] args) 11 | throws URISyntaxException, MalformedURLException { 12 | 13 | URI u = new URI("http://www.darwinsys.com/java/../openbsd/../index.jsp"); 14 | System.out.println("Raw: " + u); 15 | URI normalized = u.normalize(); 16 | System.out.println("Normalized: " + normalized); 17 | final URI BASE = new URI("http://www.darwinsys.com"); 18 | System.out.println("Relativized to " + BASE + ": " + BASE.relativize(u)); 19 | 20 | // A URL is a type of URI 21 | URL url = new URL(normalized.toString()); 22 | System.out.println("URL: " + url); 23 | 24 | // Junk 25 | URI uri = new URI("bean:WonderBean"); 26 | System.out.println(uri); 27 | } 28 | } 29 | // END main 30 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/network/ConnectSimple.java: -------------------------------------------------------------------------------- 1 | package network; 2 | 3 | // BEGIN main 4 | import java.net.Socket; 5 | 6 | /* Client with NO error handling */ 7 | public class ConnectSimple { 8 | 9 | public static void main(String[] argv) throws Exception { 10 | 11 | try (Socket sock = new Socket("localhost", 8080)) { 12 | 13 | /* If we get here, we can read and write on the socket "sock" */ 14 | System.out.println(" *** Connected OK ***"); 15 | 16 | /* Do some I/O here... */ 17 | 18 | } 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/network/DaytimeObjectServer.java: -------------------------------------------------------------------------------- 1 | package network; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | import java.util.*; 6 | 7 | /** 8 | * DaytimeObjectServer - server for the non-standard Time (object) service. 9 | * @author Ian F. Darwin 10 | */ 11 | // BEGIN main 12 | public class DaytimeObjectServer { 13 | /** The TCP port for the object time service. */ 14 | public static final short TIME_PORT = 1951; 15 | 16 | public static void main(String[] argv) { 17 | ServerSocket sock; 18 | Socket clientSock; 19 | try { 20 | sock = new ServerSocket(TIME_PORT); 21 | while ((clientSock = sock.accept()) != null) { 22 | System.out.println("Accept from " + 23 | clientSock.getInetAddress()); 24 | ObjectOutputStream os = new ObjectOutputStream( 25 | clientSock.getOutputStream()); 26 | 27 | // Construct and write the Object 28 | os.writeObject(new Date()); 29 | 30 | os.close(); 31 | } 32 | 33 | } catch (IOException e) { 34 | System.err.println(e); 35 | } 36 | } 37 | } 38 | // END main 39 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/network/DaytimeText.java: -------------------------------------------------------------------------------- 1 | package network; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | 6 | /** 7 | * DaytimeText - connect to the standard Daytime (ascii) service. 8 | * @author Ian F. Darwin 9 | */ 10 | // BEGIN main 11 | public class DaytimeText { 12 | public static final short TIME_PORT = 13; 13 | 14 | public static void main(String[] argv) { 15 | String hostName; 16 | if (argv.length == 0) 17 | hostName = "localhost"; 18 | else 19 | hostName = argv[0]; 20 | 21 | try { 22 | Socket sock = new Socket(hostName, TIME_PORT); 23 | BufferedReader is = new BufferedReader(new 24 | InputStreamReader(sock.getInputStream())); 25 | String remoteTime = is.readLine(); 26 | System.out.println("Time on " + hostName + " is " + remoteTime); 27 | } catch (IOException e) { 28 | System.err.println(e); 29 | } 30 | } 31 | } 32 | // END main 33 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/network/Listen.java: -------------------------------------------------------------------------------- 1 | package network; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | 6 | /** 7 | * Listen -- make a ServerSocket and wait for connections. 8 | * @author Ian F. Darwin 9 | */ 10 | // BEGIN main 11 | public class Listen { 12 | /** The TCP port for the service. */ 13 | public static final short PORT = 9999; 14 | 15 | public static void main(String[] argv) throws IOException { 16 | ServerSocket sock; 17 | Socket clientSock; 18 | try { 19 | sock = new ServerSocket(PORT); 20 | while ((clientSock = sock.accept()) != null) { 21 | 22 | // Process it. 23 | process(clientSock); 24 | } 25 | 26 | } catch (IOException e) { 27 | System.err.println(e); 28 | } 29 | } 30 | 31 | /** This would do something with one client. */ 32 | static void process(Socket s) throws IOException { 33 | System.out.println("Accept from client " + s.getInetAddress()); 34 | // The conversation would be here. 35 | s.close(); 36 | } 37 | } 38 | // END main 39 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/BigNums.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | import java.math.*; 4 | 5 | /** 6 | * Demonstrate large numbers. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | public class BigNums { 10 | public static void main(String[] argv) { 11 | // BEGIN main 12 | System.out.println("Here's Long.MAX_VALUE: " + Long.MAX_VALUE); 13 | BigInteger bInt = new BigInteger("3419229223372036854775807"); 14 | System.out.println("Here's a bigger number: " + bInt); 15 | System.out.println("Here it is as a double: " + bInt.doubleValue()); 16 | // END main 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/BinaryDigits.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | /** 4 | * Template for standalone, line-mode main program. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class BinaryDigits { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | String bin = "101010"; 11 | System.out.println(bin + " as an integer is " + Integer.valueOf(bin, 2)); 12 | int i = 42; 13 | System.out.println(i + " as binary digits (bits) is " + 14 | Integer.toBinaryString(i)); 15 | // END main 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/CastNeeded.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | /** Casting Demo. */ 4 | public class CastNeeded { 5 | // BEGIN main 6 | public static void main(String[] argv) { 7 | int i; 8 | double j = 2.75; 9 | i = j; // EXPECT COMPILE ERROR 10 | i = (int)j; // with cast; i gets 2 11 | System.out.println("i =" + i); 12 | byte b; 13 | b = i; // EXPECT COMPILE ERROR 14 | b = (byte)i; // with cast, i gets 2 15 | System.out.println("b =" + b); 16 | } 17 | // END main 18 | } 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/ComplexDemo.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | /** A class to show uses of my Complex Number class; 4 | * see ComplexTest for actual unit tests. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | // BEGIN main 8 | public class ComplexDemo { 9 | /** The program */ 10 | public static void main(String[] args) { 11 | Complex c = new Complex(3, 5); 12 | Complex d = new Complex(2, -2); 13 | System.out.println(c); 14 | System.out.println(c + ".getReal() = " + c.getReal()); 15 | System.out.println(c + " + " + d + " = " + c.add(d)); 16 | System.out.println(c + " + " + d + " = " + Complex.add(c, d)); 17 | System.out.println(c + " * " + d + " = " + c.multiply(d)); 18 | System.out.println(Complex.divide(c, d)); 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/FormatPlurals.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | /** 4 | * Format a plural correctly, by hand. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | // BEGIN main 8 | public class FormatPlurals { 9 | public static void main(String[] argv) { 10 | report(0); 11 | report(1); 12 | report(2); 13 | } 14 | 15 | /** report -- using conditional operator */ 16 | public static void report(int n) { 17 | System.out.println("We used " + n + " item" + (n==1?"":"s")); 18 | } 19 | } 20 | // END main 21 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/FormatPluralsChoice.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | import java.text.*; 4 | 5 | /** 6 | * Format a plural correctly, using a ChoiceFormat. 7 | * @author Ian F. Darwin, http://www.darwinsys.com/ 8 | */ 9 | // BEGIN main 10 | public class FormatPluralsChoice extends FormatPlurals { 11 | 12 | // ChoiceFormat to just give pluralized word 13 | static double[] limits = { 0, 1, 2 }; 14 | static String[] formats = { "reviews", "review", "reviews"}; 15 | static ChoiceFormat pluralizedFormat = new ChoiceFormat(limits, formats); 16 | 17 | // ChoiceFormat to give English text version, quantified 18 | static ChoiceFormat quantizedFormat = new ChoiceFormat( 19 | "0#no reviews|1#one review|1" + nf.format(0)); 11 | System.out.println("Failed to object to zero"); 12 | } catch (NumberFormatException ex) { 13 | System.out.println("Correctly rejected zero"); 14 | } 15 | System.out.println("42->" + nf.format(42)); 16 | System.out.println("678->" + nf.format(678)); 17 | System.out.println("1999->" + nf.format(1999)); 18 | System.out.println("2000->" + nf.format(2000)); // Y2K anyone? 19 | System.out.println("2001->" + nf.format(2001)); // Y2K anyone? 20 | System.out.println("3999->" + nf.format(3999)); 21 | System.out.println("4000->" + nf.format(4000)); // expect Exception 22 | // END main 23 | // parsing not implemented. 24 | System.out.println("XIV->" + nf.parseObject("XIV", null)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/RomanNumberSimple.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class RomanNumberSimple { 6 | public static void main(String[] args) { 7 | // BEGIN main 8 | RomanNumberFormat nf = new RomanNumberFormat(); 9 | int year = LocalDate.now().getYear(); 10 | System.out.println(year + " -> " + nf.format(year)); 11 | // END main 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/RomanYear.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | import java.util.*; 4 | 5 | /** Print the current year in Roman Numerals */ 6 | // BEGIN main 7 | public class RomanYear { 8 | 9 | public static void main(String[] argv) { 10 | 11 | RomanNumberFormat rf = new RomanNumberFormat(); 12 | Calendar cal = Calendar.getInstance(); 13 | int year = cal.get(Calendar.YEAR); 14 | 15 | // If no arguments, just print the year. 16 | if (argv.length == 0) { 17 | System.out.println(rf.format(year)); 18 | return; 19 | } 20 | 21 | // Else a micro-formatter: replace "-" arg with year, else print. 22 | for (int i=0; i " + round(d)); 25 | System.out.println("Math way:" + d + "-> " + Math.round(d)); 26 | } 27 | } 28 | } 29 | // END main 30 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/StringToDouble.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | 4 | public class StringToDouble { 5 | 6 | // BEGIN main 7 | public static void main(String[] argv) { 8 | String aNumber = argv[0]; // not argv[1] 9 | double result; 10 | try { 11 | result = Double.parseDouble(aNumber); 12 | System.out.println("Number is " + result); 13 | } catch(NumberFormatException exc) { 14 | System.out.println("Invalid number " + aNumber); 15 | return; 16 | } 17 | } 18 | // END main 19 | } 20 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/TempConverter.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | 4 | /* Print a table of Fahrenheit and Celsius temperatures 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | // BEGIN main 8 | public class TempConverter { 9 | 10 | public static void main(String[] args) { 11 | TempConverter t = new TempConverter(); 12 | t.start(); 13 | t.data(); 14 | t.end(); 15 | } 16 | 17 | protected void start() { 18 | } 19 | 20 | protected void data() { 21 | for (int i=-40; i<=120; i+=10) { 22 | float c = (i-32)*(5f/9); 23 | print(i, c); 24 | } 25 | } 26 | 27 | protected void print(float f, float c) { 28 | System.out.println(f + " " + c); 29 | } 30 | 31 | protected void end() { 32 | } 33 | } 34 | // END main 35 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/TempConverter2.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | 4 | /* Print a table of fahrenheit and celsius temperatures, a bit more neatly. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | // BEGIN main 8 | public class TempConverter2 extends TempConverter { 9 | 10 | public static void main(String[] args) { 11 | TempConverter t = new TempConverter2(); 12 | t.start(); 13 | t.data(); 14 | t.end(); 15 | } 16 | 17 | protected void print(float f, float c) { 18 | System.out.printf("%6.2f %6.2f%n", f, c); 19 | } 20 | 21 | protected void start() { 22 | System.out.println("Fahr Centigrade"); 23 | } 24 | 25 | protected void end() { 26 | System.out.println("-------------------"); 27 | } 28 | } 29 | // END main 30 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/numbers/Trig.java: -------------------------------------------------------------------------------- 1 | package numbers; 2 | 3 | /** 4 | * Demonstrate a few of the Math functions for Trigonometry. 5 | * @author Ian F. Darwin, http://www.darwinsys.com/ 6 | */ 7 | public class Trig { 8 | public static void main(String[] argv) { 9 | // BEGIN main 10 | System.out.println("Java's PI is " + Math.PI); 11 | System.out.println("Java's e is " + Math.E); 12 | System.out.println("The cosine of 1.1418 is " + Math.cos(1.1418)); 13 | // END main 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/AllClasses.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | import java.awt.Component; 4 | import java.awt.event.*; 5 | import javax.swing.*; 6 | 7 | // BEGIN main 8 | public class AllClasses { 9 | public class Data { // <1> 10 | int x; 11 | int y; 12 | } 13 | public void getResults() { 14 | JButton b = new JButton("Press me"); 15 | b.addActionListener(new ActionListener() { // <2> 16 | public void actionPerformed(ActionEvent evt) { 17 | Data loc = new Data(); 18 | loc.x = ((Component)evt.getSource()).getX(); 19 | loc.x = ((Component)evt.getSource()).getY(); 20 | System.out.println("Thanks for pressing me"); 21 | } 22 | }); 23 | } 24 | } 25 | 26 | /** Class contained in same file as AllClasses, but can be used 27 | * (with a warning) in other contexts. 28 | */ 29 | class AnotherClass { // <3> 30 | // methods and fields here... 31 | AnotherClass() { 32 | // Inner class from above cannot be used here, of course 33 | // Data d = new Data(); // EXPECT COMPILE ERROR 34 | } 35 | } 36 | // END main 37 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/ChessMoveException.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | // BEGIN main 4 | /** A ChessMoveException is thrown when the user makes an illegal move. */ 5 | public class ChessMoveException extends Exception { 6 | 7 | private static final long serialVersionUID = 802911736988179079L; 8 | 9 | public ChessMoveException () { 10 | super(); 11 | } 12 | 13 | public ChessMoveException (String msg) { 14 | super(msg); 15 | } 16 | 17 | public ChessMoveException(String msg, Exception cause) { 18 | super(msg, cause); 19 | } 20 | } 21 | // END main 22 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/Clone1.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /** Demonstration of cloning. */ 4 | // BEGIN main 5 | public class Clone1 implements Cloneable { 6 | 7 | /** Clone this object. Call super.clone() to do the work */ 8 | public Object clone() { 9 | try { 10 | return super.clone(); 11 | } catch (CloneNotSupportedException ex) { 12 | System.out.println("Now that's a surprise!!"); 13 | throw new InternalError(ex.toString()); 14 | } 15 | } 16 | 17 | int x; 18 | transient int y; // will be cloned, but not serialized 19 | 20 | /** Display the current object as a string */ 21 | public String toString() { 22 | return "Clone1[" + x + "," + y + "]"; 23 | } 24 | } 25 | // END main 26 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/PrintHashCodes.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /** Display hashCodes from some objects */ 4 | // BEGIN main 5 | public class PrintHashCodes { 6 | 7 | /** Some objects to hashCode() on */ 8 | protected static Object[] data = { 9 | new PrintHashCodes(), 10 | new java.awt.Color(0x44, 0x88, 0xcc), 11 | new SomeClass() 12 | }; 13 | 14 | public static void main(String[] args) { 15 | System.out.println("About to hashCode " + data.length + " objects."); 16 | for (int i=0; i " + 18 | data[i].hashCode()); 19 | } 20 | System.out.println("All done."); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/SerializableUser.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /** Demo of a data class that will be used as a JavaBean or as a data 4 | * class in a Servlet container; marking it as Serializable allows 5 | * it to be saved ("serialized") to disk or over a network connection. 6 | */ 7 | // BEGIN main 8 | public class SerializableUser implements java.io.Serializable { 9 | public String name; 10 | public String address; 11 | public String country; 12 | public String phoneNum; 13 | 14 | // other fields, and methods, here... 15 | static final long serialVersionUID = -7978489268769667877L; 16 | } 17 | // END main 18 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/Singleton.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /** An example of a Singleton implementation in Java, using static initialization. 4 | * The Singleton design pattern is described in GOF; the idea is to ensure 5 | * that only one instance of the class will exist in a given application. 6 | * @author Ian F. Darwin, http://www.darwinsys.com/ 7 | */ 8 | // BEGIN main 9 | public class Singleton { 10 | 11 | private static Singleton instance; 12 | 13 | /** A private Constructor prevents any other class from instantiating. */ 14 | private Singleton() { 15 | // nothing to do this time 16 | } 17 | 18 | /** The Static initializer constructs the instance at class loading time; 19 | * this is to simulate a more involved construction process (it it 20 | * were really simple, you'd just use an initializer) 21 | */ 22 | static { 23 | instance = new Singleton(); 24 | } 25 | 26 | /** Static 'instance' method */ 27 | public static Singleton getInstance() { 28 | return instance; 29 | } 30 | 31 | // other methods protected by singleton-ness would be here... 32 | 33 | /** A simple demo method */ 34 | public String demoMethod() { 35 | return "demo"; 36 | } 37 | } 38 | // END main 39 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/StringParse.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | import com.darwinsys.lang.MutableInteger; 4 | 5 | /** Show use of MutableInteger to "pass back" a value in addition 6 | * to a function's return value. 7 | */ 8 | // BEGIN main 9 | public class StringParse { 10 | /** This is the function that has a return value of true but 11 | * also "passes back" the offset into the String where a 12 | * value was found. Contrived example! 13 | */ 14 | public static boolean parse(String in, char lookFor, 15 | MutableInteger whereFound) { 16 | 17 | int i = in.indexOf(lookFor); 18 | if (i == -1) 19 | return false; // not found 20 | whereFound.setValue(i); // say where found 21 | return true; // say that it was found 22 | } 23 | 24 | public static void main(String[] args) { 25 | MutableInteger mi = new MutableInteger(); 26 | String text = "Hello, World"; 27 | char c = 'W'; 28 | if (parse(text, c, mi)) { 29 | System.out.println("Character " + c + " found at offset " + 30 | mi + " in " + text); 31 | } else { 32 | System.out.println("Not found"); 33 | } 34 | } 35 | } 36 | // END main 37 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/ToStringWith.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /* Demonstrate toString() with an override */ 4 | // BEGIN main 5 | public class ToStringWith { 6 | int x, y; 7 | 8 | /** Simple constructor */ 9 | public ToStringWith(int anX, int aY) { 10 | x = anX; y = aY; 11 | } 12 | 13 | @Override 14 | public String toString() { 15 | return "ToStringWith[" + x + "," + y + "]"; 16 | } 17 | 18 | /** Main just creates and prints an object */ 19 | public static void main(String[] args) { 20 | System.out.println(new ToStringWith(42, 86)); 21 | } 22 | } 23 | // END main 24 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/ToStringWithout.java: -------------------------------------------------------------------------------- 1 | package oo; 2 | 3 | /* Demonstrate toString() without an override */ 4 | // BEGIN main 5 | public class ToStringWithout { 6 | int x, y; 7 | 8 | /** Simple constructor */ 9 | public ToStringWithout(int anX, int aY) { 10 | x = anX; y = aY; 11 | } 12 | 13 | /** Main just creates and prints an object */ 14 | public static void main(String[] args) { 15 | System.out.println(new ToStringWithout(42, 86)); 16 | } 17 | } 18 | // END main 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/oo/shapes/ShapeDriver.java: -------------------------------------------------------------------------------- 1 | package oo.shapes; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | // BEGIN main 7 | /** Part of a main program using Shape objects */ 8 | public class ShapeDriver { 9 | 10 | Collection allShapes; // created in a Constructor, not shown 11 | 12 | /** Iterate over all the Shapes, getting their areas; 13 | * this cannot use the Java 8 Collection.forEach because the 14 | * variable total would have to be final, which would defeat the purpose :-) 15 | */ 16 | public double totalAreas() { 17 | double total = 0.0; 18 | for (Shape s : allShapes) { 19 | total += s.computeArea(); 20 | } 21 | return total; 22 | } 23 | // END main 24 | ShapeDriver() { 25 | allShapes = new ArrayList<>(); 26 | allShapes.add(new Circle()); 27 | allShapes.add(new Rectangle()); 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(new ShapeDriver().totalAreas()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/otherlang/ExecDemoFiles.java: -------------------------------------------------------------------------------- 1 | package otherlang; 2 | 3 | import com.darwinsys.lang.ExecAndPrint; 4 | 5 | /** 6 | * Create, list and remove some files 7 | */ 8 | public class ExecDemoFiles { 9 | public static void main(String av[]) throws Exception { 10 | 11 | // BEGIN main 12 | // Get and save the Runtime object. 13 | Runtime rt = Runtime.getRuntime(); 14 | 15 | // Create three temporary files (the slow way!) 16 | rt.exec("mktemp file1"); 17 | rt.exec("mktemp file2"); 18 | rt.exec("mktemp file3"); 19 | 20 | // Run the "ls" (directory lister) program 21 | // with its output sent into a file 22 | String[] args = { "ls", "-l", "file1", "file2", "file3" }; 23 | ExecAndPrint.run(args); 24 | 25 | rt.exec("rm file1 file2 file3"); 26 | // END main 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/otherlang/ExecDemoSimple.java: -------------------------------------------------------------------------------- 1 | package otherlang; 2 | 3 | /** 4 | * ExecDemo shows how to execute an external program and read its output. 5 | */ 6 | // BEGIN main 7 | public class ExecDemoSimple { 8 | public static void main(String av[]) throws Exception { 9 | 10 | // Run the "notepad" program or a similar editor 11 | Process p = Runtime.getRuntime().exec("kwrite"); 12 | 13 | p.waitFor(); 14 | } 15 | } 16 | // END main 17 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/otherlang/ProcessBuilderDemo.java: -------------------------------------------------------------------------------- 1 | package otherlang; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * ProcessBuilderDemo shows how to execute an external 9 | * program (in this case the MS-Windows notepad program). 10 | */ 11 | public class ProcessBuilderDemo { 12 | 13 | public static void main(String argv[]) throws Exception { 14 | // BEGIN main 15 | List command = new ArrayList<>(); // <1> 16 | command.add("notepad"); 17 | command.add("foo.txt"); 18 | ProcessBuilder builder = new ProcessBuilder(command);// <2> 19 | builder.environment().put("PATH", 20 | "/windows;/windows/system32;/winnt"); // <3> 21 | final Process godot = builder.directory( 22 | new File(System.getProperty("user.home"))). // <4> 23 | start(); 24 | System.err.println("Waiting for Godot"); // <5> 25 | godot.waitFor(); // <6> 26 | // END main 27 | 28 | System.out.println("Program terminated!"); 29 | return; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/otherlang/RenjinScripting.java: -------------------------------------------------------------------------------- 1 | package otherlang; 2 | 3 | import javax.script.ScriptEngine; 4 | import javax.script.ScriptEngineManager; 5 | import javax.script.ScriptException; 6 | 7 | public class RenjinScripting { 8 | // BEGIN main 9 | /** 10 | * Demonstrate interacting with the "R" implementation called "Renjin" 11 | */ 12 | public static void main(String[] args) throws ScriptException { 13 | ScriptEngineManager manager = new ScriptEngineManager(); 14 | ScriptEngine engine = manager.getEngineByName("Renjin"); 15 | engine.put("a", 42); 16 | Object ret = engine.eval("b <- 2; a*b"); 17 | System.out.println(ret); 18 | } 19 | // END main 20 | } 21 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/otherlang/ScriptEnginesDemo.java: -------------------------------------------------------------------------------- 1 | package otherlang; 2 | 3 | import javax.script.ScriptEngine; 4 | import javax.script.ScriptEngineManager; 5 | import javax.script.ScriptException; 6 | 7 | // BEGIN main 8 | public class ScriptEnginesDemo { 9 | 10 | public static void main(String[] args) throws ScriptException { 11 | ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); 12 | 13 | // Print list of supported languages 14 | scriptEngineManager.getEngineFactories().forEach(factory -> 15 | System.out.println(factory.getLanguageName())); 16 | 17 | // Run a script in the JavaScript language 18 | String lang = "ECMAScript"; 19 | ScriptEngine engine = 20 | scriptEngineManager.getEngineByName(lang); 21 | if (engine == null) { 22 | System.err.println("Could not find engine"); 23 | return; 24 | } 25 | engine.eval("print(\"Hello from " + lang + "\");"); 26 | } 27 | } 28 | // END main 29 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/patterns/Makefile: -------------------------------------------------------------------------------- 1 | all: links 2 | links: 3 | ln -s $$HOME/lt318/CodeWorkshop.txt . 4 | ln -s ../com.darwinsys/src/com/darwinsys/util/ArrayIterator.java . 5 | ln -s ../com.darwinsys/src/com/darwinsys/swingui/I18N.java . 6 | ln -s ../com.darwinsys/src/com/darwinsys/swingui/IntlAction.java . 7 | ln -s ../JabberPointExtracts . 8 | ln -s ../gui/ObservDemo.java . 9 | ln -s ../oo/Singleton.java . 10 | ln -s ../oo/SingletonDemo.java . 11 | ln -s ../oo/SingletonTest.java . 12 | ln -s ../gui/UndoDemo.java . 13 | ln -s ../../src/jabagator . 14 | ln -s ../com.darwinsys.regexp . 15 | ln -s $$HOME/webs/javawebframeworks/servletdispatcher . 16 | 17 | jar: 18 | cd ..; jar cvf $$HOME/webs/students/lt318/codeworkshop.zip patterns 19 | -------------------------------------------------------------------------------- /javacooksrc/javacooksrc/main/java/performance/Array.java: -------------------------------------------------------------------------------- 1 | package performance; 2 | 3 | import com.darwinsys.lang.MutableInteger; 4 | 5 | /** Time a bunch of creates and gets through an Array */ 6 | // BEGIN main 7 | public class Array { 8 | public static final int MAX = 250000; 9 | public static void main(String[] args) { 10 | System.out.println(new Array().run()); 11 | } 12 | public int run() { 13 | MutableInteger list[] = new MutableInteger[MAX]; 14 | for (int i=0; i list = new ArrayList<>(); 16 | for (int i=0; i" + o.toString() + "

"); 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 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 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 | --------------------------------------------------------------------------------