Platform-Specific Benefits


Sun provides different development platforms for different development problems one size does not fit all. Today we have three distinct Java development environments directed toward different processing requirements.

  • The Java 2 Standard Edition (J2SE) provides the middle ground solution to capture client development directed at the traditional PC and workgroup environments.

  • The Java 2 Enterprise Edition (J2EE) represents the high-end development environment required to support scalable solutions in business-to-business (B2B) and electronic commerce.

  • The Java 2 Micro Edition (J2ME) now represents the attack on the device market, specifically aimed at resource-constrained devices.

J2SE

As of this writing, the current release of the Java 2 Standard Edition (J2SE) is version 1.4. You can download the release from java.sun.com/j2se/.

The J2SE provides the packages and APIs necessary to build client- and server-side applications targeted at traditional PC and workgroup environments.

Primary support includes the following:

  • Java Applets

  • JavaBeans Component API

  • Java Networking

  • Java Utilities

  • Java Threads

  • Java Media

  • Java Foundation Classes/Swing

  • Security

  • Java Database Connectivity (JDBC)

  • RMI/IIOP

P2P applications can utilize any of these programming APIs and supporting packages to speed up and ease development. Of special significance to P2P are Java networking, Java utilities, Java threads, Java foundation classes and security.

Java Networking

Java provides a tremendous amount of support for building networked applications. The java.net package contains a number of classes that greatly simplify the complexity of sending and receiving information across the network.

Using Java's java.net.URL class, you can establish connections with, and write or read content to or from, Internet resources without having to know much about sockets or specific protocols such as HTTP. Programmers can use the java.net.Socket class to make point-to-point connections using TCP, or java.net.DatagramSocket for UDP connections. java.net.ServerSocket makes it possible to construct sockets that accept and manage incoming connections, making it simple to write servers.

Dynamic discovery of peers and resources is a cornerstone of the P2P architecture. Java supports not only point-to-point unicast sockets, but also multicast sockets that can be used to discover peers on subnets. This, combined with directed unicast to relay or rendezvous peers, provides a powerful combination for building dynamic networks of cooperating peers.

The multicast sender shown in Listing 2.1 provides a simple example of how to send a datagram using multicast.

Listing 2.1 MulticastSender Class
 import java.net.*; public class MulticastSender {     public static void main(String args[]) {         int port = 1234;         String address = "224.0.0.1";         String data = "Hello Multicast";         try {             InetAddress ip = InetAddress.getByName(address);             DatagramPacket packet =                 new DatagramPacket(data.getBytes(), data.length(), ip, port);             MulticastSocket ms = new MulticastSocket();             ms.send(packet);             ms.close();         } catch (Exception e) {             e.printStackTrace();         }     } } 

A multicast listener is shown in Listing 2.2:

Listing 2.2 MulticastListener Class
 import java.net.*; public class MulticastListener {   public static void main(String args[]) {     int port = 1234;     String address = "224.0.0.1";     byte[] data = new byte[256];     try {       InetAddress ip = InetAddress.getByName(address);       MulticastSocket ms = new MulticastSocket(port);       ms.joinGroup(ip);       DatagramPacket packet = new DatagramPacket(data, data.length);       ms.receive(packet);       String message =         new String(packet.getData(), 0, packet.getLength());       System.out.println(message);       ms.close();     } catch (Exception e) {       e.printStackTrace();     }   } } 

Running one or more listeners followed by a sender results in the message "Hello Multicast" being sent to each listener. Although there may be some details in the code that you might not be acquainted with, you can see how easy it is to construct an application that makes use of multicast. Building applications using sockets or URLS is just as simple.

Java Utilities

Collections are of special importance to P2P developers. A collection is an object that represents a group of objects, known as elements. The Java collections framework provides a consistent approach to using and manipulating sets or groups of objects. Using collections allows you to avoid implementation-specific details by providing access through a generic container interface. In other words, the specific implementation of the collection can change without having to modify the interface. This enables you to change representations of the underlying data structure if access patterns indicate performance gains are possible by using one structure over another.

Collections have different properties; for instance, some collections allow duplicates, whereas others do not. Some collections support the sequencing or ordering of elements, whereas others might appear at random.

The root interface in the collection hierarchy is represented by the java.util.Collection interface. The Set and List interfaces provide two of the most popular descendent interfaces.

Developers in other languages like C++ often combine third-party products that supply collection frameworks. Of course, this usually means yet another set of classes and templates to learn, all of which are unique to a vendor's API. The Java platform, however, includes a collections framework. The primary advantages of a collections framework are that it

  • Reduces programming effort The proper use of collections can dramatically decrease the amount of code that must be written and maintained.

  • Increases performance and flexibility In most cases, the performance provided by the generic collection classes will outperform custom collection classes. In addition, different interfaces provide different performance tradeoffs. It is important to understand the implementation details of each interface so you can tune your program to the appropriate data structure.

  • Provides interoperability Collections can be passed between programs using a common language.

  • Reduces the learning curve Collections reuse many of the same method calls, which helps to minimize the time required to learn a collection's unique APIs.

  • Reduces the development effort This reduces the time and effort required to design, code, and test most projects.

  • Reduces programming errors and promotes reuse This provides a standard interface for collections and algorithms to manipulate them. It also uses tested framework code instead of ad hoc project code.

The Java collections framework consists of

  • Collection interfaces These interfaces represent different types of collections, such as sets, lists, and maps. These interfaces form the basis of the framework.

  • Collection implementations These classes represent the implementations of the collection framework interfaces.

  • Wrapper implementations Wrappers such as java.util.Collections augment primary collection functionality by adding polymorphic manipulation, collection transformation, and synchronization. Synchronization is especially important in multithreaded applications, where modification of data can occur in multiple threads.

  • Abstract implementations Partial implementations help to reduce the customization coding effort required to implement a primary collection interface.

Java Threads

Java's support for threads makes it a strong candidate for the multiprocessing capabilities required of peers in P2P networks. From a network perspective, this includes but is not limited to discovery and search. Both of these operations can take an inordinate amount of time when using slow network connections, or when the search horizon is extremely large.

Java threads provide an easy approach to providing multiple streams of execution within a process. So, while discovery or a Web search is being initiated, other processes such as supporting a user interface or establishing connections to multiple peers can proceed without being blocked by slow synchronous activities.

The Monitor class (shown in Listing 2.3) provides an example of extending the Java Thread class. Monitor is a thread that runs, waits a specified amount of time, then runs again. This example simply prints out the system time. However, it could be used to invoke a heartbeat process that periodically examines network utilization, file system capacity, or the number of concurrent connections to provide adaptive behavior in P2P networks.

Listing 2.3 Monitor Class
 public class Monitor extends Thread {    private volatile Thread listener;    private int frequency;    public Monitor(int frequency) {       this.frequency = frequency*1000;    }    public void run() {       listener = Thread.currentThread();       while(listener != null) {          // do something useful!          System.out.println(System.currentTimeMillis());          Thread.sleep(frequency);       }    }    public void stopMonitor() {       listener = null;    } } 

A using application would start Monitor with the following code fragment:

 Monitor monitor = new Monitor(60);  monitor.start() 
Java Foundation Classes

Swing, along with AWT, provides support for the visual components of your P2P application. Swing provides support for all the usual visual widgets in graphical user interfaces, such as buttons, tables, trees, lists, and so on. In addition, it provides support for features that might be useful to P2P clients, such as browsing Web sites and documents.

Listing 2.4 shows the ease with which you can create a simple document browser using a Swing JEditorPane and the java.net.URL class.

Listing 2.4 URLViewer Class
 import java.awt.*; import java.net.*; import javax.swing.*; public class URLViewer extends JFrame {   private URL url;   private JEditorPane webView;   public static void main(String[] args) {     URLViewer viewer =       new URLViewer("http://www.pearsonptg.com/book_detail/ 0,3771,0672323990,00.html");   }   public URLViewer(String address) {     super("URLViewer");     webView = new JEditorPane();     webView.setEditable(false);     webView.setPreferredSize(new Dimension(400, 400));     JScrollPane scrollPane = new JScrollPane(webView);     getContentPane().add(scrollPane, BorderLayout.CENTER);     pack();     try {       url = new URL(address);       webView.setPage(url);       setVisible(true);     } catch (Exception e) {       e.printStackTrace();     }   } 

JEditorPane encapsulates the functionality required to display HTML. Besides that, the code only makes use of one other Swing component, JScrollPane, to make it possible for the user to scroll the contents.

Note

JEditorPane is currently limited to supporting HTML 3.2. Consequently, some sites that you may browse might not display correctly. As a note, JEditorPane is also capable of displaying plain text and RTF.


Swing has an extensive set of packages that rival any GUI library on the market. Performance continues to be an area where improvements are being made.

Security

Robust network security will continue to gain importance in P2P architecture. Network security is commonly defined as the protection of information, systems, and services against manipulation, mistakes, and disasters. It is comprised of authentication, authorization, integrity, confidentiality, and nonrepudiation.

  • Authentication is the most common type of network security. It generally involves a user or process demonstrating some form of evidence to prove identity. Such evidence might be information only the user would likely know (a password), or it might be information only the user could produce (signed data using a private key).

  • Authorization involves the capability to enforce access controls upon an authenticated user. This is commonly implemented using an access control policy associating user access rights to system resources, such as databases, files, and processes.

  • Integrity means ensuring that messages are delivered correctly, and that messages in transit have not been tampered with maliciously.

  • Confidentiality and privacy ensure that data cannot be seen or disclosed over the network by outside parties. Encryption is a procedure used to convert text into code in order to prevent any but the intended recipient from reading that data. It can be used to ensure the confidentiality of data, the authentication of the data sender, or the integrity of the data sent.

  • Finally, nonrepudiation guarantees that a sender cannot deny having sent a particular message.

Chapter 10, "P2P Security," discusses these topics in more detail, and provides a look at how Java can be used to build secure P2P applications.

Network security in Java is based on three primary components: Java Secure Sockets Extension support, the Java Authentication and Authorization Service, and Java cryptography extensions.

Secure Sockets Layer

The Secure Socket Layer (SSL) protocol provides encryption, authentication, and integrity of data by introducing a protocol layer above TCP/IP, and defining a handshake process that ensures communicating peers are authenticated. All data in transit is encrypted to ensure confidentiality. The Java Secure Sockets Extension (JSSE) supports SSL 3.0 and its successor, Transport Layer Security (TLS) 1.0. P2P applications can use JSSE to protect their network communication.

The JSSE was an optional package (extension) prior to JDK 1.4, and was a separate download from the core distribution. As of JDK 1.4, JSSE has been integrated into the core platform.

Java Authentication and Authorization Service (JAAS)

The Java Authentication and Authorization Service (JAAS) provides a framework and standard API for authenticating and authorizing users in Java-based applications. Java applications can now provide code-centric access control, user-centric access control, or a combination of both.

JAAS provides a means to validate users, and can make certain that a user is able to perform an action by using existing frameworks such as Kerberos, and it integrates those frameworks into standard Java security mechanisms. JAAS performs authentication using "pluggable" authentication technologies, making it possible to construct applications that are portable, in spite of the potentially different authentication mechanisms that may be required at deployment. It also relieves applications from managing identities and the low-level details of authentication themselves they can let Unix or Windows NT provide the facilities.

Like JSSE, JAAS was an optional package prior to JDK 1.4. It is now a part of the basic services.

Java Cryptography Extensions

Java's cryptography extensions (JCE) provide most of the building blocks for secure applications. Fundamentally, JCE supports encryption and decryption, message authentication and key generation, and management. These services form the foundation for protecting information exchanged between parties.

Like other Java frameworks, JCE uses "pluggable" modules, making it possible to implement solutions independent of the underlying technology. The standard provider implements many useful and popular algorithms such as DES (FIPS PUB 46-1) and Triple DES. Although the standard provider is usually sufficient, providers that implement other algorithms, like the new federal standard for encryption AES, or cryptographic services can be obtained from companies such as RSA Security.

JCE was also an optional package prior to JDK 1.4 that is now a part of the standard JDK.

J2EE

As of this writing, the current release of the Java 2 Enterprise Edition (J2EE) is version 1.3.1. You can download it from http://java.sun.com/j2ee/.

The J2EE provides the packages and APIs necessary to build scalable high-end solutions in business-to-business (B2B) and electronic commerce.

Primary support includes the following:

  • JDBC

  • Enterprise JavaBeans

  • JavaServer Pages and Servlets

  • Java Messaging Service

  • JavaMail

  • Java Transaction Architecture (JTA)/Java Transaction Services (JTA)

  • JNDI

P2P applications can utilize any of these programming APIs and supporting packages to build enterprise-level applications. As P2P applications mature, it's likely that these technologies will begin to interoperate, and might eventually integrate. Because J2EE provides a mature foundation for enterprise applications that is widely implemented, Appendix A provides an overview that should be useful to P2P programmers in understanding the breadth and architecture of the platform. Of the several standards that make up J2EE, JMS is particularly significant to P2P.

Java Messaging Service

The Java Messaging Service (JMS) provides a common way for Java clients to create, send, receive, and read messages. J2EE provides JMS as the interface to message-oriented middleware. JMS tries to standardize the interface to messaging systems.

JMS supports two models of communication:

  • Point-to-point Involves a single requestor sending a message to a single responder.

  • Publish/subscribe Enables a single requestor to send a message to an unknown number of responders, also known as subscribers.

Message addressing is based on the concept of topics, or names that identify message queues. Typically, JMS is implemented in an enterprise that has control over queue identity and can configure clients with the necessary information to find and access these resources. In this respect, P2P is more dynamic. Peers discover resources dynamically.

However, P2P and JMS both present compelling integration possibilities. For instance, a P2P application might subscribe to a known enterprise JMS topic, and receive notification of events in the enterprise that are of special significance to the P2P application. The P2P application could then act as a gateway to the P2P network. This provides a more secure interface to the external world from the enterprise, and still offers the advantages of dynamic discovery. The P2P peer and the JMS system are able to secure their identity and information to the desired level. This could include Java authentication and authorization services.

The P2P client acts as a rendezvous point for information housed in the enterprise messaging system. The messaging system only publishes information to the "P2P topic" that it wants the peer network to know. Trading markets and quoting applications might use this technique to increase access to commodities and securities yet still maintain control over the publication process.

Chapter 12, "Messaging and Java APIs for XML," explains JMS further and provides an example of how to use JMS.

J2ME

The Java 2 platform, Micro Edition (J2ME) is a more recent Java application environment. It is a framework for the deployment and use of Java technology in the post-PC world. J2ME software is configured for a variety of market segments.

J2ME is targeted at the device market, specifically at resource-constrained devices. It features a highly optimized runtime environment designed to efficiently use the available resources and provide the best possible performance. P2P applications have an opportunity to connect these devices to one another and to more capable peers. J2ME can help significantly.

Primary support includes the following:

  • Personal Java API (MIDP/CDC)

  • Embedded Java (CLDC)

The J2ME architecture is designed to be modular, using two fundamental elements: configurations and profiles. Together, they deliver a specification for consumer electronics and embedded device manufacturers to implement on their products.

Configurations and Profiles

A configuration is a virtual machine and a minimal set of basic class libraries and APIs. It specifies a generalized runtime environment for consumer electronic and embedded devices, and acts as the Java platform on the device.

A profile is an industry-defined specification of the Java APIs used by manufacturers and developers to address specific types of devices. A profile is built on top of and utilizes the underlying configuration necessary to provide a complete runtime environment for a specific kind of device. Profiles specify both the APIs and the configuration. An application written to the specification can execute in the specified Java technology environment without the addition of other Java classes (see Figure 2.3).

Figure 2.3. A configuration and profile provide the building blocks to J2ME.

graphics/02fig03.gif

Two configurations make up current J2ME technology:

  • Connected Limited Device Configuration (CLDC)

  • Connected Device Configuration (CDC)

Connected Limited Device Configuration

The Connected Limited Device Configuration (CLDC) was developed for devices with a small amount of memory. It is used in small, resource-constrained devices, each with memory in the range of 160 512KB. This provides the minimal functionality needed to minimize the memory footprint for memory-constrained devices. These devices usually contain 16- or 32-bit processors, and a minimum total memory footprint of 128KB. The Mobile Information Device Profile (MIDP) is used with CLDC. It is targeted at devices such as cell phones (see Figure 2.4).

Figure 2.4. CLDC and MIDP targeting the "weak" device market.

graphics/02fig04.gif

The CLDC is composed of the K virtual machine (KVM) and basic class libraries that can be used on a variety of devices. The KVM is a portable virtual machine designed for small-memory, limited-resource, network-connected devices. Newer, 32-bit devices with between 512KB and 1MB of memory can take advantage of the CLDC HotSpot virtual machine, which offers increased performance.

Connected Device Configuration

The Connected Device Configuration (CDC) was developed for devices with relatively large amounts of memory two megabytes or more of total memory available for the Java platform. These devices typically require the full features and functionalities of the Java virtual machine. Target devices for CDC contain connectivity to a network with a wireless, intermittent connection and limited bandwidth (9600bps or less). Some devices that might be supported by CDC include residential gateways, next-generation smart phones, two-way pagers, Personal Digital Assistants (PDAs), home appliances, point-of-sale terminals, and automobile navigation systems. Currently, CDC has a profile called the Foundation Profile. The CDC is a superset of CLDC, and therefore a CLDC-compliant profile is upwardly compatible with CDC.

The Foundation Profile

The Foundation Profile is a set of Java APIs that, together with the CDC, provides a complete J2ME application runtime environment targeted at consumer electronics and embedded devices. The C virtual machine (CVM) in the CDC is the engine for the Foundation Profile libraries. The CVM is a full-featured virtual machine designed for devices needing the functionality of the Java 2 virtual machine feature set, but with a smaller footprint (see Figure 2.5).

Figure 2.5. CDC and Foundation Profile targeting the "strong" device market.

graphics/02fig05.gif

In general, the Foundation Profile contains the complete basic Java packages from J2SE technology, except that the GUI dependencies on java.awt are removed. The CVM supports version 1.3 of the Java 2 Platform, and includes security, weak references, JNI, RMI, and JVMDI.

The J2ME architecture is changing rapidly. To find the latest information, you might want to visit the Sun Microsystems site at http://java.sun.com/j2me/.

The documentation and API specifications for the following releases can be downloaded from the Sun Web site at java.sun.com/products.

  • The CDC release: java.sun.com/products/cdc

  • The CVM release: java.sun.com/products/cdc/cvm

  • The Foundation Profile release: java.sun.com/products/foundation

XML

As you will learn throughout the book, XML is a key component in P2P architecture. It is rapidly becoming the encoding standard for message exchange on the Web.

Java provides robust support for XML that goes far beyond simple message parsing. There are now a number of optional packages available to minimize your development requirements for processing XML-based message exchanges in B2B and Web services.

The JAX Pack

The Java XML Pack, also known as the JAX Pack, is a suite of Java technologies for XML. The Java XML Pack attempts to address the need for Java processing across standards for XML such as SAX, DOM, XSLT, SOAP, UDDI, ebXML, and WSDL. It provides a single bundle of packages to jumpstart the Java processing of relevant XML technologies. In addition to the overview here, the JAX pack will be explored some more in Chapter 12, "Messaging and Java APIs for XML."

Java API for XML Processing

The Java API for XML Processing (JAXP) provides support for popular XML document-processing standards such as SAX, DOM, and XSLT. JAXP enables you to use any XML-compliant parser from within your application while standardizing the interface between implementations. It does this with what is called a pluggability layer, which enables you to plug in an implementation of the SAX, DOM, or XSL APIs.

The JAXP 1.1 reference implementation provides the Xalan XSLT processor and the Crimson parser, which was developed jointly between Sun and the Apache Software Foundation.

SAX is an event-driven XML parser. In other words, SAX triggers notifications to using applications when it recognizes an element in an XML document. SAX is used when you want to read XML data and parse it to find and process elements quickly.

DOM permits you to create an object model of an XML document. It enables you to not only read and parse the document, but also manipulate its contents. DOM creates an in-memory representation of the XML document. Each element is represented as a node that can be traversed and used to add and remove content from the document.

XSL allows you to transform an XML document from one XML representation to another. Besides normal conversions such as XML to HTML, XSL transformations can be used to bridge proprietary XML formats to industry-standard protocols and representations. These bridges open up possibilities for enabling P2P XML data to interoperate with industry standards such as ebXML.

Java Architecture for XML Binding

The Java Architecture for XML Binding (JAXB) maps XML elements to classes in the Java programming language. Like DOM, JAXB enables access to XML data in memory, but generally requires a smaller memory footprint. JAXB does not build in tree manipulation capabilities such as those supported by DOM. JAXB requires a schema or document type definition (DTD) to be defined for the XML document. It generates the Java classes based on the DTD definition and a JAXB defined schema that you must construct. You can use JAXB to create Java objects and convert data between different types.

Java API for XML Messaging

The Java API for XML Messaging (JAXM) implements SOAP messaging with attachments. It extends SOAP to provide a foundation for message profiles. A message profile is an implementation of a standard, such as the ebXML Transportation, Routing, and Packaging Message Handling Service. JAXM supports simple point-to-point SOAP messages, as well as message providers. Message providers enable asynchronous messaging between a SOAP requestor and a SOAP responder by introducing a level of indirection between the source and destination. A message provider can be an implementation of JMS.

A standalone client is limited to using a point-to-point connection that goes directly from the sender to the recipient.

To use a messaging provider, an application must obtain a connection to a messaging provider rather than to a specified recipient. You can get a provider connection by using a naming service. Once you have a connection, you can populate a standard SOAP message header and request. You can also customize message content using message factories.

JAXP also supports attachments. Any data can be used in an attachment, even non-XML data. This is another possible bridge between P2P and XML-based messaging systems. P2P applications can use the attachment specification to transfer data such as images, audio, and video files using SOAP-defined exchanges.

Java API for XML Registries

The Java API for XML Registries (JAXR) provides a standard Java API for interacting with XML registries such as UDDI and ebXML Registry/Repository.

Business registries provide the advertising capabilities for businesses on the Internet. They are often compared to the electronic "yellow pages" for business service publication. They contain a listing of the products and services that a business wants to promote electronically.

JAXR provides a Java interface to using business registries that are based on open standards or industry consortium-led specifications, such as UDDI.

Businesses can register themselves with a registry or discover other businesses with which they might want to do business. A business supplies its name, a description, and some classification concepts to facilitate searches. Standards groups have developed DTDs for particular kinds of XML documents. Because the DTD is stored in a standard business registry, both parties can use JAXR to access it.

A business can use JAXR to search a registry for other businesses. JAXR also supports using an SQL query to search a registry. Registries have become an important component of Web services because they enable businesses to collaborate with each other dynamically in a loosely coupled way.

JAXR enables enterprises to access standard business registries from the Java programming language.

Java API for XML-Based RPC

The Java API for XML-based RPC (JAX-RPC) supports XML-based remote procedure call (RPC) functionality conforming to the SOAP 1.1 specification.

The Java programming language already has two other APIs for making remote procedure calls: Java IDL and Remote Method Invocation (RMI). All three have an API for marshaling and unmarshaling arguments, and for transmitting and receiving procedure calls. The difference is that JAX-RPC is based on XML, and is geared to Web services. Java IDL is based on the Common Object Request Broker Architecture (CORBA) and uses the Object Management Group's Interface Definition Language (OMG IDL). RMI is based on RPC, where both the method calls and the methods being invoked are in the Java programming language although with RMI over IIOP, the methods being invoked might be in another language.

All varieties of RPC are fairly complex, involving the mapping and reverse mapping of data types and the marshaling and unmarshaling of arguments. However, these take place behind the scenes and are not visible to the user. JAX-RPC continues this model, which means that a client using XML-based RPC from the Java programming language is not required to work with XML or do any mapping directly.

Although JAX-RPC implements a remote procedure call as a request-response SOAP message, a user of JAX-RPC is shielded from this level of detail. So, underneath the covers, JAX-RPC is actually a specialized form of SOAP messaging. In contrast, JAXM is a more robust form of SOAP messaging. This is especially true if a higher-level protocol such as ebXML is layered on top of SOAP.

The following list includes features that JAXM can provide and that RPC, including JAX-RPC, does not generally provide:

  • Asynchronous messaging

  • Routing of a message to more than one party

  • Reliable messaging with features such as guaranteed delivery



JavaT P2P Unleashed
JavaT P2P Unleashed
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net