Java Coffee Break Newsletter Volume 3, Issue 6 http://www.javacoffeebreak.com/ ISSN 1442-3790 ================================================================= In this issue * Editor's Note * Featured Java Websites * Book Review - Java Pitfalls * Book Review - Professional Java XML Programming * Interview : Mark Grand, author of Patterns in Java * Q&A : How can I poll a remote server, to see if it is still available? * Q&A : How can I create an event handling mechanism in Java? * Q&A : How can I read the status code of a HTTP request? ================================================================= Editor's Note Readers may have noticed a new format for the newsletter. We are now featuring reviews of useful Java websites, based on feedback from subscribers. We're also featuring a series of interviews with leading Java authors. Space limitations prevent us from including every interview, however. You can see an archive of previous interviews from the Java Coffee Break website at http://www.javacoffeebreak.com/articles/authorprofiles/ Reminder : JavaOne, the world's largest conference, starts June 6, 2000. Perhaps I'll see you there! ================================================================= Featured Java Websites Here are a selection of websites that may be of interest to readers. THE JINI WORKBENCH - TOOLS FOR LEARNING JINI The Jini Workbench, by Gamelan, features a collection of great articles relating to this exciting new topic. Jini allows hardware and software services to talk to each other over a network, using Java remote method invocation as the glue that connects services and clients together. You'll learn about the Jini technology, how it works, and how to produce Jini software. There's also a great no-nonsense article that cuts through the hype, and shows you where Jini's strengths and weaknesses lie. http://www.gamelan.com/workbench/jini/ JAVA, IT'S NOT JUST FOR BROWSERS ANYMORE You may be surprised to know, but Java isn't just for browsers. Java is making the move into the wired world, into palmtop and handheld devices like the Palm V, thanks to the Java 2 Platform Micro Edition. Bill Joy, a regular contributor to JavaWorld, has written a FAQ about writing Java code for the micro edition, where you'll learn all sorts of useful tidbits such as where to download tools, and how to create and test software for palmtop devices. http://www.billday.com/Work/devicefaq.txt PERFECT PROGRAMMING WITH PRIMATES Wired's Webmonkey series of tutorials is well known to webmasters and developers for its no-nonsense approach to teaching Web concepts. There's some really great web development material and tutorials available on programming topics, with a special section devoted exclusively to Java. Webmonkey tutorials cover a wide range of topics, from client side applets to server-side applications in Java. Well worth a look, and a good starting point for those new to Java. http://hotwired.lycos.com/webmonkey/programming/java/index.html TO BODLY GO WHERE NO-ONE HAS GONE BEFORE.. NO, NOT THAT ENTERPRISE! Have you ever dreamed of creating the next Amazon.com or Yahoo portal? Sure you might be able to do it in Java with some applets and a customized server, but would it scale? Java 2 Enterprise Edition is the solution - a new SDK for enterprise programming. It's scalable, contains all the technologies you could ever want (like CORBA, JSP, servlets, EJB and more jargon than you'll ever need), and is now available for Solaris and Windows NT. There are plenty of whitepapers, articles, and tutorials on this Sun-run site. It's just what you need for your next e-commerce portal site! http://java.sun.com/j2ee/ JAVA SERVLET FAQ Written by Thomas Moore, this FAQ features common questions and answers about servlet programming. Servlet programming is a form of server side Java (just as applets are mini applications, servlets are mini web applications that replace CGI scripts). You'll learn about servlet tools, web servers that support servlets, how they work and how they compare to CGI. This is a work in progress, but well worth a look. http://wwwusers.imaginet.fr/~lse/JSS/textes/servfaq.htm ================================================================= Book Review - Java Pitfalls : Time-Saving Solutions and Workarounds to Improve Programs Author : Michael C. Daconta, et al Publisher : John Wiley & Sons ISBN : 0471361747 Experience: Beginner-Expert I've reviewed quite a few Java books about improving the attributes of Java software. Some concentrate on improving the design, others the robustness of software or the performance. While they usually start out promising, by the end of the book you're left with a good understanding of theory but little practical skills. Java Pitfalls : Time-Saving Solutions and Workarounds to Improve Programs, breaks free of that mould, by providing a wealth of techniques and code that has real practical application. The title does not do it justice, however. Not only does the book show you how to improve programs, the advice contained within also saves you time, frustration, and effort. After reading through even a few pages of tips within the book, you understand that the advice isn't dry theory, but practical advice gained from real-life problems that Java developers face. Michael Daconta, and his co-authors, offer warnings gained from the trenches of software development using Java. The book is divided neatly into eight sections, covering different aspects of Java programming. A wide range of areas are covered, from the obligatory Java language syntax, to more fun topics like graphical user interfaces (using AWT and Swing), the utilities package and collections, input and output (I/O), and even improving Java performance. The one significant area lacking from the book, in my opinion, is a section on network programming pitfalls, and perhaps other advanced topics like databases. These areas are fraught with pitfalls for the unwary. However, for readers not involved with such areas, this is a moot point, and it leaves more room for other tips. There are a total of 50 individual pieces of advice, and each is packed full of detailed code examples. Whether you're a Java newbie, or an experienced Java developer looking to improve your coding and reduce the frustration and time of software development, Java Pitfalls is an ideal addition to your book collection. With the usefulness of this advice, you'll probably find it taking a place on your desk though, rather than the bookshelf. -- David Reilly For more information about this title, or to order it, visit http://www.davidreilly.com/goto.cgi?isbn=0471361747 ================================================================= Book Review - Professional Java XML Programming with Servlets and JSP Author : Alexander Nakhimovsky and Tom Myers Publisher : Wrox Press Inc. ISBN : 1861002858 Experience: Intermediate - Expert Professional Java Xml Programming, by Alexander Nakhimovsky and Tom Myers, tackles the ambitious goal of teaching the readers two of the hottest programming technologies in recent years: the eXstensible Markup Language (XML) and Java. Along the way, you'll pick up a little JavaMail, and a fair deal of Java Servlet and Java Server Pages (JSP) experience as well. All of these technologies, aside from being very important for the construction of websites, are highly prized by employers and useful skills to learn. Why Java and XML you may ask yourselves? To answer that, consider the roles that they are suited for. Java is ideal for server-side programming and web development, and XML has gone beyond a simple way to exchange information between databases to being a language for structured information. Together, and with Professional Java XML Programming as your guide, you'll learn how to created multiple-tiered web applications, a focus that XML and Java are ideally suited to. By combining Java, databases using the Java DataBase Connectivity (JDBC) API, and XML, you can create powerful server-side systems and websites. The first few chapters give you a basic overview of three tiered applications, JDBC access, and the basics of Java servlets. From there, the book progresses to XML. It presents a good introduction to XML theory, without tying you down too much with trivial details. XML gurus might prefer a more weighty tome, but it's great for normal Java programmers, and covers all the important topics like grammar, entities, document type definitions (DTDs), and types of parsers : SAX vs Document Object Model (DOM). Before teaching you XML parsing, the authors offer an introduction on parsing techniques and formal languages. This chapter is mandatory for readers, and though some may find this a waste of their time, others will find it a useful grounding in parsing theory.  There's also coverage of advanced applications of XML, using eXstensible Style-sheet Language for Translations (XSLT), and other Java technologies like Java Server Pages, JavaBeans, and JavaMail. Professional Java XML Programming may not be the best or simplest XML theory book, but does an admirable job of merging both XML and Java together. These are valuable skills for Java programmers, and the book includes plenty of examples that demonstrate XML concepts. Don't get me wrong - XML isn't a walk in the park, but with a little perseverance, Professional Java XML Programming will teach you how to blend XML and Java server-side technologies to create powerful web applications, and will find a treasured place on your bookshelf. -- Michael Reilly For more information about this title, or to order it, visit http://www.davidreilly.com/goto.cgi?isbn=1861002858 ================================================================= Interview : Michael Daconta, author of Java Pitfalls Michael Daconta, is President of Synergy Solutions, Inc., where he conducts training seminars and develops advanced systems with Java, JavaScript and XML. He's also the author of the recently published Java Pitfalls : Time-Saving Solutions and Workarounds to Improve Programs. Whether you're new to programming, or a seasoned Java veteran, Java Pitfalls is full of useful techniques and coding solutions. In this exclusive interview, we talk with Michael about the Java language, its limitations and advantages, and "real-life" practical coding. Q: What do you see as being the biggest change affecting the Java community in the last year? A: Which Java community? Do you mean the Java 1.1.8 community or the Java 2 community? And there's the rub. The biggest change over the last year has been Java's slow slide from its idealistic and hallowed perch. This slide has been greased from every angle with ample skepticism. When Java began, many developers (including myself) held our breath and whispered, "Is this the ONE?" "Is this the Silver Bullet?" But now, all of our ego boundaries have snapped back into place and we are really seeing the technology for the first time - warts and all. This is where our book, Java Pitfalls, comes into play. It is a straight look at 50 programming obstacles that we guide you around. The most treacherous of those obstacles is the pitfall -- here is the definition from the book's introduction: A pitfall is code that compiles fine but when executed produces unintended and sometimes disastrous results. Pitfalls are the bane of beginning programmers who rely so heavily on the blessing of compilation. So, now to the good news... putting the browser and Microsoft fiasco aside, for those developers lucky enough to be able to move on to the Java 2 platform, they have witnessed an impressive maturing of the platform. The platform has also continued its astounding growth and spread into every computing niche. The question is no longer whether you will develop in Java anymore but whether you will develop in anything else. This is especially true for the average corporate developer. Lastly, there is another rising star that is both threatening and invigorating the Java community: XML. I see the ascendancy of XML as the greatest potential threat to Java. XML is as ambivalent to programming languages as Java is to operating systems. So, this game is really only in the second quarter. Q: What do you see as the main advantages of Java, compared to other languages like C++? A: A good part of my career has revolved around teaching C and C++ Pointer intricacies and pitfalls to programmers so I feel qualified to affirm that Java is a significant improvement over C++. Yet instead of going through the laundry list let's cut right to the chase: Java is a more productive language. You can produce more code, of higher quality and with less effort than if the project used C++. Now let's move beyond C++ and discuss the key advantages of the Java platform. By far, the key advantage that provides the time-saving is the large number of continually expanding class libraries. There is over 2000 classes provided by Sun alone to provide various services to your program. That is not even mentioning open source and commercial Java Beans. So, this enormous Java support system offers a tremendous amount of leverage to the average programmer. Some other advantages are the well-known C syntax, the simple and consistent heap-based storage for everything except local primitives, garbage collection, and the smart-card to mainframe scalability. However, I cannot leave this topic without scratching off a former oft-touted benefit: simplicity. I'm sorry but once you cross the line into phantom references, anonymous classes, deadlock scenarios and soon templates, you are hard-pressed to argue the simplicity of the language. Our book covers many of these issues, for example Item 11: Reclaiming References using SoftReference objects. Q: Michael, your book takes a very practical approach to Java programming. There's several other books out there on the market aimed at teaching time-saving solutions based on programming experience, but they generally focus on design patterns and aren't always Java specific. How is your book different? A: Right from the outset, I wanted a book free from debates on design techniques. While those books have their place, many design patterns take time (sometimes a long time) before they can be understood and put to use. I wanted a book to help the practicing programmer right from page one without spending hours, weeks or months attempting to map pure theory to everyday, messy reality. As an interesting aside, the book's previous title was "Effective Java: 50 specific ways to avoid pitfalls and improve your programs." Unfortunately, at the last minute we had to change the title, due to the litigious nature of a very large publisher whose name will not be mentioned. What does this have to do with a practical approach? All the co-authors were very sensitive to the book being compared to Scott Myer's Effective C++ so we were very careful to put out a high quality product. It is actually amusing that we had to change the title at the last minute because Java Pitfalls was the original title I proposed! So, in the end, even though we had to delay the book a few weeks, the programmers won out over the marketing suits. The other thing that is immediately obvious about Java Pitfalls is that all of this is coming from direct experience. We have the bruises to show for it. This material is not watered down or surmised or distilled from researching other people's work. For awhile I did a Java column called "Java from the Trenches" and that is also a good metaphor for the type of hard-won, battlefield lessons the book provides. Editor's Note : Michael discusses a wide range of topics in his interview, covering the Java API, practical pitfalls, all the way to the future direction of Java. The entire text of the interview is available from http://www.javacoffeebreak.com/articles/authorprofiles/daconta_michael/ ================================================================= Interview : Mark Grand, author of Patterns in Java Mark Grand is the author of a series of books titled Patterns in Java, which teach the basics of design patterns and provide examples of their implementation in the Java programming language. He is also currently one of the architects of an open-source application framework for e-commerce called Hatchware. In this exclusive interview, we talk with Mark about design patterns. Q: You've written extensively on the topic of design patterns in Java. For the benefit of people unsure exactly what one is, how would you define a design pattern? A: A very simple definition for a pattern is a reusable solution to a recurring problem. A design pattern is a pattern that solves a software design problem. Some other pattern writers take exception to such a simple definition of pattern, because it does not address important form and style issues. For people who may be interested in reading patterns, I think this definition is good enough. Q: Design patterns are very popular with developers using languages like C++. There's a range of books aimed at a C++ audience, but a relatively small amount of titles for Java. How does Java stack up to C++ in general, and specifically with regard to design patterns. A: There has been much material written that compares Java and C++. Most design patterns are language neutral, although the specific solution that they propose may be slanted towards a particular language. The differences that you see are typical of the language's different object models. Where you may see multiple inheritance or abstract classes in an example oriented towards C++, you will usually see interfaces in a Java oriented solution. Another difference that you find is in applying some patterns. C++ gives you more than one way of doing many things, where Java give you just one. For example, C++ allows an object to contain a value or a pointer to the value. This means having to make more decisions in how to apply a pattern. Q: Do you find the lack of certain C++ features like multiple inheritance and generic types in Java a hindrance when designing software, or do they make object designs simpler? A: As you may guess from my previous response, I generally find that my designs are simpler when designing for Java. Multiple inheritence is something that I rarely use. Generic types simplify coding, but do not have much impact on design. I understand that JavaSoft has looked at some proposal for generic types, but has not acted on the proposals yet. Q: You've written two volumes on Java design patterns, and I understand a third volume is underway. What can readers expect to gain from these books? Does an understanding of design patterns make life easier on programmers, make software more robust and reliable, or are there productivity bonuses? Experience gives programmers a variety of wisdom. As programmers gain experience, they recognize the similarity of new problems to problems they have solved before. With even more experience, they recognize that the solutions for similar problems follow recurring patterns. With the knowledge of these patterns, experienced programmers recognize the situations where patterns apply and immediately use the solution without having to stop, analyze the problem, and then pose possible strategies. When a programmer discovers a pattern, it's just an insight. In most cases, to go from an unverbalized insight to a well thought-out idea that the programmer can clearly articulate is surprisingly difficult. It's also an extremely valuable step. When we understand a pattern well enough to put it into words, we are able to intelligently combine it with other patterns. More importantly, once put into words, a pattern can be used in discussions among programmers who know the pattern. That allows programmers to more effectively collaborate and combine their wisdom. It can also help to avoid the situation where programmers argue over different solutions to a problem, only to find out later that they were really thinking of the same solution but expressing it in different ways. Putting a pattern into words has an additional benefit for less experienced programmers who have not yet discovered the pattern. Once a pattern has been put into words, more experienced programmers can teach it to programmers who aren't familiar with the pattern. The Patterns in Java books I have written provide experienced programmers with a common vocabulary to discuss patterns. It also allows programmers who have not yet discovered a pattern to learn about the pattern. Each of the volumes of Patterns in Java have a different focus. The first volume is about micro-architecture design patterns. The patterns in there tend to focus on issues such as how to create objects, organize behavior, manage complexity and multi-threading. The pattern topics that the second volume covers include patters for GUI design, coding and testing. I wrote that with the idea that people can use information about patterns outside of the design realm. The third volume of Patterns in Java will focus on design patterns for enterprise and distributed applications. There seems to be a lot of interest in it. I am behind schedule, but I am still hoping that it will be out before the end of the year. The current working outline is at http://www.mindspring.com/~mgrand/pattern_synopses3.htm  I still need people to review some of my chapters, if any of your readers would be interested. Q: Design patterns are often expressed using Unified Modeling Language notation. What's your opinion of UML diagrams? While many universities now teach UML diagrams, do you think that they're accessible to the average programmer? A: There are really two issues in your questions. UML is just a notation for expressing software designs. I like it because its basic feature set is focused on the essentials. There are some specialized design details, such as thread synchronization semantics, that UML does not provide a good way to express. Because UML is just a notation for expressing software designs rather than a full blown design methodology, it is possible to learn UML without knowing much about software design. The reason that I have chosen to use UML in my books is that it is currently the most popular notation for software designs. Q: Thanks for your perspective on design patterns, Mark - they certainly appear to be an important topic for developers. Readers interested in learning more about design patterns will find the Patterns in Java series available in your local bookstore, or online from Amazon.com.  * Patterns in Java Volume 1, http://www.davidreilly.com/goto.cgi?isbn=0471258393 * Patterns in Java Volume 2, http://www.davidreilly.com/goto.cgi?isbn=0471258415 ================================================================= Q&A: How can I poll a remote server, to see if it is still available? I'd like to check to see if the server has crashed, and if so, record the time. If your application is a TCP server, the easiest way to do this is for a client to connect to it, using the java.net.Socket class. When the Socket is connected, if the server is down an IOException will be thrown, indicating that the server is not accepting connections. However, this may not be a sufficient test for mission critical applications. What if the server has stalled, and will accept connections but not respond to them? In this situation, you'll need to write a valid request to the server (using the appropriate network protocol, such as HTTP or FTP). It doesn't matter what type of request is made, or what data is really returned (unless it is an error message). The only purpose of the request is to see if the server will response, and is still available for use. ================================================================= Q&A: How can I create an event handling mechanism in Java? I'm used to ActiveX controls, which fire asynchronous events (i.e. when a control is finished a task, it notifies another component of that event). The most common mechanism for this is the callback, where one class calls the method of another to notify it of an action or event. The class to be notified defines methods that will respond to specific events, such as when a mouse is clicked, dragged, or released. The AWT makes heavy use of this, with Listener interfaces. A class implements the event handling methods of a listener, and can then be registered with a component that generates these types of events. Classes that are event sources provide methods which register a listener, and at a later time when the event is generated, will invoke listener methods. The Abstract Windowing Toolkit (AWT) and Swing APIs would be a good place to start, to see if this suits your needs. ================================================================= Q&A : How can I read the status code of a HTTP request? If you use the URL.openStream() method, there's no way to determine whether a request was successful or not. The only alternative is to use the URL.openConnection() method, which returns a URLConnection instance. The URLConnection is an abstract class, meaning that it provides a template of methods which other classes will implement. Even though the URL.openConnection() method returns a URLConnection instance, it is actually returning a concrete implementation of that class. When a request is made for a resource using the Hypertext Transfer Protocol, the implementation of URLConnection that is returned is a java.net.HttpURLConnection. This class defines additional methods, one of which allow you to access the response status code. To find out the status of a request, you need to cast the URLConnection to a HttpURLConnection, and invoke the int HttpUrlConnection.getResponseCode() method. URL url = new URL ( some_url ); URLConnection connection = url.openConnection(); connection.connect(); // Cast to a HttpURLConnection if ( connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; int code = httpConnection.getResponseCode(); // do something with code ..... } else { System.err.println ("error - not a http request!"); } ================================================================= The Java Coffee Break Newsletter is only sent out to email subscribers who have requested it, and to readers of the comp.lang.java.programmer and comp.lang.java.help newsgroups. If you'd like to receive our newsletter, and get the latest Java news, tips and articles from our site, then get your FREE subscription & back issues from http://www.javacoffeebreak.com/newsletter/ If you are an email subscriber and no longer wish to receive the JCB Newsletter, please unsubscribe by emailing javacoffeebreak-unsubscribe@listbot.com