Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Java.JDK.5.Edition (Wrox)

.pdf
Скачиваний:
31
Добавлен:
29.02.2016
Размер:
12.07 Mб
Скачать

Chapter 14

Though this scenario may seem like it solves the problem, it just ends up creating new deployment problems. First, application A has no dependency on application B, but the opposite is not true. If application A were to fail or be brought down for maintenance, then application B would also be down. Second, you have to create some way of adding the stub code to application B that is necessary to utilize the EJBs in application A. This is not addressed by the J2EE specification.

Another option is to package all these components into the same EAR file, effectively combining multiple applications into a single file. Of course, this approach has problems, too. In the real world, two different applications will have different deployment and uptime requirements. One application might have to always be available to its users, but the other one might have different memory requirements or only need to be up during the night. This makes packaging both applications within the same EAR file a poor choice due to the disparate requirements.

Another significant problem whenever there is a shared component between two or more applications is version incompatibility. Because the shared component usually has a single owning entity, classes inside the shared component might change method signatures, and this may break other applications that weren’t expecting the method to change.

So, any route you choose seems to have its own set of problems. There is one other deployment scenario. You can take the shared component and place it inside each application’s EAR file. This makes one EAR file totally separate from another. This still presents a deployment problem though. What happens when the API changes but the component used by all EARs is only updated in one EAR? This scenario makes it easy for different EAR files to all have different versions of this common component.

The basic approach you should take when deciding how to package your various enterprise applications and shared components is to consider each deployment scenario and pick the one that will (hopefully) cause the fewest nightmares for you in the future. Consult the following table for a summary of these deployment scenarios and rough guidelines as to when to use each one.

Scenario

When to Use

 

 

Shared component external to EARs

— Applications have different runtime

 

requirements.

 

— API of shared component is not expected

 

to change, or it is easy to update all applica-

 

tions that use the shared API.

Shared component packaged in a single EAR

— Applications have compatible uptime

 

requirements and system requirements.

 

— API of shared component is not expected

 

to change, or it is easy to update all applica-

 

tions that use the shared API.

Placing shared component in each EAR

— Each EAR is on a different system, and

 

the systems cannot communicate with each

 

other.

 

— The shared component is expected to stay

 

relatively the same over time, or updating

 

each EAR with a new version is easy.

 

 

646

Packaging and Deploying Your Java Applications

Jumping into Java Web Star t

Web-based solutions have become the standard for delivering client/server applications even though Web browsers were never intended to be used to deliver anything other than static content. Developers continue to stretch the bounds of Web technologies in search of the best solution. Applets appeared to be the answer because they delivered such a strong feature set and were able to be embedded in a Javasupporting Web browser. Applets still require a significant amount of download time and are still not as rich as a thick client is. Sun is again proving to be very innovative and removing the limitations of browser-based technology by introducing a solid, rich client technology called Java Web Start. Java Web Start is based on the Java Network Launch Protocol (JNLP) and the Java 2 platform. Java Web Start was introduced as a standard component in Java 1.4. Because of Java Web Start’s unique architecture, it only takes one click to download the application you wish to launch from a Web browser. The link that you click is the JNLP file that tells Java to launch Web Start and download the application.

This section will teach you how to package and deploy a Java Web Start application through an example of an all-time favorite game, tic-tac-toe.

Examining the TicTacToe Example

This example goes into detail on how to create, package, deploy, and launch a Java Web Start application. The game is not exceptionally smart and could be enhanced by adding an artificial intelligence (AI) capability. An AI would have been overkill for the purpose of this demonstration. The following table is a list of files that make up the TicTacToe example.

File

Description

 

 

tictactoe.jnlp

This is the Java Network Launch Protocol file that contains all the specific

 

attributes to tell Java Web Start how to launch the application. It is also the file

 

that the user clicks on to execute the application.

ttt.htm

This HTML file contains a link to the tictactoe.jnlp file used to launch the

 

application.

TTTMain.java

This is the source file with the main method in it that drives the application.

TTTGui.java

This file contains all the Swing code necessary to handle the user interaction

 

with the game.

TTTLogic.java

This file contains all the game logic and is used to determine who wins, whose

 

move it is, and what positions are open on the board. This is the perfect spot

 

to add an artificial intelligence capability.

tictactoe.jar

This is the signed JAR file that contains the compiled code and will be

 

launched by Java Web Start.

 

 

The tictactoe.jar file, the ttt.htm file, and the tictactoe.jnlp must all be deployed to a Web server so that the user can download the application. When the user clicks the link that is in the ttt.htm file, the following window is displayed to the user (see Figure 14-6).

647

Chapter 14

TIC TAC TOE

TTT Team

Powered by Java (tm) Web Start

Figure 14-6

This window is displayed until the application is downloaded. Once it is downloaded, the application is launched, and the user can begin using it. If there is no specific code to tie the application to network use, the user can also use the application offline! Try that with an applet! The TicTacToe application shown in Figure 14-7 appears as any normal thick client would.

Figure 14-7

This is what makes Java Web Start so powerful and the technology of the future. It is just now starting to catch on in the world of distributed computing and is proving to have all the security features required to be a strong enterprise solution to complicated applications that require heavy client-side processing. Also, by moving the processing to the client, you eliminate the load on the server.

Examing the TicTacToe.JNLP

Before you actually create and deploy the JNLP file, you do have to make sure that whatever Web server you are using is configured to properly handle the JNLP mime type. To do this, simply add an entry in your deployment descriptor for the JNLP extension. In Tomcat, you can do this in the WEBINF/web.xml file with the following XML entry:

<mime-mapping> <extension>jnlp</extension>

<mime-type>application/x-java-jnlp-file</mime-type> </mime-mapping>

648

Packaging and Deploying Your Java Applications

Now that you are sure the Web server can handle the JNLP extension, you can create the JNLP file:

<?xml version=”1.0” encoding=”utf-8”?> <jnlp

spec=”1.0+”

codebase=”http://localhost/ttt”

href=”tictactoe.jnlp”>

The <spec> attribute is used to denote the JNLP specification version. The next attribute, <codebase>, is used as a base directory to locate resources on the Web server. The final attribute, href, is used to point to the JNLP file:

<information>

<title>TIC TAC TOE</title> <vendor>TTT Team</vendor>

<homepage href=”http://localhost/ttt/ttt.htm”/>

<description>TICTACTOE GAME</description>

<description kind=”short”>

A demo of the capabilities of JAVA WebStart. </description>

<offline-allowed/> </information>

The <information> element supplies Java Web Start with general information about the application. It has a <title> attribute to signify the title of the application. It also has a <vendor> attribute to denote the company, organization, or supplier of the application. There is also a <homepage> attribute that is used to tell the person where to go to get more information on the application. The <description> attribute is used to give the application a description. There is also a short <description> attribute if you need to supply one; finally, there is the <offline-allowed> attribute that signifies the application can be used offline. If this attribute is not supplied, the application cannot be launched without being first connected to the network:

<security> <all-permissions/>

</security>

<resources>

<j2se version=”1.5”/>

<jar href=”tictactoe.jar”/> </resources>

<application-desc main-class=”com.wrox.TTTMain”/> </jnlp>

649

Chapter 14

The security of a Java Web Start application is the same as that of an applet. It is very restrictive unless instructed otherwise. You are specifying an <all-permissions/> attribute that gives the application full access to the client’s machine. The <resources> element defines attributes that are needed in order to run properly. The <j2se> attribute signifies which Java platform to run the application on. The <jar> attribute tells Java Web Start which classes are required to run the application. Keep in mind that there can be multiple <jar> tags depending on your needs. The final element is the <application-desc> element that is instructing Java Web Start to run the com.wrox.TTTMain class. The importance of the <application-desc> tag is to let Java Web Start know that it is to run an application and not an applet:

<html>

<head>

<meta http-equiv=”Content-Language” content=”en-us”>

<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252”>

<title>TIC TAC TOE GAME!</title> </head>

<body topmargin=”0” leftmargin=”0” link=”#000080” vlink=”#000080”>

<center><A HREF=”tictactoe.jnlp”>Click Here to Launch TICTACTOE Game</A></center>

</body>

</html>

The ttt.htm file is shown in the previous example and is illustrated to teach you how to set up an HTML file to launch a Java Web Start application. As you can see, all that is required is to have the HREF tag point to the JNLP file.

TTTMain.java

The TTTMain class is the simple driver class for the application. Java Web Start calls this class to launch the application:

public class TTTMain {

public static void main(String[] args) { TTTLogic tLogic = new TTTLogic(); TTTGui tg = new TTTGui(tLogic);

// Set the GUI visible tg.setVisible(true);

}

}

This class creates the TTTLogic object that is to be used by the GUI. So, when users interact with the application, the GUI can track their interactions using this object.

TTTLogic.java

This class contains the most complicated code for the example. It keeps track of player moves, player turns, player positions, and if there is a winner or not. There is a member variable called m_nBoard, which is a two-dimensional array that always keeps track of which squares are occupied on the board:

650

Packaging and Deploying Your Java Applications

public class TTTLogic { int [][]m_nBoard;

int m_nX, m_nO;

boolean m_bXTurn;

The TTTLogic constructor sets the values for X and O in the m_nX and m_nO variables and sets the default to turn to X. Finally, it clears the board array by setting it with all zeros:

public TTTLogic() {

m_nX = 1; m_nO = 2;

m_bXTurn = true;

// Initialize array m_nBoard = new int[3][3];

// Clear the board

for (int x = 0; x < 3; x++){ for (int y = 0; y < 3; y++) {

m_nBoard[x][y] = 0;

}

}

}

The getMarker method takes an x and y parameter. The x parameter represents a row, and the y parameter represents a column. The method will return the value for the particular square on the board that is requested. For example, an x value of 0 and a y value of 2 would result in the value of the upper-right corner square being returned:

public int getMarker(int x, int y) { return m_nBoard[x][y];

}

The setMarker is the opposite of getMarker and actually sets the marker value of a specified square. It knows which mark to put in by determining whose turn it is using the this.getXTurn method. Once the marker has been set, the method advances the turn to the next player:

public boolean setMarker(int x, int y) { int nIsFree = 0;

nIsFree = getMarker(x, y);

if (nIsFree == 0) {

if (this.getXTurn() == true) { m_nBoard[x][y] = m_nX; this.setXTurn(false);

} else {

m_nBoard[x][y] = m_nO; this.setXTurn(true);

}

651

Chapter 14

return true;

}

return false;

}

The getWinner method is a very large method that determines who the winner is by executing different checks on the board. The checking for the O winner was purposely removed to save space in the chapter:

public int getWinner() {

//1 = X

//2 = O

int nWinner = 0; int nCount = 0;

//-------- CHECK FOR an X winner

//check the across boxes first for X for (int x = 0; x < 3; x++){

nCount = 0;

for (int y = 0; y < 3; y++) { if (m_nBoard[x][y] == m_nX) {

nCount++; } else {

break;

}

}

if (nCount == 3) {

nWinner = m_nX; // X Wins! return nWinner;

}

}

So far, you have checked the across squares to see if there is a winner. If the winner is X, the value of m_nX is returned. Next, you will check the down squares and see if X has won:

// check the down boxes first for X for (int y = 0; y < 3; y++){

nCount = 0;

for (int x = 0; x < 3; x++) { if (m_nBoard[x][y] == m_nX) {

nCount++;

}else { break;

}

}

if (nCount == 3) {

nWinner = m_nX; // X Wins! return nWinner;

}

}

Finally, you need to check diagonally to see if X has won. If not, then you will need to search to see if O has won:

652

Packaging and Deploying Your Java Applications

// Check Diagonals

if (m_nBoard[0][0] == m_nX && m_nBoard[1][1] == m_nX && m_nBoard[2][2] == m_nX) {

nWinner = m_nX; // X Wins! return nWinner;

} else if (m_nBoard[2][0] == m_nX && m_nBoard[1][1] == m_nX &&

m_nBoard[0][2] == m_nX) { nWinner = m_nX; // X Wins! return nWinner;

}

return nWinner;

}

The method getXTurn is used to determine if it is player X’s turn or not. The setXTurn allows you to set whether it is player X’s turn or not:

public boolean getXTurn() { return m_bXTurn;

}

public void setXTurn(boolean bTurn) {

m_bXTurn = bTurn;

}

}

TTTGui.java

The TTTGui is too big to display here, so what you are seeing is an example of what occurs when the button representing square 0,0 is pressed by the user. The same code exists for almost all other buttons with a few coordinate changes:

private javax.swing.JButton getJbtOne() { if (jbtOne == null) {

jbtOne = new javax.swing.JButton(); jbtOne.setName(“jbtOne”);

jbtOne.setPreferredSize(new java.awt.Dimension(55,55)); jbtOne.setText(“”);

jbtOne.setFont(new java.awt.Font(“Dialog”, java.awt.Font.BOLD, 24));

jbtOne.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent e) { boolean bXTurn = m_TLogic.getXTurn();

if (m_TLogic.setMarker(0,0)) { if (bXTurn) {

jbtOne.setText(“X”);

}else { jbtOne.setText(“O”);

}

}

653

Chapter 14

When the button is pressed, the first thing that happens is the code saves the player’s turn in the bXTurn variable and then tries to set the marker on the space. If setMarker is successful, the appropriate symbol is used to mark the square the user chose:

int nWinner = m_TLogic.getWinner();

if (nWinner != 0) {

if (nWinner == 1) { JOptionPane.showMessageDialog(null, “X WINS!!!”,

“X WINS!!!”, JOptionPane.OK_OPTION);

}else {

JOptionPane.showMessageDialog(null, “O WINS!!!”,

“O WINS!!!”, JOptionPane.OK_OPTION);

}

}

}

});

}

return jbtOne;

}

Before the method is complete, it checks to see if it has a winner. If the user who clicked the square has won, the method will pop up a message box declaring the winner! The application must now be reset in order to play another game.

Summarizing Java Web Start

From the examples of code that you have seen, there is one step that wasn’t mentioned — signing the JAR file. The necessary steps to sign JAR files are discussed under the JAR section of this chapter. To summarize, you should configure your Web server to understand requests for JNLP files. You’ll then need to create the JNLP file that describes the application to be launched with Java Web Start. You should package your application in a JAR file and sign the JAR file using the jarsigner tool. Finally, you should create the HTML page that will be used to access your JNLP file. That’s all that is needed to turn your application into a Java Web Start application!

Using ANT with Web Archives

ANT is an open source application used for generally building Java applications. It has a vast array of built-in configuration management functions that are configured through XML tags. Ant essentially is a tool to do away with the dreaded makefiles of the past that required programmers to write an enormous amount of fragile, shell-based commands that had to be flexible enough for the user’s environment and demands. ANT uses Java to do its necessary work, and, instead of shell-based commands, ANT has a concept called ANT tasks that performs almost every configuration/build task a programmer could want. You can download the latest binary distribution of ANT from http://ant.apache.org.

Installing ANT

Once you have downloaded your ANT distribution of choice, you simply extract the file to a directory of choice. When ANT is exploded, it creates the following main directory structure that is illustrated and explained in the following diagram, Figure 14-8.

654

Packaging and Deploying Your Java Applications

ROOT

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

bin

 

 

lib

 

 

docs

 

etc

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Contains XSL

Contains the

 

 

 

 

 

manual

 

scripts used

 

 

 

 

 

 

 

 

 

 

utilities.

 

 

 

 

 

 

 

 

to execute ANT.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Contains all

 

 

 

The main

 

Contains ANT's

 

 

the libraries

 

 

 

ANT manual can

documentation.

 

 

that ANT needs

 

 

 

be found here

 

 

 

 

 

 

in order to run.

 

 

 

in HTML form.

 

 

 

 

Figure 14-8

 

 

 

 

 

 

 

 

 

 

 

 

The main directory of interest should be the bin directory because this directory contains the scripts that execute ANT. You will need to configure your environment to be able to execute the ANT scripts from a console or command prompt. In order to do so, simply follow these three steps:

1.Set JAVA_HOME to point to the directory where your JDK is installed.

2.Create an environment variable called ANT_HOME, and set it to the directory that you have installed Ant to. Example: ANT_HOME= C:\apache-ant-1.6.2

3.Finally, add the ANT_HOME\bin directory to your PATH environment variable so that Ant can be accessible from any directory in any console window.

If you did not download a binary distribution of ANT, then you will have to consult the instructions that come with ANT on how to build the source code for the particular platform you are on.

Building Projects with ANT

ANT is extremely easy to build with once you understand the basics of what is involved with creating Ant build files. ANT requires you to create an XML file called a build file that contains a project element and at least one target element. Each target can have multiple task elements that can perform a variety of operations from deleting files to compiling source code. With ANT, you can incorporate property files that you can read in, and you can also access system properties at any time during the execution of the build file.

A basic ANT system for building a project generally consists of a simple build.xml file and sometimes a properties file for loading in specific settings like a location of a third-party JAR. The build.xml file will

655

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]