Assistant Professor Department of Information Technology Jadavpur University, Kolkata Java ADVANCED PROGRAMMING Uttam K. Roy
Oxford University Press is a department of the University of Oxford. It furthers the University’s objective of excellence in research, scholarship, and education by publishing worldwide. Oxford is a registered trade mark of Oxford University Press in the UK and in certain other countries. Published in India by Oxford University Press YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India © Oxford University Press 2015 The moral rights of the author/s have been asserted. First published in 2015 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, without the prior permission in writing of Oxford University Press, or as expressly permitted by law, by licence, or under terms agreed with the appropriate reprographics rights organization. Enquiries concerning reproduction outside the scope of the above should be sent to the Rights Department, Oxford University Press, at the address above. You must not circulate this work in any other form and you must impose this same condition on any acquirer. ISBN-13: 978-0-19-945550-8 ISBN-10: 0-19-945550-3 Typeset in Times New Roman by Mukesh Technologies Pvt. Ltd, Puducherry 605005 Printed in India by Magic International (P) Ltd, Greater Noida Third-party website addresses mentioned in this book are provided by Oxford University Press in good faith and for information only. Oxford University Press disclaims any responsibility for the material contained therein.
PreFace The power of Java is unquestionable and is well-known to everyone in the software community. Numerous books are available on core Java. However, the real power of Java primarily lies in Java’s advanced concepts. Although there are many books available on these topics, most of them focus on a specific technology. For example, it is not impossible to find dozens of books on Socket programming, RMI, JNI, Servlets, JSP, and JDBC, but it is almost impossible to find any engineering/science curriculum, which has subjects like these. However, topics such as Network Programming and Advanced Java are very common. In these circumstances, it is not convenient for students having “Advanced Java” as a subject in his/her course to purchase all the necessary books and comprehend all the concepts included therein. This book aims to bring almost all the advanced concepts of Java under a common roof so that experienced programmers can easily find relevant information whenever necessary and can become experts in this field. Needless to say, readers of this book should have good working knowledge of core Java. ABOUT THE BOOK This book covers, in depth and with extensive examples and references, the primary technical issues that every Java expert should understand, such as JNI, Socket programming, RMI, JavaMail, Java XML-RPC, Soap, Security, Servlet, JSP, JDBC, Hibernate, JNDI, JMS, CORBA, and many others. Each chapter provides detailed working examples illustrating the functioning of these technologies and how they can be used to build robust Java-based applications. This book provides real-world examples supported with ample screenshots so that readers can understand and easily apply them to Java-based applications they would develop in the future. Although this book is intended as a textbook for undergraduate- and postgraduate-level courses on Advanced Java, it can also be used as a supplementary textbook for undergraduate/postgraduate courses on network programming, server-side programming, Enterprise Java, and GUI programming. The book is also a useful resource for researchers to learn to write different kinds of distributed applications effectively and efficiently using various Java concepts. In addition, it will provide useful background and reference information for professionals working in the area of Java-based web applications. CONTENT AND STRUCTURE The book is organized into twenty eight chapters, each covering a unique topic in detail. The chapters have been grouped into three parts: • Part I—Inside Java • Part II—Network Programming • Part III—Enterprise Java In Part I (Chapters 1–11), important Java concepts such as Exception Handling, Multi-threading, Garbage Collection, Collection Framework, Generic Programming, Reflection, JNI, AWT and Swing, and Java and XML, among others, have been discussed. Part II (Chapters 12–18) includes networking concepts such as Socket programming, RMI, The JavaMail API, and Java XML-RPC. Part III (Chapters 19–28) covers concepts of Java Enterprise Edition such as Servlet, JSP, JDBC, Hibernate, JNDI, JMS, CORBA, and JSF.
PREFACE vii Chapter 1 gives a quick summary of six important Java tools (jhat, jdb, javap, javadoc, and jcmd) out of many powerful tools that come with JDK to help Java developers in better programming. Other tools have been discussed in the remaining chapters. Chapter 2 covers Java exception handling. It helps programmers to understand what exceptions are and how they are handled. It also gives a brief description of exception classes and their hierarchy. In Chapter 3, we discuss multi-threaded processes in Java. A multi-threaded process has two or more parts which can run concurrently and each part can do a designated task at the same time. Multi- threading enables us to write programs in a way where multiple activities can proceed concurrently in the same program. Chapter 4 first describes the basics of the working of Garbage Collection inside HotSpot. It then gives an overview of the available garbage collectors with their functions and performance metrics. It also demonstrates how to select and configure a collector and set sizes for the memory areas on which the collector operates. Finally, it lists some of the most commonly used options that affect garbage collector behaviour. Chapter 5 explains a powerful unified architecture, known as collection framework, provided by Java. Java provides high-quality implementation of collection interfaces resulting in unquestionable performance and quality of programs. Java not only provides the different implementations of an interface, but also allows us to interchange these implementations seamlessly. In Chapter 6, we talk about Java generics, which was one of the extensions added to Java 1.5. Generics allows us to write parameterized classes, interfaces, and methods where parameters are type names. This also helps us to detect more bugs at compile time and fix them then and there. Chapter 7 throws light on the concept of Java reflection APIs. The reflection API in Java enables us to examine and/or modify the properties, behaviour, or other elements of an object at run-time. An understanding of reflection will help us in comprehending the tools (NetBeans, Eclipse, Spring) that use this API. Chapter 8 covers the Java Native Interface (JNI) which is an API that allows Java code to interoperate with applications and libraries written in other programming languages such as C and C++. It is a two-way interface that allows Java applications to invoke the native method, and native methods to interact with the Java code. Chapter 9 gives us a detailed understanding of Java AWT concepts, background philosophy, and practical concerns with an introduction to Swing which is an extension to AWT. Chapter 10 expounds on the Java APIs for XML (eXtensible Markup Language), which is a key technology for structured data representation and transfer. It is used virtually everywhere, from small- to large-scale legacy applications. Java also promotes portability and is an obvious choice to work with XML documents. Java APIs for XML make it easier to use XML from the Java programming language. It also provides sample applications that you can run. Chapter 11 outlines how applications process some input and generate some output. Java provides a rich set of classes and interfaces as a separate package java.io for such Input and Output (I/O). Java also provides another package java.nio containing Non-blocking I/O (NIO) API, which, in some situations, can give a big performance boost over blocking IO. In this chapter, we have also given an overview of how all these classes are grouped with their purposes. Chapter 12 demonstrates how one can use Java network APIs to write basic network programs easily and quickly. Java has some distinct advantages over other programming languages as far as network applications are concerned. In addition, Java can handle network security issues extremely well. Features such as platform independence and garbage collection allows us to develop efficient and elegant network applications without worrying about system crashes, spread of viruses, or stealing of sensitive data.
viii PREFACE In Chapter 13, we lay emphasis on Java implementation of socket API. Sockets can be used as lower-level tools for IPC in local processes as well as processes running on different computers. Sockets are particularly useful when we want to write client–server applications. In Chapter 14, we explore how Java’s object-oriented version of RPC (known as Remote Method Invocation) can be easily used to develop sophisticated networking applications. This technology elevates network programming to a higher plane. Chapter 15 deals with the primary protocols for delivery and accessing of emails such as Simple Mail Transfer Protocol (SMTP), Post Office Protocol (POP), and Internet Message Access Protocol (IMAP). In Chapter 16, we cover the structure of applets, their execution philosophy, and other applet-specific issues. Applets are Java programs that usually run within web browsers and give more power to the browsers. Chapter 17 outlines XML-RPC, the XML-based Remote Procedure Call (RPC) protocol. In this protocol, eXtensible Markup Language (XML) is used to describe a Remote Procedure Call. It is a very simple and portable way to call remote procedures over HTTP. Chapter 18 illustrates the Simple Object Access Protocol (SOAP), which is an extension to XML-RPC. SOAP can be used in a wide variety of systems ranging from messaging systems to RPC. Chapter 19 brings to the fore almost all the aspects of Java security mechanism from secure language features to the security APIs, tools, and built-in provider services, highlighting key packages and classes. Chapter 20 elucidates the powerful Java server-side technology called Servlets. They usually run inside a Java-enabled web server and extend its capabilities. Since servlets are written in Java and Java is an extremely powerful language, even a simple web server bundled with servlets becomes unquestionably powerful. Chapter 21 describes the Java Server pages which is an extension to Servlets. It is one of the many server- side technologies used to build dynamic web applications that has caught the attention of web developers due to several reasons. In Chapter 22, we discuss an important technique called Java DataBase Connectivity (JDBC), which allows us to access databases through Java programs. It provides Java classes and interfaces to fire SQL and PL/SQL statements, process results (if any), and perform other operations common to databases. Chapter 23 presents Hibernate, an open source Object Relational Mapping (ORM) tool. It allows us to persist Plain Old Java Objects (POJO) to the database. Chapter 24 examines the Java Naming and Directory Service. It allows us to associate (called binding) names with objects and to find (called lookup) those objects later by their names. Chapter 25 reviews another Java technology used to write distributed applications that can communicate in a loosely coupled way. Messaging is often used to coordinate programs in dissimilar systems or written in different programming languages. In Chapter 26, we study some other J2EE technologies, especially, JavaBean and EJB. Since JavaBean is the fundamental component technology and is a basic building block of EJB, we have primarily focused on this technology in this chapter. Chapter 27 simplifies the generic concept of CORBA (Common Object Request Broker Architecture), which is a specification that describes how heterogeneous objects can interoperate. CORBA objects can be created/accessed using virtually any programming language (such as Java, C, C++, Smalltalk, and Ada) and can exist on any platform (such as Windows, Unix, Linux, and Solaris). In Chapter 28, we look into the primary concepts of Java Server Faces (JSF), which is a Java-based framework for creating web-based user interfaces. It combines the power of Struts and Swing and follows Model–View–Controller (MVC) architecture. Many examples, starting with a simple example JSF application, have been provided.
PREFACE ix ACKNOWLEDGEMENTS Bringing together important advanced Java concepts under a common roof is no easy task. The exercise was even more difficult due to the large volume of the manuscript. I, therefore, had a very tough time. However, the support from colleagues and many other key people led to successful completion of this project. I thank all of them. I am extremely grateful to the reviewers, as their feedback helped me in improving the technical accuracy and presentation of the chapters. It is said that “behind every successful man, there is a woman”. People will decide if I am successful. However, the woman in front, not behind me, is none other than my beloved wife Banhishikha Roy. No words can describe her contribution towards this work. I acknowledge her patience from the bottom of my heart. She always took some time out to help me develop the manuscript. This book would not have been successfully completed without her understanding and cooperation. The other “woman” is my six-year-old little girl, Rimisha. While working on the more demanding topics of the manuscript, my little daughter’s presence, even late at night, would calm me and bring a smile to my face. I love her dearly I have taken utmost care to eliminate any technical or typographical errors in the book and urge readers to send in their comments, constructive criticism, and suggestions, preferably through email (u_roy@it.jusl.ac.in and royuttam@gmail.com). I appreciate your feedback and hope you enjoy reading this book. Uttam K. Roy
BrieF contents Features of the Book iv Preface vi Detailed Contents xi PART I: INSIDE JAVA 1 1. Java Tools 3 2. Exception Handling 26 3. Multi-threading 45 4. Garbage Collection 68 5. Collection Framework 92 6. Generic Programming 113 7. Reflection 133 8. Java Native Interface 158 9. AWT and Swing 182 10. Java and XML 217 11. Input/Output 247 PART II: NETWORK PROGRAMMING 271 12. Basic Networking 273 13. Socket Programming 287 14. Remote Method Invocation 348 15. Java Mail API 392 16. Applets 421 17. Java XML-RPC 445 18. Java and SOAP 475 PART III: ENTERPRISE JAVA 501 19. Security 503 20. Servlet 557 21. Java Server Pages 583 22. Java Database Connectivity (JDBC) 625 23. Hibernate 657 24. Java Naming and Directory Interface 692 25. Java Message Service 714 26. Introduction to J2EE 739 27. Java and CORBA 770 28. Java Server Faces 801 Answers to Objective-type Questions 841 Index 849 About the Author 855
DetaileD contents Features of the Book iv Preface vi Brief Contents x PART I: INSIDE JAVA 1 1. Java Tools 3 1.1 Introduction 3 1.2 Javadoc 3 1.3 Javap 7 1.4 Jcmd 9 1.5 Jhat 12 1.6 Jdb 13 1.7 Jar 18 1.7.1 Syntax 19 1.7.2 Creating a JAR File 19 1.7.3 Viewing Contents of a JAR File 20 1.7.4 Extracting the Content 20 1.7.5 Updating a JAR File 21 1.7.6 Manifest File 21 2. Exception Handling 26 2.1 Exceptions 26 2.2 Handling Exceptions 27 2.3 An Example 28 2.4 Types of Exceptions 28 2.4.1 Checked Exceptions 29 2.4.2 Unchecked/Runtime Exceptions 29 2.5 Catching Exception 29 2.6 Tracing Stack 30 2.6.1 Multiple Catch Blocks 30 2.6.2 throw 31 2.6.3 throws 33 2.6.4 finally 34 An example 35 Some properties 36 2.6.5 try-with-resources Statement 37 2.6.6 Nested try-catch 39 2.7 Custom Exception Classes 40 3. Multi-threading 45 3.1 Introduction 45 3.2 Main Thread 45 3.3 Using Sleep 46 3.4 Creating Thread 47 3.4.1 Extending Thread 47 3.4.2 Implementing Runnable 48 3.5 Interrupting Thread 49 3.6 Suspending and Resuming 51 3.7 Thread Priority 52 3.8 Using join() 53 3.9 Synchronization 55 3.9.1 Synchronization and Atomicity 59 3.10 Deadlock 59 3.11 Inter-thread Communication 61 4. Garbage Collection 68 4.1 Introduction 68 4.2 Exploring JVM 69 4.2.1 Performance 69 4.3 JVM Options 70 4.4 Garbage Collection 70 4.5 Generational Garbage Collector 70 4.6 HotSpot’s Garbage Collection 72 4.7 Available Collectors 75 4.7.1 Serial Collector 75 4.7.2 Parallel Collector 76 4.7.3 Parallel Compacting Collector 77 4.7.4 Concurrent Collector 78 4.8 Some Commands 79 4.9 Tools 80 4.9.1 jstatd 80 4.9.2 jps 80 4.9.3 jmap 80 4.9.4 jstat 81 4.10 Tuning Memory Size 82 4.11 Tuning Heap Size 82 4.12 Tuning Young Generation 83 4.12.1 Tuning Survivor Space 83
xii CONTENTS 4.13 Accessing GC from Java Program 83 4.13.1 Inspecting GC Parameters 83 4.13.2 Explicit Garbage Collection 84 4.13.3 finalize() 84 4.14 Appendix 84 5. Collection Framework 92 5.1 Introduction 92 5.2 Benefits 93 5.3 Collection Interfaces 94 5.4 Collection Implementation 95 5.4.1 Set 95 HashSet 96 LinkedHashSet 97 5.4.2 SortedSet 98 TreeSet 98 5.4.3 List 98 ArrayList 99 LinkedList 100 5.4.4 Queue 100 LinkedList 101 PriorityQueue 102 5.4.5 Map 102 HashMap 103 LinkedHashMap 104 5.4.6 SortedMap 105 TreeMap 105 5.5 Algorithms 105 5.5.1 Sorting 106 Custom sort 106 5.5.2 Shuffling 106 5.5.3 Manipulation 107 Reversing 107 Swapping 107 Copying 107 Filling 107 Adding 107 5.5.4 Searching 108 5.5.5 Finding Extreme Values 108 5.5.6 Counting Frequency 108 6. Generic Programming 113 6.1 Introduction 113 6.2 Motivation 114 6.3 Solution 114 6.4 Collection Framework and Generics 116 6.5 Type Naming 117 6.6 Generic Methods and Constructors 117 6.7 Type Inference 118 6.7.1 Generic Methods 118 6.7.2 Constructors 119 6.7.3 Classes 119 6.8 Bounded Type Parameters 119 6.8.1 Multiple Bounds 120 6.9 Generics and Sub-type 121 6.10 Wildcards 122 6.10.1 Upper-bound Wildcard 123 6.10.2 Lower-bound Wildcard 124 6.10.3 Unbounded Wildcard 124 6.10.4 Wildcard and Sub-typing 125 6.11 Type Erasure 125 6.12 Backward Compatibility 126 6.13 Restrictions on Generics 127 6.13.1 Cannot Specify Primitive Type Arguments 127 6.13.2 Cannot Declare Static Fields of Type Parameters 127 6.13.3 Cannot Create Instances of Type Parameters 127 6.13.4 Cannot Use instanceof 128 6.13.5 Cannot Create Generic Arrays 128 6.13.6 Limitations on Exception 128 6.13.7 Cannot Use .class 129 7. Reflection 133 7.1 Introduction 133 7.1.1 Pros and Cons of Reflection 133 7.2 Classes 134 7.2.1 Class 134 Using getClass() 134 Using .class 135 Using forName() 135 Using TYPE field 136 7.2.2 Modifier 136 7.3 Inspecting Class 137 7.3.1 Getting Class Information 137 7.3.2 Getting Class Modifiers 138 7.3.3 Finding Implemented Interfaces 138 7.3.4 Finding Inheritance Hierarchy 139 7.3.5 Finding Annotations 139 7.4 Finding Class Members 140 7.4.1 Getting Fields 140 7.4.2 Getting Methods 142 7.4.3 Getting Constructors 143
CONTENTS xiii 7.5 Working with Class Members 143 7.5.1 Field Type 143 7.5.2 Field Modifiers 144 7.5.3 Accessing Fields 144 Accessing forbidden fields 145 Modifying final fields 145 7.5.4 Method Modifiers 146 7.5.5 Method Information 146 7.5.6 Invoking Methods 147 Accessing forbidden methods 147 7.5.7 Debugging with Reflection 148 7.5.8 Getting Constructor Modifiers 149 7.5.9 Instantiating Objects 149 7.5.10 Arrays 150 Checking array types 150 Creating new arrays 151 7.6 Dynamic Proxy 151 7.6.1 Designing Dynamic Proxy 151 7.6.2 Invocation Handlers 153 7.7 Disadvantage of Reflection 155 8. Java Native Interface 158 8.1 Introduction 158 8.2 Java Program with C/C++ 159 8.2.1 Writing Java Program 159 8.2.2 Compiling Java Program 160 8.2.3 Create Header File 160 8.2.4 Implement Native Method 161 8.2.5 Create Shared Library 162 8.2.6 Running the Program 162 8.3 Using C++ 163 8.4 Syntax Difference in C/C++ 163 8.5 Using Java Package 164 8.5.1 JNI Types and Data Structures 165 8.6 Passing Arguments 167 8.6.1 Passing Primitives 167 8.6.2 Passing Strings 168 8.6.3 Passing Primitive Array 169 8.7 Accessing Java Code from Native Program 171 8.7.1 Passing Object Array 172 8.8 Creating Objects 174 8.9 Exception Handling in JNI 174 8.10 Appendix 177 9. AWT and Swing 182 9.1 Introduction 182 9.2 AWT Class Hierarchy 183 9.2.1 Component 183 9.2.2 Container 183 9.2.3 Controls 185 9.3 Creating Container 185 9.3.1 Empty Frame 185 9.3.2 Frame with a Title 185 9.4 Adding Components 186 9.4.1 Adding a Label 186 9.4.2 Adding a Button 186 9.5 Layout 187 9.5.1 FlowLayout 187 9.5.2 GridLayout 187 9.5.3 BorderLayout 188 9.6 Using Panel 189 9.7 Text Field 189 9.8 TextArea 190 9.9 List 190 9.10 Checkbox 191 9.11 Check Box Group 191 9.12 Choice 192 9.13 Event Handling 192 9.13.1 Event Sources 192 9.13.2 Event Classes 192 9.13.3 Event Listeners 194 9.13.4 Example 194 9.13.5 Adapter Classes 197 9.14 Dialog Boxes 198 9.14.1 Simple Dialog 198 9.14.2 File Dialog 199 9.15 ScrollBar 200 9.16 Menu 200 9.16.1 Popup Menu 201 9.17 Swing 202 9.17.1 Containment Hierarchy 203 9.17.2 Adding Components 203 9.17.3 JTextField 203 9.17.4 JPasswordField 204 9.17.5 JTable 204 9.17.6 JComboBox 205 9.17.7 JProgressBar 205 9.17.8 JList 206
xiv CONTENTS 9.17.9 JTree 207 9.17.10 JColorChooser 209 9.17.11 Dialogs 210 9.17.12 Appendix A: Methods of Important Event Listener Interfaces 212 10. Java and XML 217 10.1 Introduction 217 10.2 XML and DOM 217 10.3 DOM Nodes 219 10.4 The Node Interface 221 10.4.1 Node Properties 221 10.5 Document Node 225 10.5.1 Document Node Properties 225 10.5.2 Document Node Methods 225 10.6 Element Node 227 10.6.1 Element Node Properties 227 10.6.2 Element Node Methods 227 10.7 Text Node 228 10.7.1 Text Node Properties 228 10.7.2 Text Node Methods 228 10.8 Attr Node 229 10.8.1 Attr Node Properties 229 10.9 Parsing XML 229 10.9.1 Creating Document 230 10.9.2 Navigating DOM Tree 230 Using root node 230 Getting all child nodes 231 Using getElements ByTagName 232 Using getElementById 233 Getting attributes of an element 233 Viewing DOM 235 10.9.3 Manipulating DOM Tree 236 Creating a node 236 Setting an attribute 237 Adding a node 237 Inserting a node 238 Deleting a node 239 Cloning a node 240 10.9.4 Java DTD Validation 241 11. Input/Output 247 11.1 Introduction 247 11.2 Streams 247 11.2.1 Byte Stream 249 11.2.2 Character Stream 251 11.2.3 Bridging Stream 251 11.2.4 Buffered Stream 252 Buffered byte stream 252 Buffered character stream 252 11.2.5 Reading from Keyboard 253 Reading character 253 Reading string 253 11.2.6 Console 254 11.3 Formatting 254 11.4 Data Streams 255 11.5 Object Stream 255 11.6 Reading/writing Arrays via Streams 256 11.7 Pipes 256 11.8 File I/O 258 11.9 Path 258 11.9.1 Creating a Path 258 11.9.2 Retrieving Path Information 258 11.9.3 Path Operations 259 Removing redundancy 259 Converting to URI 259 Joining paths 259 11.9.4 Comparing Paths 259 11.10 File 260 11.10.1 Checking Existence 260 11.10.2 Creating File 260 11.10.3 Deleting File 260 11.10.4 Copying a File 260 11.10.5 File Attribute 261 11.10.6 Reading, Writing, Creating Files 261 11.10.7 Random Access Files 262 11.10.8 Working with Directories 263 Listing Directory Contents 263 11.10.9 Walking Directory Tree 263 11.10.10 Watching Directory 264
CONTENTS xv PART II: NETWORK PROGRAMMING 271 12. Basic Networking 273 12.1 Java and the Net 273 12.2 Java Networking Classes and Interfaces 273 12.3 Getting Network Interfaces 274 12.3.1 Getting Interface Addresses 275 12.3.2 Getting Interface Properties 276 12.4 URL 277 12.4.1 Creating URL 277 12.4.2 Parsing URL 277 12.4.3 Web Page Retrieval 278 12.5 URLConnection 279 12.6 HttpURLConnection 280 12.6.1 URLEncoder/URLDecoder 281 12.7 Proxy 283 12.7.1 Using Command Line Arguments 283 12.7.2 Using System Properties 283 12.7.3 Using Proxy Class 283 12.8 ProxySelector 283 13. Socket Programming 287 13.1 Introduction 287 13.2 Client/server Programs 288 13.3 Sockets 289 13.3.1 Types of Socket 290 13.3.2 Ports 290 13.3.3 Socket Address 290 13.3.4 Socket Address and Java 291 13.3.5 Reserved Ports 291 13.4 TCP Sockets 292 13.4.1 The ServerSocket Class 294 13.4.2 The Socket Class 296 13.4.3 An Application 297 13.4.4 Complete Example 298 13.4.5 Running Example Program 299 13.4.6 Handling Multiple Client Requests 300 Iterative solution 300 13.4.7 Concurrently Solution 302 13.4.8 Sending and Receiving Objects Using TCP 306 Serializing an object 306 Reconstructing objects 308 13.4.9 An Example 309 13.4.10 Writing the Server 310 Writing interfaces 310 Implementing interfaces 310 Implementing server 311 Implementing client 312 Running the example 313 13.5 UDP Sockets 313 13.5.1 Datagram Packets 315 13.5.2 Datagram Server 315 13.5.3 Datagram Client 317 13.5.4 Receiving Multiple Datagrams 319 13.5.5 Sending and Receiving Objects Using UDP 321 13.5.6 Sending an Object 321 13.5.7 Reconstructing the Object 322 13.5.8 Running the Application 323 13.6 Multicasting 323 13.7 Multicast Sockets 323 13.7.1 Multicast Addresses 324 13.7.2 MulticastSocket Class 325 13.7.3 Sending Data 326 13.7.4 Receiving Data 326 13.7.5 Complete Example 327 13.7.6 Another Multicasting Example 328 13.7.7 A Text Conference Example 330 13.8 Appendix A (Useful Methods of ServerSocket Class) 332 13.8.1 Constructors 332 13.8.2 Methods 332 13.9 Appendix B (Useful Methods of Socket Class) 334 13.9.1 Constructors 334 13.9.2 Methods 335 13.10 Appendix C (Useful Methods of DatagramSocket Class) 338 13.10.1 Constructors 338 13.10.2 Methods 338
xvi CONTENTS 13.11 Appendix D (Useful Methods of DatagramPacket Class) 341 13.11.1 Constructors 341 13.11.2 Methods 342 13.12 Appendix E (Useful Methods of MulticastSocket Class) 343 13.12.1 Constructors 343 13.12.2 Methods 343 14. Remote Method Invocation 348 14.1 Introduction 348 14.2 Remote Method Invocation 348 14.2.1 Application Components 349 14.2.2 Basic Steps 350 14.3 Java RMI Interfaces and Classes 351 14.4 An Application 352 14.4.1 Writing an Interface 352 14.4.2 Writing Implementation class 354 Implementing the remote interface 354 Providing method implementation 355 Writing Constructor 356 14.4.3 Writing an RMI Server 356 Creating a remote object 357 Exporting the object 357 Registering the stub 360 14.4.4 Writing an RMI Client 361 14.5 Compiling the Program 363 14.5.1 Compiling Server 363 14.5.2 Compiling Client 363 14.6 Generating Stub Classes 364 14.7 Running the Program 364 14.7.1 Start Server 364 14.7.2 Start Client 365 14.7.3 Understanding Object Registry 365 14.7.4 Using RMI URL 367 14.8 Callback 369 14.8.1 Creating Interfaces 370 14.8.2 Implementing Interfaces 371 14.8.3 Writing the Server 371 14.8.4 Writing the Client 372 14.8.5 Compiling the Application 372 14.8.6 Running the Application 372 14.9 Another Callback Application 373 14.10 Dynamic Object Activation 375 14.10.1 Basic Idea 375 14.10.2 Implementation 375 14.10.3 The Activation Protocol 375 14.10.4 An Example 376 Writing implementation class 376 Writing server class 377 Compiling and running the program 379 14.11 Dynamic Class Downloading 379 14.12 An Example 380 14.12.1 Writing an RMI Server 381 Write an interface 381 Implement the interface 381 Implement the server 382 14.12.2 Writing a Client 384 14.12.3 Compiling the Program 385 Creating interface classes 386 Compiling server 386 Compiling client 387 14.12.4 Running the Application 387 14.12.5 Start Client 388 15. Java Mail API 392 15.1 E-mail 392 15.2 JavaMail API 392 15.3 Installing JavaMail API 393 15.4 Sending Emails 393 15.4.1 Creating a Session Object 394 15.4.2 Compose a Message 395 15.4.3 Sending the Mail 396 15.4.4 Compiling and Running the Program 397 15.5 Sending Emails Directly Using Socket 397 15.6 Secured SMTP 398 15.6.1 Using SSL 399 15.6.2 Using TLS 399 15.6.3 Providing Authentication Information 400 15.7 Email Message Revisited 403 15.7.1 MIME 403
CONTENTS xvii 15.7.2 Single-part Message 404 15.7.3 Multi-part MIME Message 405 15.7.4 Composing a Mixed Message 406 15.7.5 Compiling the Program 407 15.8 Email with HTML Content 408 15.9 Accessing Email 409 15.9.1 POP 409 15.9.2 IMAP 410 15.9.3 Secured Mail Access 411 15.9.4 JavaMail API Support 411 15.9.5 Reading Email 411 15.9.6 Using Authenticator 413 15.10 Deleting Mails 413 15.11 Replying to Mails 414 15.12 Forwarding Mails 414 15.13 Copying Emails 415 15.14 List of SMTP, POP3 and IMAP Servers 416 16. Applets 421 16.1 Client Side Java 421 16.2 Life Cycle 422 16.2.1 init() 423 16.2.2 start() 423 16.2.3 paint() 424 16.2.4 stop() 425 16.2.5 destroy() 425 16.3 Writing an Applet 426 16.4 Generating Class File 426 16.5 Running the Applet 426 16.5.1 The Applet Tag 426 16.6 Security 430 16.7 Utility Methods 431 16.8 Using Status Bar 432 16.9 AppletContext Interface 432 16.10 Document Base and Code Base 433 16.11 Passing Parameter 434 16.11.1 Retrieving Parameter 434 16.12 Event Handling 435 16.13 Communication Between Two Applets 436 16.13.1 Using getApplet() Method 436 16.13.2 Using getApplets() Method 437 16.13.3 A Sample Application 438 16.14 Loading Web Pages 439 16.15 Interacting with JavaScript Code 440 17. Java XML-RPC 445 17.1 Introduction 445 17.2 XML-RPC Operational Principle 446 17.3 Data Types 447 17.3.1 Basic Data Types 447 17.3.2 Compound Data Types 449 17.4 XML-RPC Messages 451 17.4.1 Request Message 452 17.4.2 Response Message 453 17.4.3 Fault Message 454 17.5 Java XML-RPC 454 17.6 Installing the Apache XML-RPC Java Library 455 17.7 XML-RPC versus Java Data Types 455 17.8 Example 456 17.8.1 Writing the Server 456 17.8.2 Writing the Client 457 17.8.3 Running the Application 459 17.9 Dynamic Proxies 460 17.10 Using XmlRpcServlet 462 17.11 Using ServletWebServer 464 17.12 Introspection 466 17.12.1 Example 467 Listing methods 468 Finding method signature 469 Getting help 470 17.13 Limitations of XML-RPC 471 18. Java and Soap 475 18.1 Introduction 475 18.2 Differences with XML-RPC 475 18.3 Soap Architecture 476 18.4 SOAP Flavors 477 18.5 SOAP Messages 477 18.6 SOAP Binding 479 18.7 RPC Using SOAP 479 18.8 Web Service 480 18.9 JAX-WS 480 18.9.1 Developing Web Service 481 18.9.2 Deploying Web Service 482 18.9.3 Invoking Web Service 483 18.9.4 Tracking SOAP messages 485
xviii CONTENTS 18.9.5 Using WSDL 486 18.9.6 Document Style 489 18.9.7 Using Tomcat to Deploy Web Service 490 18.9.8 Using Ant to Build War File 492 18.9.9 Asynchronous Client 493 Polling 494 Callback 495 PART III: ENTERPRISE JAVA 501 19. Security 503 19.1 Introduction 503 19.2 Java Security Architecture 504 19.2.1 Language Security 504 19.2.2 Basic Security 504 19.2.3 Java Cryptography Architecture (JCA) 505 Secret-key cryptography 505 Public-key cryptography 506 19.2.4 Public Key Infrastructure (PKI) 506 Public key certificates 506 Certificate format 506 Digital signature 507 Key and certificate store 507 19.2.5 PKI Tools 507 19.3 Secure Communication 508 19.4 SSL 508 19.4.1 What does SSL do? 508 19.4.2 How does it do? 508 19.4.3 An Example 509 Writing the server 509 Writing the client 510 Compiling and running the application 510 19.4.4 Using Client Authentication 514 19.4.5 Using KeyStore 515 19.4.6 Ignoring Server Certificates 517 19.4.7 Working with HTTPS 517 19.5 keytool Revisited 519 19.5.1 KeyStore 519 19.5.2 Keystore Entries 520 Truststore 520 19.5.3 Keystore Aliases 520 19.5.4 Public Key Generation 520 19.5.5 Changing Password 521 19.5.6 Generating a Certificate Chain 521 19.5.7 Generating a Certificate Using Openssl 522 19.6 Generating Keys 524 19.6.1 Public Key Generation 524 19.6.2 Private Key Generation 524 19.7 Working with Keystore 525 19.7.1 Reading Keystore 525 19.7.2 Extracting Private Keys from Keystore 525 19.7.3 Storing Private Key and Certificate in Keystore 526 19.8 Working with Certificates 526 19.8.1 Reading Certificate Information 527 19.8.2 Creating Certificate 527 19.8.3 Converting Certificates 528 19.8.4 SignedObject 529 19.8.5 SealedObject 531 19.8.6 GuardedObject 534 19.9 Secure RMI 535 19.9.1 Writing Custom Socket Factories 538 19.10 Secure XML-RPC 539 19.10.1 Using XmlRpcServlet 539 19.10.2 Using Secure XML-RPC 540 19.11 Signing and Verifying JAR 542 19.11.1 Signing JAR 542 Signature (.SF) file 543 Signature block file 544 19.11.2 Verifying JAR 544 19.12 Multiple Signatures for a JAR File 544 19.13 Access Control 545 19.13.1 Installing Built-in Security Manager 546 19.13.2 Policy Files 546
CONTENTS xix 19.13.3 Policy File Syntax 547 Keystore entry 547 Grant entry 548 Permission entry 549 19.13.4 Custom Permission Class 549 19.14 An application 550 20. Servlet 557 20.1 Server-side Java 557 20.2 Advantages Over Applets 558 20.3 Servlet Alternatives 558 20.3.1 Common Gateway Interface (CGI) 558 20.3.2 Proprietary APIs 558 20.3.3 Active Server Pages (ASP) 559 20.3.4 Server-side JavaScript 559 20.4 Servlet Strengths 559 20.4.1 Efficient 559 20.4.2 Persistent 559 20.4.3 Portable 559 20.4.4 Robust 559 20.4.5 Extensible 559 20.4.6 Secure 560 20.4.7 Cost-effective 560 20.5 Servlet Architecture 560 20.6 Servlet Life Cycle 561 20.6.1 init() 562 20.6.2 service() 562 20.6.3 destroy() 562 20.6.4 Other Methods 563 20.7 GenericServlet 563 20.8 HttpServlet 563 20.9 First Servlet 564 20.9.1 Installing Apache Tomcat Web Server 565 20.9.2 Building and Installing Servlet 566 20.9.3 Invoking Servlet 567 20.10 Passing Parameters to Servlets 568 20.10.1 Passing Parameters Directly to a Servlet 568 20.10.2 Passing Parameters Directly to a Servlet 568 20.11 Retrieving Parameters 569 20.12 Server-Side Include 571 20.13 Cookies 574 20.13.1 Limitations of Cookies 575 20.14 Filters 575 20.14.1 Deploying Filter 577 20.15 Problems with Servlet 577 20.16 Security Issues 578 20.17 Appendix A: List of SSI Servlet Variables 578 21. Java Server Pages 583 21.1 Introduction and Marketplace 583 21.2 JSP and HTTP 584 21.3 JSP Engines 584 21.3.1 Tomcat 584 21.3.2 Java Web Server 586 21.3.3 WebLogic 586 21.3.4 WebSphere 586 21.4 How JSP Works 586 21.5 JSP and Servlet 587 21.5.1 Translation and Compilation 587 21.6 Anatomy of a JSP Page 590 21.7 JSP Syntax 591 21.8 JSP Components 591 21.8.1 Directives 591 Page directive 592 Include directive 594 21.8.2 Comments 594 21.8.3 Expressions 595 21.8.4 Scriptlets 595 Conditional processing 596 21.8.5 Declarations 596 21.8.6 Scope of JSP Objects 597 21.8.7 Implicit Objects 598 21.8.8 Variables, Methods, and Classes 600 Synchronization 601 21.8.9 Standard Actions 602 21.8.10 Tag Extensions 606 Tag type 606 Writing tags 606 21.8.11 Iterating a Tag Body 609 21.8.12 Sharing Data Between JSP Pages 611 21.9 Beans 612 21.9.1 useBean 612 21.9.2 setProperty 613
xx CONTENTS 21.9.3 getProperty 613 21.9.4 Complete Example 613 21.9.5 Other Usage 614 21.10 Session Tracking 614 21.10.1 Hidden fields 614 21.10.2 URL Rewriting 616 21.10.3 Cookies 616 21.10.4 Session API 617 21.11 Users Passing Control and Data between Pages 619 21.11.1 Passing Control 619 21.11.2 Passing Data 619 21.12 Sharing Session and Application Data 620 22. Java Database Connectivity (JDBC) 625 22.1 Introduction 625 22.2 JDBC Drivers 625 22.2.1 JDBC-ODBC Bridge (Type 1) 626 22.2.2 Native-API, Partly Java (Type 2) 626 22.2.3 Middleware, Pure Java (Type 3) 626 22.2.4 Pure Java Driver (Type 4) 626 22.3 JDBC Architecture 626 22.4 JDBC Classes and Interfaces 627 22.5 Basic Steps 627 22.6 Loading a Driver 628 22.7 Making a Connection 629 22.8 Execute SQL Statement 631 22.9 SQL Statements 631 22.9.1 Simple Statement 632 22.9.2 Atomic Transaction 635 22.9.3 Pre-compiled Statement 637 22.9.4 SQL Statements to Call Stored Procedures 638 22.10 Retrieving Result 640 22.11 Getting Database Information 641 22.12 Scrollable and Updatable ResultSet 642 22.12.1 Scrollability Type 643 22.12.2 Concurrency Type 643 22.12.3 Examples 643 22.13 Result Set Metadata 647 23. Hibernate 657 23.1 Introduction 657 23.2 Installing Hibernate 658 23.3 Basic Steps 658 23.4 Writing POJO Class 658 23.5 Creating a Table 659 23.6 Writing a Hibernate Application 659 23.7 Compiling and Running Application 663 23.8 Using Annotation 664 23.9 Environment Setup for Hibernate Annotation 664 23.10 Book Application Using Annotation 664 23.11 Function of Different Annotations 665 23.12 Object Life Cycle 666 23.13 Hibernate Query Language 667 23.13.1 From 667 23.13.2 Select 667 23.13.3 Where 668 23.13.4 Filtering 668 23.13.5 Order by 668 23.13.6 Group by 668 23.13.7 Parameter Binding 668 23.13.8 Update 669 23.13.9 Delete 669 23.13.10 Insert 669 23.13.11 Aggregate Methods 70 23.14 Using Native SQL Query 670 23.15 Named Queries 670 23.15.1 Defining Named Queries 671 23.15.2 Calling Named Queries 672 23.16 Generating DDL 673 23.17 Syntax of O/R Mapping File 674 23.18 Generator Class 676 23.19 Hibernate Tools 677 23.19.1 Using Hibernate Tools with Ant 677 23.19.2 Ant Task 678 23.19.3 Configuring Task 678 23.19.4 Exporters 679 23.19.5 Controlling Reverse Engineering 683 23.19.6 Controlling POJO Code Generation 685
CONTENTS xxi 24. Java Naming and Directory Interface 692 24.1 Naming Concepts 692 24.1.1 Naming Convention 693 24.1.2 Naming Context 693 24.1.3 Binding 693 24.2 Directory Concepts 694 24.2.1 Directory Context 694 24.3 Java Naming and Directory Interface 694 24.4 An Example 695 24.4.1 Writing the Server 695 24.4.2 Writing the Client 696 24.4.3 Running Application 696 24.5 Specifying JNDI Properties 697 24.6 Name Servers 697 24.7 Using ApacheDS 698 24.7.1 Installing and Starting ApacheDS 698 24.7.2 JNDI Properties for ApacheDS 699 24.8 Calculator RMI Application Using LDAP 699 24.9 Calculator RMI-IIOP Application Using JNDI 699 24.9.1 Server 699 24.9.2 Client 700 24.9.3 Running the Application 700 24.10 Naming Operations 700 24.10.1 Adding, Replacing and Removing Binding 701 24.10.2 Looking Up 701 24.10.3 Renaming 701 24.10.4 Listing 702 Using list() 702 Using listBindings() 702 24.11 Working with Subcontext 703 24.12 Working with Directory 703 24.12.1 Reading Attributes 703 24.12.2 Binding with Attributes 704 24.12.3 Creating Subcontext with Attributes 705 24.12.4 Adding Attributes 705 24.12.5 Modifying Attributes 706 24.12.6 Removing Attributes 706 24.12.7 Batch Operation on Attributes 707 24.12.8 Search 707 Basic search 707 Filters 709 25. Java Message Service 714 25.1 Messaging 714 25.2 JMS API 714 25.3 JMS Components 715 25.4 Messaging Models 715 25.4.1 Point-to-Point 716 25.4.2 Publish/Subscribe 716 25.5 Message Consumption 717 25.5.1 Synchronous 717 25.5.2 Asynchronous 717 25.6 Programming Model 717 25.7 Installing Open MQ 720 25.8 Writing JMS Application 722 25.9 Writing a P2P Producer 722 25.9.1 Running Example 723 25.10 Writing a P2P Synchronous Consumer 724 25.11 Writing a P2P Asynchronous Consumer 725 25.12 Writing a Pub/Sub Producer 726 25.13 Writing a Pub/Sub Synchronous Consumer 726 25.14 Running this Example 727 25.15 Writing a Pub/Sub Asynchronous Consumer 727 25.16 Browsing Queue 728 25.17 Using JNDI 729 25.18 Reliability Mechanisms 731 25.18.1 Acknowledgement 732 25.18.2 Message Persistence 732 25.18.3 Message Priority 732 25.18.4 Message Expiration 732 25.18.5 Temporary Destinations 733 25.19 Transacted Session 733 26. Introduction to J2EE 739 26.1 Overview of J2EE 739 26.2 Introduction to JavaBeans 740 26.2.1 Properties 741 26.2.2 Accessor Methods 741
xxii CONTENTS 26.3 Bean Builder 741 26.4 Advantages of JavaBeans 742 26.5 BDK Introspection 742 26.5.1 Design Patterns 743 26.6 Properties 744 26.6.1 Simple Properties 744 26.6.2 Bound Properties 745 26.6.3 Constrained Properties 748 Implementing constrained property support 748 Implementing constrained property Listener 749 Example 750 26.6.4 Indexed Properties 751 26.7 BeanInfo Interface 752 26.8 Persistence 756 26.9 Customizer 758 26.10 JavaBeans API 759 26.11 EJB 761 26.11.1 Benefits of EJB 761 26.11.2 Usage Scenario 761 26.11.3 EJB Architecture 761 26.11.4 Session Beans 762 Stateless session beans 762 Stateful session beans 762 26.11.5 Entity Beans 762 26.11.6 Message Driven Beans 763 26.12 Introduction to Struts Framework 763 26.12.1 Basic Idea 763 27. Java and CORBA 770 27.1 Introduction 770 27.2 CORBA Architecture 770 27.2.1 IDL 771 27.2.2 ORB 771 27.2.3 IIOP 771 27.2.4 IOR 771 27.3 Java IDL 772 27.4 Developing CORBA Applications 772 27.4.1 Write an Interface Using IDL 772 27.4.2 Mapping IDL Interface to Java 773 27.4.3 Implementing the Interface 774 27.4.4 Writing the Server 774 Binding IOR to naming service 775 27.4.5 Writing the Client 776 27.5 Compiling Applications 777 27.6 Running the Application 777 27.7 Using Properties 778 27.8 Stringified Object Reference 779 27.9 Using URL 780 27.9.1 Using corbaloc 780 27.9.2 Using corbaname 781 27.10 Using Tie 782 27.11 Persistent Objects 782 27.11.1 Running Persistent Application 784 27.12 Callback 784 27.13 Using Dynamic Invocation Interface (DII) 787 27.14 Using Dynamic Skeleton Interface (DSI) 789 27.14.1 Basic Steps 789 27.14.2 An Example 789 27.15 Using Out and Inout Parameter 791 27.15.1 Invoking Operation Using Holder Classes 792 27.15.2 An Example 792 27.16 RMI-IIOP 793 27.16.1 An Example 793 Writing an interface 793 Implementing the interface 794 Writing the server 794 Writing the client 794 Compiling server files 794 Compiling client files 795 Running the application 795 27.17 IDL to Java Language Mapping 795 28. Java Server Faces 801 28.1 Introduction 801 28.2 First Application 802 28.2.1 Installing JSF 802 28.2.2 Writing a JSF Page 803 28.2.3 Deploying the Application 804 28.2.4 Testing the Application 805 28.3 Request Processing Life-cycle 806 28.3.1 Restore View 806 28.3.2 Apply Request Values 807 28.3.3 Process Validations 807
CONTENTS xxiii 28.3.4 Update Model Values 808 28.3.5 Invoke Application 808 28.3.6 Render Response 808 28.4 Tracing Phases 808 28.5 Managed Bean 809 28.5.1 Using faces-config.xml File 810 28.5.2 Using @ManagedBean Annotation 811 28.5.3 Scope Annotations 811 28.5.4 @ManagedProperty Annotation 812 28.6 Accessing Managed Bean Programmatically 813 28.6.1 Using javax.faces.context. ExternalContext 813 28.6.2 Using javax.el.ELContext 813 28.6.3 Using evaluateExpressionGet() Method 814 28.7 Basic JSF Tags 814 28.8 Expression Language 817 28.8.1 Value Expression 818 28.8.2 Method Expression 819 28.8.3 Facelets 820 Templates 820 Custom tags 821 Composite components 823 Remove 824 28.8.4 Converter Tags 824 28.8.5 Displaying Messages 827 28.8.6 Validations 828 28.9 AJAX 830 28.10 Event Handling 831 28.10.1 Value Change Listener 831 Using value-ChangeListener attribute 831 28.10.2 Using <f:valueChangeListener> Tag 832 28.10.3 Action Listener 832 Using actioneListener attribute 832 28.10.4 Using <f:actionListener> Tag 833 28.11 An Event Handling Example 833 28.12 Page Navigation 834 28.12.1 Auto Navigation 834 28.12.2 Using Managed Bean 835 28.12.3 Using Navigation Rule in Faces-config.xml 835 Answers to Objective-type Questions 841 Index 849 About the Author 855
Comments 0
Loading comments...
Reply to Comment
Edit Comment