2010년 8월 23일 월요일

java unicode encoding test

Unicode encoding: Spanish

Unicode encoding: Spanish


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Unicode : System.Windows.Forms.Form {
System.Windows.Forms.Label myLabel = new System.Windows.Forms.Label();

public Unicode()
{
this.SuspendLayout();

this.myLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 50.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.myLabel.Location = new System.Drawing.Point(20, 20);
this.myLabel.Size = new System.Drawing.Size(800, 800);

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(800, 200);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.myLabel});
this.Name = "Unicode";
this.Text = "Unicode";
this.Load += new System.EventHandler(this.Unicode_Load);
this.ResumeLayout(false);
}

[STAThread]
static void Main()
{
Application.Run(new Unicode());
}

private void Unicode_Load(object sender, System.EventArgs e)
{
// Spanish
char[] spanish = {'\u0042', '\u0069', '\u0065',
'\u006E', '\u0076', '\u0065', '\u006E', '\u0069',
'\u0064', '\u006F', '\u0020', '\u0061', '\u0020' };

myLabel.Text = new string(spanish) + "Unicode" + '\u0021';
}
}



Related examples in the same category
1.Unicode encoding: English
Unicode encoding: English
2.Unicode encoding: German
Unicode encoding: German
3.Unicode encoding: French
Unicode encoding: French
4.Unicode encoding: Japanese
Unicode encoding: Japanese
5.Unicode encoding:
Unicode encoding:
6.Unicode encoding: Russian
Unicode encoding: Russian
7.Unicode encoding: implified Chinese
Unicode encoding: implified Chinese

2010년 8월 15일 일요일

2.2.3. Component Module Assembly Example

2.2.3. Component Module Assembly Example

Suppose we have a web application that maintains profiles for each user, and a profile
contains various preferences for the behavior of the application. The profile data is stored
in a database, and an EJB component is used to represent each profile within the
application. The application also includes a JSP web component that provides an editor
for profiles, where each user can specify his preferences. The JSP makes use of the profile
EJB to access the profile data stored in the database.
Given this architecture, our application needs a web component module to deploy the JSP
and an EJB module to deploy the profile EJB. Each of these modules will need its own
deployment descriptor and will be packaged into a jar file to be assembled into the final
application.

2010년 8월 13일 금요일

2.2.2. Deployment Descriptors

2.2.2. Deployment Descriptors

Each component module (except for applet jar files) includes a standard J2EE deployment
descriptor. These descriptors are key to the assembly and deployment process in J2EE.
The deployment descriptor knits together all the bits and pieces in the module jar file into
actual components and describes to the container how each component should be
managed. Without the deployment descriptor, the module jar just looks like a bag of Java
classes and other files to the container.
Component deployment descriptors specify these major sets of information for the
container:

Module descriptive information

In most cases, a component module as a whole can be given some descriptive
information, such as a name, a description, and so on. This information can be used
by application server management tools and server logs to provide human-readable
information about the components deployed in the server.

Component elements

Each component (EJB, web, or resource connector) is made up of one or more parts.
A web component is implemented as either a servlet class or a JSP file. An entity EJB
is implemented as a bean implementation class, one or more client interfaces, one or
more home interfaces, and a primary key class. For each component in the module
jar file, the container needs to be told the parts that make up the component.

Configuration data for component services

Each type of component makes use of specific services provided by the container.
Some of these services are optional; some are part of the standard runtime
management provided by the container. Web components use basic instantiation and
lifecycle services, optional security services, and so on. EJBs use more elaborate
lifecycle services, security services, persistence services, transaction management
services, and so on. Where there are options in terms of how these services are
managed at runtime, the deployment descriptor allows you to specify these options.

Resource and component dependencies

A component may make use of various resources that are expected to be deployed in
its runtime environment in the application server. These may include JDBC
DataSources used to make database connections, JavaMail Sessions used to create
and send/receive email messages, and so on. Also, components can make use of other
components. A web component might make use of a session EJB to perform some key
tasks on behalf of users of its interface, and the session EJB may in turn make use of
an entity EJB to access persistent data. These dependencies on external resources and
components need to be declared in the deployment descriptor as well.
The full format of each of the various component deployment descriptors is described in
Appendix A and the details of their use are demonstrated in the examples in Chapters 3,
4, 6, and 12. The following example demonstrates the general assembly process for
component modules , including the use of deployment descriptors.[*]

2.1.3.3. Physical deployment

2.1.3.3. Physical deployment

The physical steps that you take to deploy an application in an application server are a
vendor-specific detail. The resource and component references might be resolved using
server-specific configuration files, as depicted in Figure 2-3, or an application server may
provide a web-based administration tool that allows you to graphically link references in
deployment descriptors to actual resources and components running in the application
server. The documentation for your application server should explain the details.
Now that we've seen the J2EE assembly and deployment model at a conceptual level, let's
run through the technical details, starting with the creation of component modules, then
application assemblies, and then deployment. Along the way, we'll work with a concrete
example application consisting of web and EJB components.

2.1.3.3. Physical deployment

2.1.3.3. Physical deployment

The physical steps that you take to deploy an application in an application server are a
vendor-specific detail. The resource and component references might be resolved using
server-specific configuration files, as depicted in Figure 2-3, or an application server may
provide a web-based administration tool that allows you to graphically link references in
deployment descriptors to actual resources and components running in the application
server. The documentation for your application server should explain the details.
Now that we've seen the J2EE assembly and deployment model at a conceptual level, let's
run through the technical details, starting with the creation of component modules, then
application assemblies, and then deployment. Along the way, we'll work with a concrete
example application consisting of web and EJB components.

2010년 8월 12일 목요일

2.1.3.2. Runtime classloading models

2.1.3.2. Runtime classloading models

Another key consideration when deploying applications is the classloading model used by
the application server. Typically, a J2EE application server runs within a parent Java
virtual machine, and that parent JVM may spawn other JVMs or non-Java processes to
run specific runtime elements (messaging services, directory services, etc.). Within the
application server's JVM, the management of classloaders can be done in a variety of ways.

The most simplistic approach would be to have all applications share the same classloader.
In a multiple application scenario, this is usually not desirable since various applications,
or even different versions of the same application, may depend on different versions of
Java

Figure 2-3. Deployed application

libraries and classes, which would cause conflicts in a single-classloader situation (the first
version of a class loaded at runtime would be used by all applications in the server). If an
application server runs all applications within the same classloader, then you may find
yourself forced to run multiple server instances in order to run each application with the
proper versions of libraries and classes.

A more realistic runtime model would be to assign a separate classloader to each deployed
application. This allows each application to load its own versions of specific classes,
independent of other applications. Assuming that the server is using the standard Java
classloader implementation, each application classloader would be a child of the server's
main classloader, so any libraries that you truly want to share across all applications (i.e.,
the same version used by all applications) will be loaded by the main server at startup. This
is typically done by either adjusting the server's startup classpath or putting the shared
libraries in a special library directory.

Some application servers impose a single classloading scheme on deployed applications,
while others allow you to configure the classloading scheme at a server or an application
level. It's important to understand the classloading schemes supported by your application
server and to adjust these settings if needed.

2.1.3. Deploying Applications

2.1.3. Deploying Applications

Deploying an application involves several steps, including resolving resource and
component references , managing the classloader used by the application server or servers,
and finally, physically deploying the application. We describe this process next.

2.1.3.1. Resolving resource and component references

Once we move our application assembly into an application server environment (i.e.,
deploy our application), we need to settle all of the resource and component references
contained in the various deployment descriptors. In the J2EE model, application servers
make resources available to applications through an internal directory, accessed at
runtime using the Java Naming and Directory Interface (JNDI). This internal directory
could be a full LDAP server, a CORBA Naming Service, or any other directory service
supported by JNDI.

Figure 2-3 shows the situation after a J2EE application assembly has been successfully
deployed to an application server environment. The resource and component references
in the module descriptors have been linked to deployed resources and components in the
application server. These references are linked through the application server's JNDI
service: components and resources have been deployed in the application server and
"published" in its JNDI service under specific names. These components and resources
are then linked to the references in the deployment descriptors in our deployed application,
and the application is fully deployed.

If a component reference in a deployment descriptor needs to be linked to a component
residing in the same application assembly, it's possible to make that link directly in the
module deployment descriptor, and not through the server's JNDI service. This is depicted
in Figure 2-3 by the "internal reference" link between the two modules in the application.
Otherwise, the resource and component references need to be resolved to real assets
through the application server's JNDI service.

2.1.2.2. Two-level name resolution

2.1.2.2. Two-level name resolution

Many application servers support two-level name bindings for the linking of JNDI names
to actual assets. This capability offers flexibility and, in some cases, efficiency when
operating a number of components and applications in the same server.
Two-level name binding allows you to assign an independent name to an asset when
configuring it within the application server and then link this asset name to the name
specified in the component deployment descriptors. Suppose, for example, that a
deployment descriptor declares a requirement for a JavaMail Session to be deployed on
the server under the name java:comp/env/mail/AppSession. If the application server
supports two-level name bindings, we can configure a Session on the server under an
independent name, such as java:comp/mail/GenericSession, and link the asset name to
the name required by the component module. In effect, this linking ensures that the
runtime JNDI lookup at java:comp/env/mail/AppSession actually resolves to the
Session deployed under java:comp/mail/GenericSession. The mechanics of making this
linkage is application-dependent—it can be done in a server-specific configuration file, in
a web administration tool, or in something else entirely. Later in this chapter, we'll see a
concrete example of configuring an asset this way in JBoss.

Not only does this two-level binding feature allow you to manage your namespace more
flexibly, but it can also make it possible to share assets among components and applications
running in the same server. Following on to the Session example we just used, suppose
this Session were configured with fairly generic settings and that other components also
needed a Session configured similarly. We can reuse the same Session asset with other
components by simply linking the names that these other components declare for the asset
with the same Session that is deployed at java:comp/mail/GenericSession.

2.1.2. JNDI Configuration Services

2.1.2. JNDI Configuration Services

Given all this, the configuration services provided by an application server are a critical
element in deploying J2EE applications. Various runtime assets required by your
components, such as database connections, JMS message queues, JCA resource adapters,
or even other J2EE components, will be provided by the application server at runtime.
These assets will be located at runtime using JNDI lookups, so it's critical that all of the
assets referenced in the component deployment descriptors are configured properly in the
JNDI namespace of the application server.

More complete details on JNDI and its use with general directory services can be found in
Chapter 9. Here, we'll discuss the naming conventions typically used for different resources
and components published in an application server's JNDI service and how names used
in module deployment descriptors are resolved against the real names of these resources
and components.

2.1.1. Assembling Applications

2.1.1. Assembling Applications

As discussed in the introduction to this chapter, we've intentionally made the distinction
between assembling and deploying applications because they really are two distinct stages
in getting a J2EE application up and running. Assembling an application involves getting
all of the elements of the application together in the right package structure and with the
right configuration information included. Deploying an application is the act of taking the
application assembly and plugging it into the application server environment so that it can
actually run.

The first step in assembling an application is to assemble the component modules that
make up the application. Once this is accomplished, you package up the component
modules into an application archive.
An application is fully assembled once all of its component modules have been pulled
together
into an application archive, as shown in Figure 2-2. In the example shown, the
application archive contains two component modules, a web module and an EJB module.

Each component module contains a deployment descriptor describing the components
themselves, how they should be managed by the container at runtime, and references to
any resources or other components that the module's components require in order to
operate correctly.

The application assembly itself also includes an application.xml deployment descriptor,
which references all of the modules that make up the application.
At this point, the application is assembled but not deployed. All of the resource references
in the component module descriptors are dangling, unresolved—we can't assign actual
resources to these references until we put the application into a physical server
environment.

It is possible to resolve some internal component references at this point, if
they reside in the same application assembly. For example, if one of the component
modules in Figure 2-2 references an EJB component and that EJB component is contained
in the other component module, we can specify that internal reference directly in the
deployment descriptor of the referring component. But for other resources, like JDBC
DataSources and JavaMail Sessions, we won't be able to connect the deployment
descriptor references to actual resources until we know the application server into which
we're deploying and how its resources are configured internally.

This separation of assembly and deployment of components and applications, using
deployment descriptors as the mediator between these two stages, helps you

Figure 2-2. Assembled application archive

to develop enterprise applications that migrate easily across environments. You may be
writing a shopping cart application, for example, with an EJB component that requires a
database connection in order to store and update order items. You might be developing
this application in a development environment using a MySQL database but need to run
it in a production environment using an Oracle database.

The database requirement can be specified clearly as a reference to a DataSource in the EJB deployment descriptor when the application is assembled. When the application is deployed to the development environment, the DataSource reference can be bound to a DataSource configured against the MySQL database. When the application is eventually deployed to production, the same application assembly can be used, but the resource reference will now be bound to a DataSource configured to connect to the production Oracle database.

2010년 8월 11일 수요일

2.1. J2EE Application Assembly Model

2.1. J2EE Application Assembly Model

First, let's get the J2EE terminology straight. Figure 2-1 depicts the assembly model for
J2EE applications. J2EE applications are composed of one or more components. A
component is a functional element of an application that runs within a container and
makes use of the runtime services provided by the container. These runtime services might
be security management services, transaction management services, lifecycle services, or
others, depending on the type of component and the type of container. A component
consists of one or more Java classes that implement the component, along with any
component-specific resources like properties files, images, and the like. J2EE components
(and their containers ) come in five flavors: application clients , applets , web, EJB, and
resource adapters .[*] Each type of container is capable of providing a specific set of APIs
and runtime services to its corresponding components.

It's important to note that most references on this subject distinguish resource adapters as a different category of "component" in the J2EE model: a lower-level
component that represents a resource to be used by the other, higher-order components, without a formal container model like the others. But for the sake of consistency
of the assembly and deployment model, they are included here among the other J2EE component types, since at a general level, they are handled much the same as
the other components.

J2EE components are grouped together and deployed in modules , which are collections
of components of the same type, to be run inside the corresponding container type. A
module contains all of the component-specific classes, plus any

Figure 2-1. J2EE assembly model (conceptual)


class libraries needed by the components and other cross-component resources, such as
datafiles, HTML documents (for web components), and image files. Each module also
contains a standard XMLdeployment descriptor that provides descriptive information,
external resource references, and configuration details about each component it contains.

If required, a module can also contain application server-specific details, such as
configuration files, classes, and resources that are required by a particular application
server. Most application servers, for example, allow you to specify additional configuration
parameters, not included in the standard J2EE deployment descriptors , in separate
configuration files. The application server vendor dictates the format for these files and
where they should be included in the module archive. Modules are packaged in the form
of jar files, with the deployment descriptor, classes, class libraries, and other resources
placed in specific locations in the jar file.

An enterprise application archive, or ear file, is a set of one or more modules, and these
modules collectively contain all of the components of an application. An application
archive also contains a deployment descriptor, which specifies the modules that it contains
and several other application-wide configuration details. Like components, application
archives are packaged into jar files with a particular layout, containing the deployment
descriptor for the application, the module jar files, and any other application resources,
such as documentation for the application.

In the remainder of this section, we'll talk about the general steps and concepts involved
in assembling and deploying J2EE applications. Following this, we'll discuss component
modules and application assemblies in more detail, using an example application as a
guide.

Updating CornCo with Enterprise JavaBeans

1.5.2. Updating CornCo with Enterprise JavaBeans

You may have noticed a flaw in the previous scenario. The checkout servlet sends billing
information to one server and then sends fulfillment information to another server. But it
performs these two actions independently, without any attempt to maintain transactional
integrity and make them behave atomically. In other words, if a network failure or server
crash were to occur after the billing information had been sent, but before the fulfillment
information had been sent, the customer might receive a bill for popcorn that was never
shipped.

The designers of the e-commerce system described in the previous section were aware of
this problem, but since distributed transactions are complex and CornCo does not own a
transaction management server, they simply chose to ignore it. In practice, the number of
customers who would have problems would be small, and it was easier for the original
programmers to let the customer service department sort out any irregularities.

But now, CornCo has hired a new vice president of information systems. She's tough as
nails and likes all her i's dotted and her t's crossed. She won't stand for this sloppy state of
affairs. As her first official act as VP, she buys a high-end J2EE application server and gives
her e-commerce team the job of revamping the online ordering system to use it. The
modified design might work like this:
• The customer interacts with the web server and the shopping cart servlet in the same
way as before.
• The checkout servlet is totally rewritten. Now it is merely a frontend for an Enterprise
JavaBeans component that handles the interactions with the ordering and fulfillment
servers and with the marketing database. The servlet uses JNDI to look up the remote
enterprise bean and then uses RMI to invoke methods on the bean (recall that all
enterprise beans are RMI remote objects).
• The major functionality of the checkout servlet is moved to a new checkout bean. The
bean stores customer data in the marketing database using JDBC, sends billing
information to the billing server using CORBA, looks up a warehouse using JNDI, and
sends shipping information to the warehouse using JMS. The bean doesn't explicitly
coordinate all these activities into a distributed transaction, however. Instead, when
the bean is deployed within the EJB container provided with the J2EE server, the
system administrator configures the EJB component so that the server automatically
wraps a distributed transaction around all of its actions. That is, when the
checkout() method of the bean is called, it always behaves as an atomic operation.
• In order for this automatic distributed transaction management to work, another
change is required in the conversion from checkout servlet to checkout bean. The
checkout servlet managed all its own connections to other enterprise services, but
enterprise beans don't typically do this. Instead, they rely on their server for
connection management. Thus, when the checkout bean wants to connect to the
marketing database or the enterprise messaging system, for example, it asks the EJB
server to establish that connection for it. The server doesn't need to know what the
bean does with the connection, but it does need to manage the connection if it is to
perform transaction management on the connection.

Enabling E-Commerce for a Mail-Order Enterprise

1.5.1. Enabling E-Commerce for a Mail-Order Enterprise
CornCo Inc. runs a successful catalog-based mail-order business selling fresh flavored
popcorn. They want to expand into the exciting world of online sales. Here's how they
might do it

1. A customer visits the company's web site, http://www.cornco.com, and uses a web
browser to interact with the company's web server. This allows the customer to view
the company's products and make selections to purchase.
2. Before accessing protected or personalized sections of the web site, the customer must
log in (authenticate) to identify himself to the system. Once logged in, he is authorized
to use customer-related functions of the site and view his own data (and no one else's).
3. The web server uses a shopping cart servlet to keep track of the products the customer
has chosen to buy. The HTTP protocol is itself stateless, but servlets can persist
between client requests, so this shopping cart servlet can remember the customer's
selections even while the customer continues to browse the web site.
4. When the customer is done browsing and is ready to purchase the selected products,
the web server invokes a different checkout servlet. This servlet performs a number
of important tasks, using several Java Enterprise APIs.
5. The checkout servlet uses JDBC to retrieve the list of products to be purchased (stored
in a database by the shopping cart servlet).
6. Next, the servlet queries the customer for a shipping address, a billing address, and
other required information and then uses JDBC again to store this information in a
customer database. This database can be used, for example, by the CornCo marketing
department for direct mail purposes.
7. The servlet then sends the customer's billing address and total purchase price to the
billing server. This server is a legacy application, specific to CornCo, that has a
nonstandard interface. Fortunately, however, the billing server exports itself as a
CORBA object, so the servlet can treat the entire server as a CORBA remote object
and invoke the necessary methods on it.
8. In order to ensure the very freshest product, CornCo maintains warehouses
throughout the world. CornCo is a growing company, so the list of warehouses is
frequently updated. The checkout servlet uses JNDI to contact a directory server and
then uses the directory server to find a warehouse that is close to the customer and
has the customer's requested products in stock.
9. Having located a warehouse that can fulfill the customer's order, the checkout servlet
uses JMS to contact the company's enterprise messaging service. It uses this service
to send the customer's order to the selected warehouse in the form of a message. This
message is delivered to and queued up on the local computer at the warehouse.
1.5. An Enterprise Computing Scenario

The previous sections have been rapid-fire introductions to the Java Enterprise APIs that
are part of the J2EE framework as well as a set of key de facto standard tools used
commonly in the Java Enterprise space. Don't worry if you didn't understand all the
information presented there: the rest of the chapters in the following two parts of the book
cover the APIs in more detail. The important message you should take from this chapter
is that the Java Enterprise APIs are building blocks that work together to enable you to
write distributed Java applications for enterprise computing. The computing
infrastructure of every enterprise is unique, and the Java Enterprise APIs can be combined
in any number of ways to meet the specific needs and goals of a particular enterprise.
Figure 1-1 shows a schematic for a hypothetical enterprise. It illustrates some of the many
possible interconnections among distributed services and shows some of the Java
Enterprise APIs that facilitate those interconnections. The figure is followed by example
scenarios that demonstrate how the Java Enterprise APIs might be used to solve typical
enterprise computing problems. You may find it useful to refer to Figure 1-1 while reading
through the scenarios, but note that the figure doesn't illustrate the specific scenarios
presented here.

Figure 1-1. The distributed computing architecture of a hypothetical enterprise

2010년 8월 10일 화요일

Struts

1.4.3. Struts: Implementing Model-View-Controller Systems

The MVC paradigm for architecting UI-oriented applications was introduced more than
20 years ago in the Smalltalk environment. Since then, it's become a popular and effective
pattern for designing and managing web applications, and many tools have been created
to support it.

In the MVC pattern, the model represents the data and business logic at the heart of the
application, views represent interactive user interface elements, and the controller links
the views to the model and keeps the application flow moving. In an MVC-based
application, users interact with one or more views in the user interface. Their actions are
passed to the controller, which is responsible for handling them. Based on the user's
actions, the controller can make changes to the application model, generate new views for
the user, or all of the above. Changes in the application model can also generate
notifications directly to views, causing them to change appearance in key ways or adjust
their behavior, based on the new state of the model.
Java servlets and JavaServer Pages provide the essential tools for building web interfaces
in Java, using an object-oriented programming model or a "scripted" web page model,
respectively. Struts is an Apache project built on top of both of these standard Java
technologies, using servlets to implement the controller, both JSPs and servlets to
implement views, and standard Java technologies (such as Java beans and EJBs) to
implement the application model. Struts further facilitates MVC development by providing
a configuration scheme for specifying the page flow of the application based on user actions
and an API for defining action handlers and other key MVC elements.

It's important to point out that the introduction of the JavaServer Faces standard provides
many of the same elements that the Struts project covers. Put another way, Struts was
created to fill a perceived gap between the Java standards at the time and the needs of
enterprise developers. Since then, JavaServer Faces was defined to fill a part of that same
gap. JSF was released in specification form in March 2004, and implementations are now
readily available. The relationship that Struts will have in the future with Java servlets,
JSPs, and JSF still remains to be seen, but in the meantime, Struts remains a popular and
effective tool for MVC development.

A tutorial on Struts is provided in Chapter 19. Because of the functional overlap between
JSF and Struts, the code examples in the two chapters parallel each other and have identical
user interfaces. As a result, you can compare and contrast the implementations to help you
decide which solution is right for your application.

JUnit and Cactus

1.4.2. JUnit and Cactus: Testing Your Objects, Components, and Applications
In any application development context, the practice of testing your code is a critical
success factor. Testing enterprise applications involves a number of different dimensions.
The user experience and the proper behavior of views (in the model-view-controller, or
MVC, sense) can be tested using functional testing tools; the correct behavior of software
at the code level, in terms of objects and components performing as expected, can be tested
using unit testing tools; the throughput and overall behavior of a system when under heavy
load (large numbers of users or transactions or both) can be tested using performance
testing tools.

JUnit is an open source unit testing framework for Java. It is one in a series of such tools,
built for a number of development environments using the same conceptual architecture.
Other tools in this suite include PerlUnit for Perl and CppUnit for C++. JUnit includes a
Java API that provides interfaces and base classes for defining and running unit tests as
well as some tools that facilitate the configuration, running, and reporting of unit test
suites. JUnit is used by developers to write suites of unit tests that exercise their code in
critical ways and that verify the results to ensure that they are correct, according to the
documented behavior of the code under test. These unit tests are themselves Java code,
making it easy to use the same code management tools to manage tests for code along with
the code itself.

Enterprise developers face unique challenges when unit testing their Java objects and
components. The proper behavior of enterprise code can be tested only if a suitable
simulation of its runtime environment can be achieved. A web component like a JSP tag
handler, for example, can be tested only if the testing framework can operate within a web
container, can issue simulated handle requests to the tag handler, and can interpret the
responses that are generated to assess whether the test succeeded or not.
To facilitate the task of enterprise unit testing, the good people at Apache extended JUnit
with a framework called Cactus. Cactus allows J2EE developers to write unit tests for full
enterprise components, like servlets and EJBs.

Chapter 18 provides an introduction to the basic JUnit testing framework and also gives
a tutorial on using Cactus to define and execute test suites for enterprise components.

Ant: Building and Deploying Applications

1.4.1. Ant: Building and Deploying Applications

Ant is used to manage the process of building and deploying code, among other things.
Ant is similar in purpose to age-old tools like make, gmake, and imake. It provides a way
to codify the parameters needed to build your code (like dependent libraries, configuration
files, and the like) and to define various tasks that can be done with the code (compile it,
generate Javadoc pages from it, assemble it into a J2EE application archive, deploy it to
an application server, and run unit tests on it, among other things).

Ant is an open source project managed by the Apache Software Foundation. It "ships" with
a large set of core tasks that can be used to compose Ant "build scripts," which are written
in XML. An Ant build script consists of a set of targets that you define. Each target consists
of a set of tasks that are executed when that target is requested by the user or invoked by
another target. These tasks can be core tasks included with Ant (like "compile this set of
Java code" or "copy these files to that directory"), they can be custom tasks that you define,
or they can be tasks that are imported from a third-party library. Many J2EE application
servers and tools (including many of the open source tools discussed in this book) now
include their own Ant tasks, to allow you to easily integrate them into your project Ant
scripts.

Many Ant tasks and practices have been defined to help develop and manage large
enterprise projects in the Java environment. Chapter 17 provides both an overview tutorial
of Ant in general and some details on Ant-related utilities that are particularly useful when
developing J2EE applications. The chapter also includes some best practices in terms of
designing Ant build processes for multiple developers and multiple environments.

JavaMail: Email-based messaging

1.3.5.2. JavaMail: Email-based messaging

Email is another critical communication protocol for enterprise systems. Email is a
widespread tool used for interpersonal messaging in a wide variety of contexts, from
corporate communications to family reunion planning, as anyone reading this book is
surely aware. In an enterprise application context, email can also be an important tool for
end user event notifications (for example, a notice that a lower-priced flight has matched
your travel profile), for content delivery (e.g., a weekly "ezine" delivered automatically from
a content management system), and for system monitoring (e.g., a notice to a system
administrator that connectivity to a critical information system has been lost).

J2EE's tool for composing, sending, and receiving email is the JavaMail API, contained in
the javax.mail package. For dealing with various types of content in MIME-based email
messages, a companion API called the JavaBeans Activation Framework and provided in
the javax.activation package is used in conjunction with JavaMail ("activation" in
the name refers to activating a content handler to deal with a particular type of content).
Chapter 15 is a tutorial on the use of these APIs.

Java Message Service (JMS): General enterprise messaging

1.3.5.1. Java Message Service (JMS): General enterprise messaging

JMS (JSR 914) is the Java Enterprise API for working with networked messaging services
and for writing message-oriented middleware (fondly referred to as MOM).
The word "message" means different things in different contexts. In the context of JMS, a
message is a chunk of data that is sent from one system to another in an asynchronous
manner. The data serves as a kind of event notification and is almost always intended to
be read by a computer program, not by a human. In a nondistributed system that uses the
standard Java event model, an Event object notifies the program that some important
event (such as the user clicking a mouse button) has occurred. In a distributed system, a
message serves a similar purpose: it notifies some part of the distributed system that an
interesting event has occurred. You can think of a networked message service as a
distributed event notification system.

JMS is also a good complement to the synchronous communication provided by RMI,
CORBA, and most web services built using JAX-RPC. When an RMI client, for example,
makes a remote method call on a server object, the client will block until the remote method
returns. JMS provides a way for you to communicate asynchronously with a remote
process: you can send your message and carry on with useful work while the message is
delivered and processed at the receiving end. If there's a response from the receiver(s), a
callback can be invoked on your end, and you can deal with it then.

Like JNDI and JDBC, JMS is an API layered on top of existing, vendor-specific messaging
services. In order to use JMS in your application, you need to obtain a JMS provider
implementation that supports your particular message server. Some J2EE application
servers bundle their own JMS providers that you can use as message servers; some of them
provide easy ways to bridge their application servers to other message services like IBM
MQSeries or SonicMQ; others provide neither and leave it to you to obtain and install a
JMS provider.

Chapter 11 provides a tutorial on using JMS, and Appendix E documents the syntax for
JMS message selectors.

Enterprise JavaBeans: Distributed business components

1.3.4.4. Enterprise JavaBeans: Distributed business components

Enterprise JavaBeans (EJB ) do for server-side enterprise programs what Java beans do
for client-side GUIs. EJB is a component model for units of business logic and business
data. Programming models that take business logic out of the client and put it on a server
or in a middle tier have many advantages in enterprise applications. However, the task of
writing this middleware has always been complicated by the fact that business logic must
be mixed in with code for handling transactions, security, networking, and so on.

The EJB model attempts to separate high-level business logic from low-level housekeeping
chores. And in the process, it attempts to leave the former to you, the enterprise developer,
while the latter is delegated to the EJB server. A component in the EJB model is an object
that implements business logic or represents business data. The difference between an
enterprise bean and a run-of-the-mill RMI remote object or nonremote Java bean is that
EJB components run within an EJB container, which in turn runs within an EJB server.

The container and server provide features such as transaction management, resource
pooling, lifecycle management, security, name services, distribution services, and so on.
With all these services provided by the container and server, enterprise beans (and
enterprise bean programmers) are free to focus purely on business logic.

The EJB specification is a document that specifies the contracts to be maintained and
conventions to be followed by EJB servers, containers, and beans. Writing EJB
components is straightforward: simply write code to implement your business logic, taking
care to follow the rules and conventions imposed by the EJB model.

EJB components can also run within the larger J2EE framework. In addition to the
standalone EJB component services, EJBs running within a J2EE server can be assembled
with other components (like web components) into J2EE applications.
Unlike some of the other Java Enterprise APIs, the EJB API is just the beginning of
understanding how EJB works. The key to understanding Enterprise JavaBeans lies in the
interactions among beans, containers, and the EJB server. These interactions are
described in detail in Chapter 6. In addition, the syntax for the abstract persistence
language used in entity EJBs, EJB QL, is described in Appendix C.
Java Enterprise in a Nutshell, 3rd Edition Page 21 Return to Table of Contents

Java IDL: Using and writing CORBA remote objects

1.3.4.3. Java IDL: Using and writing CORBA remote objects

As we've just discussed, RMI is a distributed object solution that works especially well
when both client and server are written in Java. It is more work, and therefore less
attractive, in heterogeneous environments in which clients and servers may be written in
arbitrary languages. For environments like these, the Java platform includes a CORBA based
solution for remote method invocation on distributed objects.

CORBA (Common Object Request Broker Architecture) is a widely used standard defined
by the Object Management Group (OMG). The Java binding of this standard is
implemented as a core part of the Java platform in the org.omg.CORBA package and its
subpackages. The implementation includes a simple Object Request Broker (ORB) that a
Java application can use to communicate (as both a client and a server) with other ORBs,
and thus with other CORBA objects.

The interfaces to remote CORBA objects are described in a platform- and language independent
way with the Interface Definition Language (IDL). Sun provides an IDL compiler that translates an IDL declaration of a remote interface into the Java stub classes needed for implementing the IDL interface in Java or for connecting as a client to a remote implementation of the interface from your Java code.

A number of Java implementations of the CORBA standard are available from various
vendors. This book documents Sun's implementation, known as Java IDL. It is covered in
detail in Chapter 14. The syntax of the IDL language itself is summarized in Appendix G,
and the CORBA-related tools provided with Sun's JVM are described in Appendix H.

Java RMI: Java-to-Java remote objects

1.3.4.2. Java RMI: Java-to-Java remote objects

Remote method invocation (RMI) is a programming model that provides a high-level,
generic approach to distributed computing. RMI extends the Java object-oriented
programming paradigm to distributed client/server programming: it allows a client to
communicate with a server by invoking methods on remote objects that reside on the
server. RMI is implemented in the java.rmi package and its subpackages, which were
introduced in Java 1.1 and were enhanced in later versions of the Java platform.

The Java RMI implementation is full-featured but still simple and easy to use. It gains
much of its simplicity by requiring both client and server to be implemented in Java. This
requirement ensures that both client and server share a common set of data types and have
access to the object serialization and deserialization features of the java.io package, for
example. On the other hand, this means that it is more difficult to use RMI with distributed
objects written in languages other than Java, such as objects that exist on legacy servers.

The default remote method communication protocol used by RMI will allow only Java
code to interact with RMI objects. But you can also opt to use RMI/IIOP, which was made
a standard part of the core Java APIs in Version 1.3 of the Java platform. RMI/IIOP is an
optional communication protocol that allows RMI objects to interact with CORBA-based
remote objects. Since CORBA objects can be implemented in many languages, this
provides a bridge to systems implemented in other languages.

The java.rmi package makes it easy to create networked, object-oriented programs.
Programmers who have spent time writing networked applications using lower-level
protocols are usually amazed by the power of RMI. See Chapter 13 for a tutorial on using
RMI.

JAX-RPC and SAAJ

1.3.4.1. JAX-RPC and SAAJ: Using and writing web services

Web services have created quite a stir in the enterprise development domain by promising
a new idiom for writing and using distributed services. Web services refer to services that
are callable using an XML-based protocol and transmitted over HTTP, SMTP, and other
communication protocols. Web services are exciting because, like CORBA, they provide a
platform-independent approach to distributed computing; since they depend on
ubiquitous formats and protocols (such as XML and HTTP), the endpoints in web service
architectures can be implemented in any platform or language that supports these
protocols. In other words, web services can be produced and consumed by nearly all
modern programming languages and on all platforms.
But web services have some additional advantages that RMI and CORBA do not. Since the
overall distributed computing architecture is generic and extensible, web services provide
much more flexibility in terms of the physical implementation of the web services and their
surrounding runtime support. A web service engine can be a full-blown application server
with failover and load-balancing or a tiny runtime process on a handheld device.
Programming models, APIs, object models, and the like are left up to the implementation
platform, allowing them to be optimized for the particular environment.

The fundamental standard protocols used in web services today are SOAP (Simple Object
Access Protocol) for interprocess communications and WSDL (Web Services Descriptor
Language) for describing web services. In the Java community, a suite of standard Java
APIs have been defined to help developers build and use web services. We discuss the two
most important ones in this book: the Java API for XML Remote Procedure Calls (JAXRPC)
(JSR 101, JSR 224) and the SOAP with Attachments API for Java (SAAJ).

SAAJ defines a standard API for basic, low-level messaging using SOAP. On top of this, JAXRPC
provides a standard API for interacting with web services using a remote method
invocation paradigm in which a request to a web service is expected to result in an
immediate response. Both of these APIs are covered in the web services tutorial in Chapter
12.Java Enterprise in a Nutshell, 3rd Edition Page 19 Return to Table of Contents

Java Transaction API (JTA):

Accessing transactional resources The JTA, or Java Transaction API, is a Java Enterprise API for managing distributed transactions. Distributed transactions are one of the things that make distributed systems more complicated than nondistributed programs.

To understand distributed transactions,you must first understand simple, nondistributed transactions.
A transaction is a group of several operations that must behave atomically, as if they
constitute a single, indivisible operation. Consider a banking application that allows a user
to transfer money from a checking account to a savings account. If the two account balances
are stored in a database, the application must perform two database updates to handle a
transfer—it must subtract money from the checking account and add money to the savings
account. These two operations must behave atomically. To see why, imagine what would
happen if the database server crashed after money had been subtracted from the checking
account but before it had been added to the savings account. The customer would lose
money!
The JTA defines a Java binding for the standard XA API for distributed transactions (XA
is a standard defined by the Open Group). Using the JTA, we can write a program that
communicates with a distributed transaction service and uses that service to coordinate a
distributed transaction that involves, for example, a transfer of money between database
records in two different databases.
Chapter 16 provides a brief general tutorial on the JTA. Since EJBs and EJB containers
provide direct support for distributed transactions using JTA, there is also brief coverage
of the API (as it relates to EJB) in Chapter 6. JDBC drivers can also optionally support
Java Enterprise in a Nutshell, 3rd Edition Page 18 Return to Table of Contents
JTA-enabled distributed transactions, so JTA (as it relates to JDBC) is also briefly
mentioned in Chapter 8.

Java Naming and Directory Interface (JNDI)

1.3.3.2. Java Naming and Directory Interface (JNDI)

Working with directory services JNDI is the Java Enterprise API for working with networked naming and directory services. It allows Java programs to use name servers and directory servers to look up objects or data by name and search for objects or data according to a set of specified attribute values.
JNDI is implemented in the javax.naming package and its subpackages as a core API in the Java platform.

The JNDI API is not specific to any particular name or directory server protocol. Instead,
it is a generic API that is general enough to work with any name or directory server. To
support a particular protocol, plug a service provider for that protocol into a JNDI
installation. Service providers have been implemented for the most common protocols,
such as LDAP, Active Directory, and Novell's NDS. Service providers have also been written
to interact with the RMI and CORBA object registries.

JNDI also plays a key role in the J2EE framework since it is the API used to access runtime
configuration information and resources by J2EE applications. Information specified in
component deployment descriptors is made available to components by the application
server through an internal name server, and the application components access this name
server through JNDI.
JNDI is covered in detail in Chapter 9.

JDBC: Working with relational databases

1.3.3.1. JDBC: Working with relational databases

JDBC (JSR 054) is the Java API for working with relational database systems. JDBC allows
a Java program to send SQL query and update statements to a database server and to
retrieve and iterate through query results returned by the server. JDBC also allows you to
get metadata about the database and its tables from the database server.

The JDBC API is independent of vendor-specific APIs defined by particular database
systems. The JDBC architecture relies upon a Driver class that hides the details of
communicating with a database server. Each database server product requires a custom
Driver implementation to allow Java programs to communicate with it. Major database
vendors have made JDBC drivers available for their products. In addition, a "bridge" driver
exists to enable Java programs to communicate with databases through existing ODBC
drivers.

The JDBC API is found in the java.sql package, which was first introduced in Java 1.1.
Java 1.2 updated the core APIs to include JDBC 2.0, which added a number of new classes
to support advanced database features. JDBC 2.0 also provides additional features in the
javax.sql standard extension package. JDBC includes classes for extracting data from
databases in the form of Java objects, for pooling database connections, and for obtaining
database connection information from a JNDI name service. The extension package also
supports scrollable result sets, batch updates, and the storage of Java objects in databases.

The latest versions of the J2SE, 1.4 and 5.0, include the JDBC 3.0 API, whose specification
was released in February 2002. This version of JDBC adds support for transaction
"savepoints," allowing you to programmatically roll back database transactions to multiple
checkpoints, as well as some enhancements to connection pooling support. At this writing,
however, driver support for JDBC 3.0 is still somewhat limited, and in several cases you
may have only JDBC 2.x API support in your drivers.

The JDBC API is simple and well designed. Programmers who are familiar with SQL and
database programming in general should find working with databases in Java very easy.
See Chapter 8 for a tutorial on JDBC and Appendix D for a quick reference to SQL.

Google's Java chief subtly calls for detente with Oracle on Android?

Google's Java chief subtly calls for detente with Oracle on Android?


Much hand-wringing from Google's chief Java architect Josh Bloch spent a good chunk of a speech at Red Hat's Middleware 2020 conference wailing about Java's last few years drifting along. It's a speech that made quite a splash, for obvious reasons, and contains many familiar gripes about the platform: new releases are taking too long to come out; the JCP's future is murky. Yet the two complaints he spent the most time dwelling on have something interesting in common. The first is the raft of disputes surrounding Sun's licensing conditions, with the Apache Harmony implementation being the example he cited; the second is the stagnation of Java ME, which hasn't kept up with the hardware capabilities of mobile devices.

Both of those points, of course, are directly related to Android, Google's own OS for mobile devices, which, despite being unable to officially call itself Java because of the aforementioned licensing disputes, is ultimately based on Harmony and on Java SE. Block ended his speech by praising Oracle's past moves on openness and licensing, and urging Java's new master to show leadership on the platform.

My crazy theory about all this is that Google would like to come to some sort of accommodation with Oracle on Android. Surely Google will want to still be in charge of the platform, but if some of Android's innovations could be rolled back into the official Java codebase, that could only broaden the Android developer base.

In a possibly related matter, Daring Fireball's John Gruber predicts that James Gosling would ultimately land at Google, which would be a very interesting scenario indeed.

Web UIs and Components

1.3.2. Web UIs and Components

The J2EE framework supports web interfaces with the concept of web components. These
components run within application servers and take advantage of several runtime services
provided by these servers, including user session management, security services like
authentication and encrypted communications, and so on. Web components are also able
to access other J2EE resources and components, such as Java Database Connectivity
(JDBC) DataSources and local and remote EJB components.
J2EE supports the development of web components and web UIs with a family of three
standards: Java servlets , JavaServer Pages (JSPs) and, more recently, JavaServer Faces
(JSF). Each of these supports different programming models and runtime models, and
each is important in different ways and in different contexts. Struts, a nonstandard but
popular web interface technology, is described in a later section.


1.3.2.1. Java servlets: Basic web-enabled components

A servlet is a Java object that runs within a server to provide a service to a client. The name
"servlet" was originally meant to be a takeoff on "applet"—a servlet can be thought of,
roughly, as a server-side applet. The Java Servlet API (JSR 053 and JSR 154) provides a
generic mechanism for extending the functionality of any kind of server that uses a protocol
based on requests and responses.

For the most part, servlets are used behind web servers for dynamic generation of HTML
content. But more generally, a servlet is a Java object that can receive HTTP requests and
provide HTTP responses. The most typical scenario is a web browser that issues a request
to a web server and a Java servlet that receives the request, performs some operations
(perhaps JDBC calls to retrieve information or a call to an EJB component to invoke some
business logic), and sends an HTML response back to the browser. But servlets can also
serve in other ways in an enterprise application. A remote application can issue an HTTP
request to a servlet, and the servlet can respond with an XML document in response, for
example.
A key advantage of servlets over some other similar technologies, such as Microsoft Active
Server Pages, is that servlets are portable among operating systems and among application
servers. The advantage of servlets over some script-based web technologies, like Perl CGIs,
is that servlets are also compiled objects that are persistent between invocations, which
gives them major performance benefits over parsed scripts. Servlets also have full access
to the rest of the Java platform, so features such as database access are automatically
supported.

The Servlet API is a standard extension to the Java platform and is part of the J2EE
specifications. The API is implemented in the javax.servlet and
javax.servlet.http packages. The javax.servlet package defines classes that
represent generic client requests and server responses, while the
javax.servlet.http package provides specific support for the HTTP protocol,
including classes for tracking multiple client requests that are all part of a single client
session.

1.3.2.2. JavaServer Pages (JSPs): Dynamic web pages

JavaServer Pages (JSPs) (JSR 053 and JSR 152) are also part of the J2EE specifications
family and closely related to Java servlets. You can think of JSPs as an alternative approach
to creating servlets, in one sense. JSPs are similar to alternative technologies such as PHP
and Microsoft Active Server Pages—they all provide a way to insert dynamic elements
directly into HTML pages.

In the case of JSPs, these dynamic elements invoke Java code using references and calls to Java beans, using custom tags that act as dynamic macros that are implemented by Java beans, or using raw Java code snippets. Chapter 4 provides details on writing JSPs. In addition, this chapter provides some details on using the Java Standard Tag Library (JSTL), a standard set of handy JSP tags that can be used in any compliant JSP engine.

1.3.2.3. JavaServer Faces (JSF): Web UI components

JavaServer Faces (JSR 127) is a recently released Java standard for user interface (UI)
components. JSF builds on the foundation provided by Java servlets and JSPs, providing
a UI component model based on JSP tags.

This UI component model allows you to create UIs for your application from a set of predefined components (similar to the role that Java Swing plays in the world of desktop GUIs). The JSF model also includes state management and page navigation facilities that help in the development of applications using customary design patterns like model-view-controller (MVC).
See Chapter 5 for a short tutorial on JSF, its tag libraries, and application configuration
schemes.

2010년 8월 9일 월요일

J2EE Basic Tool

1.3.1.1. Java API for XML Processing (JAXP)

XML is not strictly an enterprise-focused tool. XML is useful in all kinds of contexts,
enterprise and otherwise. We've included it in this book, however, because XML is now
such a fundamental, all-purpose tool that it touches nearly every level of enterprise
application development, from basic datafile formats to interprocess communications to
user interface representations.

The Java API for XML Processing (JAXP) (defined in JSR 005)[*] is the standard API for
consuming and producing XML in Java. Application servers compliant with J2EE 1.3 and
later must include a compliant JAXP implementation. JAXP provides a pluggable API that
supports both SAX and DOM parsing of XML content, as well as XSLT-based
transformations of XML. JAXP 1.2, the version specified in the J2EE 1.4 specification,
supports the SAX 2 and DOM 2 parsing APIs, as well as the XSLT 1.0 transform API. JAXP
is covered briefly in Chapter 7. The JAXP APIs are also covered in Java in a Nutshell by
David Flanagan (O'Reilly).

1.3.1.2. J2EE security

Security is of paramount importance in enterprises today and is entrenched in many
aspects of application development and deployment. In fact, security is a concern that must
be considered in all aspects of the modern enterprise, well beyond the J2EE security APIs
discussed in this book.

The J2EE security chapter (Chapter 10) provides a brief overview of fundamental security
concepts such as authentication and authorization. Authentication refers to the process of
a user identifying himself to an application, typically using a username and password.
Authorization refers to granting the authenticated user access to the resources within the
application, as appropriate to that user.

Enterprise Computing Defined

1.1. Enterprise Computing Defined

The term "enterprise computing" raises many different images in people's minds: big,
sterile-looking corporate data centers filled with humming servers ; complex financial
systems stretching across the globe; elaborate multilevel software systems running a
stupefying amount of code distributed across many servers, locations, companies,
countries, even (in the case of NASA's Mars Rover project) planets.

All of these images are true, to a degree. But they're all imprecise to a degree as well.
Enterprise computing can be done on a single student's laptop as well as in a big corporate
data center. It can be used in a small mom and pop business with a single storefront as
well as in a huge multinational. It can be done just as effectively with a very small amount
of code as it can with huge code repositories.

At its heart, enterprise computing is all about combining separate applications, services,
and processes into a unified system that is greater than the sum of its parts. The rest is
context that determines how you go about accomplishing this basic goal.

Anyone can write enterprise applications, not only because of the generalized nature of
enterprise computing but also because the tools and techniques for developing enterprise
systems have matured to the point that this domain is accessible to a much broader group
of software developers. Many of the arcane details have been smoothed over by standards,
well-defined APIs, and really powerful tools. This has made enterprise computing less
scary and a lot more fun.