Book Giveaway: Teach Yourself Java in 24 Hours

My newest book, Sams Teach Yourself Java in 24 Hours, Fifth Edition, recently hit bookstores. The book is a for-absolute-beginners guide to programming Java, and this section from chapter one's Q&A section shows how much license I get from the publisher to have fun with the series:

Q. Do you only answer questions about Java?

A. Not at all. Ask me anything.

Q. Okay, why is Prince mad at the Foo Fighters?

A. Prince is unhappy that the Foo Fighters performed a cover of his song "Darling Nikki" and released it as a B-side single in Australia. He told Entertainment Weekly they should write their own tunes and wouldn't let the band release it in the United States. This became a pretty meaningless distinction as the song became a radio hit around the globe and was played regularly during their concerts.

When Prince performed at Super Bowl XLI a few years later, he covered the Foo Fighters' "Best of You," an artistic decision that surprised the Foo Fighters as much as everybody else.

"It was pretty amazing to have a guy like Prince covering one of our songs," Foo Fighters drummer Taylor Hawkins told MTV, "and actually doing it better than we did."

Although playing someone else's music is an odd way to exercise a grudge, this was a better option for the 5-foot-2 Prince than challenging the band to a fight.

Every chapter ends with one reader question that has bupkiss to do with Java. I used to be the Fort Worth Star-Telegram's Ed Brice, an answer man who fielded random questions, so old habits die hard.

Sams Teach Yourself Java in 24 Hours, Fifth EditionMy book has been fully updated for Java 6 and has new chapters on JAX-WS and game programming. I have 20 copies I'd like to give to people who want to learn Java, and there's still time for me to mail them before Christmas.

If you know someone who wants to learn Java, or you can make a convincing case for why Santa owes you this book after the year 2009 you just endured, please leave a comment here on Workbench or in a Twitter post to rcade. Make sure I have some means of contacting you, so I can get the address of the person getting the book.

I'm planning on mailing these out on Wednesday morning in the pre-Christmas scrum at the post office. I will mail the books directly to the people receiving them and can put your name and address as the sender and wrap them if necessary. No one needs to know I was involved.

Please note that I'm expecting the people who get this free book to teach themselves Java in a single contiguous 24-hour period. For too long, Sams has coddled readers who devote one hour a day to a subject and learn it at their leisure.

Kickin' It Old School with Microsoft Word 97

Windows 98 Microsoft Channel BarI began a new book this week on Java programming for beginners. I haven't been doing much computer book writing for a couple years, so I no longer had an installed copy of Microsoft Word 97, the version of the software my publisher uses to draft manuscripts. Word 2007 can save files in 97 format, but it doesn't support the publisher's custom styles, so I decided to install Word 97 on Vista.

Huge mistake.

Word 97 appeared to install properly, but when I installed some other Microsoft software afterward, it removed files that Word 97 requires to run. Now the program reports a registry error every time it runs and Vista won't uninstall it or install a new copy.

After considering other options, I installed a trial version of VMware Workstation, $188 software that creates virtual computers in which you can run other operating systems. You run the simulated computer in its own window after deciding how much disk space and memory to allocate to it, and it acts like it's an entire computer. After setting up one of these virtual systems, you can clone it, suspend it and run it remotely over the Internet.

Using VMware, I created a new virtual Windows XP system where I can run Word 97 and the other software required to write my book. As far as I know, this Pinocchio virtual computer thinks it's a real PC.

Because Microsoft is run by sadists, I had to install Windows 98 before I could install a Windows XP upgrade. It was weird to step back in time and see the Microsoft channel bar, an early stab at web syndication that predated RSS. During installation, Windows 98 also touts its support for USENET newsgroups. Kids today don't know how good they got it. In my day, if we wanted to see celebrities naked, we had to know how to UUdecode.

If anyone has any experience with VMware, I'd like to hear how well it works. My biggest concern is whether anything I do inside the virtual computer can adversely impact the real Vista system it runs on. I want virtual computers that I can destroy with impunity by running buggy beta software and other dodgy programs that don't get along with each other. I end up doing that a lot in the course of writing a book.

Following Web Page Redirects with Java

CNET moved a bunch of its blogs to a different domain this weekend, including Beyond Binary, Coop's Corner, Geek Gestalt, One More Thing, Outside the Lines and The Social. I mention this because the change hosed Meme13, which treated all six as if they were newly discovered sites.

One of my ground rules for developing Meme13 is that I won't hand-edit the site to make it smarter. I need the application to recognize when existing sites in its database have moved.

Meme13 monitors sites using a Java application I wrote that downloads web pages with the Apache HTTPClient 3.0 class library. Web servers indicate that a page has moved by sending an HTTP redirect response of either "301 Moved Permanently," which indicates a permanent move, or "302 Found," which is intended for temporary changes. I wrote a Java method that can find the current location of a web page, even if it has been redirected one or more times:

public String checkFeedUrl(String feedUrl) {
    String response = feedUrl;
    HttpClient client = new HttpClient();
    HttpMethod method = new HeadMethod(feedUrl);
    method.setFollowRedirects(false);
    try {
        // request feed
        int statusCode = client.executeMethod(method);
        if ((statusCode == 301) | (statusCode == 302)) {
            // feed has moved
            Header location = method.getResponseHeader("Location");
            if (!location.getValue().equals("")) {
                // recursively check URL until it's not redirected any more
                response = checkFeedUrl(location.getValue());
            }
        } else {
            response = feedUrl;
        }
    } catch (IOException ioe) {
        response = feedUrl;
    }
    return response;
}

The HeadMethod class requests a web page's headers instead of requesting the entire page, consuming far less bandwidth as it checks for redirects. My Java method looks for both kinds of redirects, because web publishers have a bad habit of using "302 Found" when they've moved a page permanently.

Exporting a Manila Site Using OPML

The RSS Advisory Board site now includes all of the articles, weblog entries, and comments from the group's old Manila site, dating back to the group's founding in 2004.

I never got a copy of the old site's root file from Harvard, so I collected the content using an obscure but cool feature of Manila: All site content is saved in the discussion board as individual messages, each of which can be downloaded as an OPML file. For example, open this weblog entry from Craig Burton's Manila blog in OPML format.

I wrote a Java application that used Apache HttpClient to download the files and XOM to process the OPML.

OPML sucks, but I got thousands of weblog files into a MySQL database so I can't complain. Manila stores message text in the text attribute of outline elements, some of which may be nested. Weblog entries are formatted using the most insane thing I've ever seen in an XML dialect:

<outline text="&lt;newsItem&gt;"/>
<outline text="&lt;title&gt;Hackers selling IDs for $14, Symantec says&lt;/title&gt;"/>
<outline text="&lt;url&gt;&lt;/url&gt;"/>
<outline text="&lt;/newsItem&gt;"/>

You need to be an XML dork to appreciate this, but it's XML elements stored as escaped markup inside XML attributes.

Sun Sees the Light on Java Applets

I'm working on the next edition of Sams Teach Yourself Java in 21 Days, an 800-page monster that will cover Java 6 so thoroughly that all the other Java authors will stop writing their books and pursue retraining for a non-technical profession. (Computer book authors should talk smack like rappers. One of these days I'm going to start an East Coast/West Coast feud with Seattle's Glenn "PC-Diddy" Fleischman.)

Ten years ago, the original edition of Java in 21 Days made a big deal out of Java applets, web-based programs that were the world's first exposure to the language. The first Java boom was sparked by then-Netscape executive Marc Andreesen's decision to add a Java interpreter to the Navigator browser.

As the years passed, the world realized that an applet is a terrible thing to do to a web browser. Even today, with five iterations of Java to improve performance, you can tell when a page contains an applet: Your hard drive starts spinning furiously as the Java Plug-in loads and there's an interminably long pause before the page displays. Fortunately for authors like me, Java found a better niche in servlets, mobile devices and enterprise applications.

The next edition of my book relegates browser applets to an appendix. By the time Java 7 rolls around, I may dump the subject entirely.

Need more proof that applets are dead? If you go to Sun's Java.Com homepage, you may see a cool demo of a Fast and the Furious: Tokyo cell phone game that's written in Java.

The demo loads quickly and incorporates fast-moving graphics synchronized perfectly with sound. When I saw it, I was so impressed that I dug into the page's source code, wanting to find out how Sun accomplished such great effects using an applet.

The answer: They wrote it in Flash.

NoWomenJustMen: The Roster at Most Tech Conferences

I heard from one of the organizers of the Spring Experience, an enterprise Java conference organized by NoFluffJustStuff that I criticized for assembling a 38-speaker roster than doesn't include a single female.

He never responded to my request to run his e-mail in full, but this quote sums it up:

We sought out a qualified speaker who was female. She is on your list. Unfortunately, she is in very high demand (as one would probably expect!) and in the end could not commit due to a scheduling conflict. Even with the conflict, we went the extra mile to accomodate her because she brought something different and refreshing to our target audience. Unfortunately, she just couldn't commit.

We're actively pushing bright girls out of professions like programming by reinforcing the idea that technological fields only appeal to one gender. The brain drain this causes has to be incredibly detrimental to this country's competitiveness, discouraging 51 percent of the population from pursuing these fields even as we rely more heavily on them in our economy.

Settlement Reached with Dave Winer

I've reached an agreement with Dave Winer regarding the Share Your OPML web application. I destroyed his original code and user data along with everything that was built from it and gave up my claim to a one-third stake in feeds.scripting.com. He gave up the claim that he's owed $5,000.

I originally hoped one of us would buy the other out and launch the application, but we found a much stronger basis for agreement in a mutual desire to stop working together as quickly as possible.

If Share Your OPML was a Java project I would've been heartsick to destroy it, but I coded the application in PHP. I've never written anything in PHP I didn't want to completely rewrite six months later.

Some people think I'm an asshat for taking this public, and I won't argue with that, but I don't have the resources to fight an intellectual property lawsuit against a millionaire. Winer knows this -- he's been a guest in my home -- and it's clear his attorney was acting from the same assumption throughout the settlement negotiation.

I decided the best way to avoid court was to show Winer what it would be like to sue a blogger.

I figured the publicity would be a stronger motivator to resolve the matter than anything I could say through an attorney. He's one of the most galvanizing figures in the technology industry. If he ever sues someone, the publication of the case's motions and depositions will put a blog in the Technorati Top 100. Since publishing the letter from Winer's attorney, my traffic's through the roof, I'm getting fan mail and I received three programming job offers.

I'm extremely grateful for the public support and the offers to contribute to a legal defense fund on my behalf, which I was hoping might lead to a Free Kevin-style sticker-based political movement.

Some programmers have said that I was foolish to write the app on the basis of a verbal agreement, and I'll concede that wholeheartedly. I won't even do the laundry now without something in writing.

I'm not going to close the book on this debacle with any Panglossian happy talk about how it all worked out for the best. This was a completely unnecessary sphincter-fusing legal dispute that could have been settled amicably months ago without benefit of counsel.

But I'm glad to stop pursuing an application so closely associated with OPML, because I don't share Winer's enthusiasm for the format.

I used to feel differently, but now that I've worked with it extensively, OPML's an underspecified, one-size-fits-all kludge that doesn't serve a purpose beyond the exchange of simple data. There's little need for an XML dialect to represent outlines. Any XML format is a hierachy of parent-child relationships that could be editable as an outline with a single addition: a collapsed attribute that's either true or false.

Developers who build on OPML will encounter a lot of odd data because the format has been extended in a non-standard way. An outline item's type attribute has a value that indicates the other attributes which might be present. No one knows how many different attributes are in use today, so if you tell users that your software "supports OPML," you're telling them you support arbitrary XML data that can't be checked against a document type definition.

OPML's also the only XML dialect I'm aware of that stuffs all character data inside attributes. Now that OPML's being turned into a weblog publishing format, outline items will have ginormous attribute values holding escaped HTML markup like this:

<outline text="&lt;img src="http://images.scripting.com/archiveScriptingCom/2006/03/16/chockfull.jpg" width="53" height="73" border="0" align="right" hspace="15" vspace="5" alt="A picture named chockfull.jpg"&gt;&lt;a href="http://scobleizer.wordpress.com/2006/03/16/the-new-a-list/"&gt;Scoble laments&lt;/a&gt; all the flamers in the thread on &lt;b style="color:black;background-color:#ffff66"&gt;Rogers Cadenhead's&lt;/b&gt; site, but isn't it obvious that the &lt;i&gt;purpose&lt;/i&gt; of his post was to get a flamewar going? What non-flamer is going to post in the middle of a festival like that one? I'm not as worried about it as Scoble is, because I've seen better flamewars and I know how they turn out. In a few days he's still going to have to try to resolve the matter with me, and the flamers will have gone on to some other trumped-up controversy. The days when you could fool any number of real people with a charade like this are long past. And people who use pseudonyms to call public figures schoolyard names are not really very serious or threatening. &lt;a href="http://allied.blogspot.com/2006/03/lynch-mob-security.html"&gt;Jeneane Sessum&lt;/a&gt; is right in saying it's extreme to call this a lynch mob. It's just a bunch of &lt;a href="http://www.cadenhead.org/workbench/news/2881/letter-dave-winers-attorney#46458"&gt;anonymous comments&lt;/a&gt; on a snarky blog post. Big deal. Not.&nbsp;&lt;a href="http://www.scripting.com/2006/03/16.html#When:11:21:10PM"&gt;" created="Tue, 16 March 2006 11:21:10 GMT"/>

I'd be amazed if XML parsers can handle attribute values of any length, but that's what's being done today with OPML.

Now that an agreement has been reached, Winer doesn't have to share Share Your OPML and I can flee in terror before any border skirmishes lead to another XML specification war.

Maybe this is the best of all possible worlds.

Update: Winer appears to have launched a new PHP-based implementation of Share Your OPML with Dan MacTough.

Handling Numeric XML Entities in a Weblog Move

I'm exporting a Radio UserLand weblog to Movable Type for a client, turning Radio's XML archive of weblog entries into a Movable Type import file. I wrote a Java application that employs the XOM XML library to read Radio's weblog data.

Some numeric character entities in Radio's XML data threw me for a loop: &#226; (’), &#192; (¿), &#142; (é), &#135; (á) and &#151; (ó). They were transformed -- either by XOM or the Xerces XML parser that it uses -- into garbage characters that display incorrectly in Movable Type.

After fumbling around, I found a solution: Read a weblog entry's XML data as a text file, replace the numeric XML entities with the equivalent numeric HTML entities and parse the resulting file with XOM:

// replace bad character entities with good ones
public void prepareFile(String source) throws IOException {
  File sourceFile = new File(directory + source);
  BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
  File destination = new File("input.xml");
  BufferedWriter writer = new BufferedWriter(new FileWriter(destination));
  String text = "";
  do {
    text = text.replaceAll("&#226;", "&amp;#8217;"); // curly single quote mark
    text = text.replaceAll("&#192;", "&amp;#191;"); // upside down question mark
    text = text.replaceAll("&#142;", "&amp;#233;"); // lowercase accented e
    text = text.replaceAll("&#135;", "&amp;#225;"); // lowercase accented a
    text = text.replaceAll("&#151;", "&amp;#243;"); // lowercase accented o
    if (!text.equals("")) {
      writer.write(text, 0, text.length());
      writer.newLine();
    }
    text = reader.readLine();
  } while (text != null);
  reader.close();
  writer.close();
}

This is a clumsy solution that relies on escaped markup to produce the HTML entities, but I can't find a better one without editing the client's Radio data by hand. I'm trying to avoid that, because I want to use this application to move other weblogs.

Radio UserLand saves an XML backup of all weblog posts and categories in the software's backups\weblog\Archive subdirectory. If you're using Radio, enable the Archiving in XML preferences to take advantage of this feature, which makes it easier to export the data to another weblog publishing program.

New Book: Programming with Java in 24 Hours

I just launched the web site for Sams Teach Yourself Programming with Java in 24 Hours, my 21st computer book since I began writing them in 1996. I'm not sure how this happened. I went to college to learn interpretive dance.

This is the fourth edition of the book, updated to cover Java 2 version 5. I wrote the first in a 17-day haze in 1997, covering Java 1.1 and its class library, which is less than one-tenth the size of the Java 2 class library today.

Over the years, the book has grown to 558 pages and been heavily reworked several times to reflect changing priorities among Java's several million programmers. Back in 1987, Java was touted as the ideal language for designing interactive web content like games and animation, so the book covered applets extensively. Today, Macromedia Flash has all but killed applets in the browser -- the last major web site using Java applets, ESPN, switched to Flash within the last year for its fantasy sports and live game stats. Java coders use the language primarily on Internet servers, database programs, web applications and middleware.

The fourth edition devotes new chapters to two subjects that weren't even around eight years ago: XML and XML-RPC. I wanted to get XML-RPC into the book so badly that I suspended the laws of time and space. Each of Sams' 24 Hours books contains 24 one-hour tutorials, which add up to a day under a timekeeping system established by the Babylonians more than 1,000 years ago. I broke that system to make room for Hour 25, "Creating Web Services with XML-RPC."

I cover XML-RPC programming using Apache XML-RPC, an open source Java class library that makes it easy to move data around from program to program over the Internet. I rely on it all the time -- this week, I transferred thousands of database records from a Frontier server to an XML-RPC server on my desktop machine to a PHP/MySQL database on Workbench.

Each chapter ends with two programming exercises solved on the site. The Hour 25 exercises are an XML-RPC client, server and request handler for the XML-RPC interface of Advogato.

Even if you don't buy the book -- a possibility I hate to even contemplate -- those two applications demonstrate how to make and receive XML-RPC requests in Java using Apache XML-RPC.

Displaying XML Data with PHP

I recently finished writing Sams Teach Yourself Programming with Java in 24 Hours, the fourth edition of an introductory book for Java programmers, which comes out in around two weeks.

I've been given wide editorial license with the book, so it contains unusual projects like Lottorobics, a lottery simulation applet that demonstrates why "Win the Lotto" is a terrible retirement plan.

The new edition adds chapters on XML and XML-RPC that use XOM and Apache XML-RPC, two great open source class libraries for Java. Programming projects in these chapters enable user lottery results to be tracked -- the applet sends the data to an XML-RPC server, which stores them in an XML file. In the years I've been offering the applet, users have won the lottery once in 4,877 simulated years of playing at a cost of $5.4 million dollars.

I wanted to display this lottery data on the web using PHP, so I've adapted some code for this purpose. The first release of the code, which I'm offering under the open source GNU Public License, shows how to read simple XML data with PHP.

If you do anything interesting with the code, and you don't mind releasing your work under the GPL, I'd like to add a few more sample programs to this project.

Keeping Computer Books Up-to-Date

Charles Wright in the Sydney Morning Herald:

With the number of blogs increasing at a phenomenal rate, more people than ever will find themselves dealing with the market-leading Movable Type. The Movable Type 3 Bible, from Wiley, gives you a thorough grounding in the complexities of a blogging platform that, on the surface, looks relatively easy to master but repays the effort required to learn about its more powerful features. Increasingly, these books are rendered somewhat out of date with the release of new versions, which this book promises to solve with an update site. Frankly, there's not much there, but there is a link to the author's site.

A truism of computer book writing is that a new software release will be announced the day after your book goes to press on the same subject. I need to write more on Workbench about Movable Type's PHP publishing features in advance of the book's next edition, but otherwise it keeps current with version 3.

I've always thought that computer books should be paired with active web sites, which is why there are more than 5,000 pages on this server supporting my books. I occasionally get a nice email from someone who picks up an eight-year old copy of Teach Yourself Java 1.1 Programming in 24 Hours and is pleasantly surprised to find the support site online.

As I told Wright in email, with the dot-com bust and the abundance of free technical information on the web, the economics of supporting a book after publication have never been uglier.

I should not have been so quick in college to choose journalism and computer science over a career in interpretive dance.

Open Source, Insert Foot

As a Java devotee, I grimace whenever language inventor James Gosling expounds to the press on the subject of open source.

In a story noting the 10th birthday of Java, Gosling said, "We did do it as close to open source as you could and still be a corporation."

Last month, Gosling responded to an Apache proposal to create an open source version of Java with puzzlement:

It's often difficult to get a good picture from the open source community of what they actually object to in what we're doing. In what way could we be more open? ...

Since day zero, 10 years ago, all of our sources have been open and available. We've got several thousand man-years of engineering in [Java], and we hear very strongly that if this thing turned into an open source project -- where just any old person could check in stuff -- they'd all freak. They'd all go screaming into the hills.

I have trouble believing that Gosling could be this mistaken about open source.

Open source projects do not allow random people to check in code. There's a submission process where proposed modifications are evaluated by people who have the ability to commit or reject a change. All revisions are tracked with code versioning software and can be backed out if necessary.

Gosling knows this -- he runs two open source projects, BlogEd and JNN, that require his permission to check in code.

The open source process works as well or better than proprietary approaches. I observed the early development of Geronimo, the Apache Software Foundation's J2EE application server, and its project committers are meticulous, professional, and extremely dedicated to software development.

Apache's so accomplished that its process has become celebrated as the Apache way. When I need a Java class library, I check Apache Jakarta before Sun. The code's often better, more reflective of real-world needs, and actively developed -- unlike parts of the Java 2 class library that Sun appears to have quietly abandoned.

Java is not remotely open. Under the Sun Community Source License, you can't publish a modified version, Sun decides whether your contributions are compatible, and contributors don't have to share their code.

If releasing open source code is detrimental to a corporation, that's news to IBM, Red Hat, JBoss, SleepyCat Software, and hundreds of other companies, many serving the enterprise customers that Gosling believes are fleeing in terror.

Gosling, who appears to have qualified some of his criticisms on his blog, ought to find some unloved part of the Java 2 class library like JavaSound and shepherd its adoption as an Apache project. He'd realize that open source can be an asset to Sun, which needs all the help it can get.

Choosing a Programmer's Editor

A reader laments the difficulty of writing programs in a plain-vanilla text editor:

I have a question that I can't seem to frame correctly. It relates to my inability to format nested punctuation (in any language, on any day). I would dearly love to see a quasi-visual editor which replaces the {{ ... }} with nested shading, and bold type used to identify classes, italics for variables, etc. etc.

It clearly calls for a different approach to the text-bound, linear approach to coding. What would such a beast be called?

Most programmers choose their editor with more care than they put into the purchase of a car. I've been lusting after this vi reference coffee mug and I don't even use the program. I feel like H.I. McDunnough in Raising Arizona, driving past convenience stores that aren't even on the way home.

For years, sheer laziness caused me to write my Java classes, Perl scripts, and other software in Windows Notepad. When I did some professional development last year for Best Blinds, a local ecommerce company, I decided it was time to find a decent programmer's text editor for Windows.

I settled on UltraEdit-32, a $40 programming, web page, and hex editor that gets great reviews in places like PC Magazine.

There are some quirks with the software, such as a hidden-character issue that was causing the header() function to fail in PHP scripts, but otherwise I've liked the editor for both programming and web design.

UltraEdit offers some great features for programming (screen shot), including keyword and class highlighting and the identification of matching brackets.

Though I recommend UltraEdit, I'd dump it for an outliner that supported code highlighting. After writing UserTalk scripts in Radio UserLand's outliner, I'm convinced an outliner is the best way to write programs. The ability to expand and collapse blocks of code as you're editing, to see exactly what you need to see, is a huge benefit.

An e-mail from a reader of Sams Teach Yourself Java 2 in 24 Hours:

i really enjoyed reading what you wrote and especially the way you wrote it!! all i want to know now is how i can make a virus because some of my pals are bugging me and i'm really pissed! and like you i feel that i'd rather be georgia vs. mafiaboy !! thanks again and please send me a repley as soon as possible and please please make sure to include a virus making "formula in it". bye