1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional Portal Development with Open Source Tools Java Portlet API phần 4 pptx

46 218 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 46
Dung lượng 1,22 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The following code shows how to use the PersistenceBrokerAPI toretrieve the number of messages that exist in the database: PersistenceBroker broker; public int getCount { try { // Create

Trang 1

Element Description

batch-mode Batch-mode is used only if a database supports it Each implementation

of the mode is database-dependent Batch-mode can be changed at time using the PersistenceBroker.serviceConnectionManager.setBatchMode( )

run-useAutoCommit Affects the way OJB uses the auto-commit mode There are three modes;

the default mode is 1

0 — turns auto-commit off.

1 — sets auto-commit explicitly to true when a connection is created,

and temporarily sets it to false when necessary (default)

2 — sets auto-commit explicitly to false when a connection is created.

ignoreAutoCommit If set to false, OJB will ignore any exceptions that are thrown from the Exceptions use of auto-commit

Home.jsp

This is the default page that is displayed to users when they access the message board sample Webapplication When this page is displayed, a list of currently existing messages is shown to the user Thispage also provides links to the user to enable the viewing of a specific message in greater detail or todelete a specific message from the database The code to perform all this functionality is embeddedwithin Home.jsp

In order to retrieve the messages and display them to the user, you need to know how many messagesexist in the database first If none are available, then there is no need to waste your time trying to iteratethrough non-existent messages The following code shows how to use the PersistenceBrokerAPI toretrieve the number of messages that exist in the database:

PersistenceBroker broker;

public int getCount() {

try { // Create a PersistenceBroker object using the // PersistenceBrokerFactory

PersistenceBrokerFactory.releaseAllInstances();

return allMessages.size();

} else {

Trang 2

PersistenceBrokerFactory.releaseAllInstances();

return 0;

}} catch (Exception e) {System.out.println(e);

e.printStackTrace();

broker.close();

PersistenceBrokerFactory.releaseAllInstances();

}return 0;

}Once you have the number of messages that exist in the database, you can then retrieve each one inde-pendently to exhibit to the user You need to use getMessageto retrieve the specified message from theserver The getMessagemethod is shown in the following code:

public Message getMessage(String sIndex, String sUserIP) {Message msgFound = null;

try {// Create a PersistenceBroker object using the // PersistenceBrokerFactory

break;

} else {iter.next();

}}Once you have found a message, you need to create a Viewerobject that will let the message know that

it has been viewed The new Viewerobject is then saved to the Messageobject, which is in turn saved tothe data source using the storemethod of the brokerobject:

101

Trang 3

// If we have a message, return it

if (msgFound != null) {// Construct a viewer object to show that this message has// been accessed

Vector tmpvVwrs = msgFound.getViewers();

Viewer tmpView = new Viewer();

Calendar clNow = Calendar.getInstance();

tmpView.setIP(sUserIP);

tmpView.setDate(

Integer.toString((clNow.get(Calendar.MONTH) + 1)) + “/” + Integer.toString(clNow.get(Calendar.DAY_OF_MONTH)) + “/” +Integer.toString(clNow.get(Calendar.YEAR))

// Store the new persistent making it persistentbroker.store(msgFound);

// Finally commit the transactionbroker.commitTransaction();

} catch (PersistenceBrokerException ex) {// Rollback on error

PersistenceBrokerFactory.releaseAllInstances();

} else {broker.close();

PersistenceBrokerFactory.releaseAllInstances();

}} catch (Exception e) {System.out.println(e);

e.printStackTrace();

broker.close();

PersistenceBrokerFactory.releaseAllInstances();

}return msgFound;

}

Trang 4

From the getCountand getMessageexamples, you can perceive that there is a systematic approach toissuing queries using the PersistenceBrokerAPI The following sequence shows the generic steps inissuing a query utilizing the PBAPI:

1. Obtain a PersistenceBrokerby using the PersistenceBrokerFactorydefaultPersistenceBrokermethod:

broker = PersistenceBrokerFactory.defaultPersistenceBroker();

2. Construct a query using a class that is mapped in the OJB metadata repository:

Query query = new QueryByCriteria(Message.class, null);

3. Ask the broker to retrieve a collection of objects based on the query statement:

Collection allMessages = broker.getCollectionByQuery(query);

4. Iterate through the collection results and manipulate the objects you want to change:

java.util.Iterator iter = allMessages.iterator();

5. After changing the objects, you then need to store them back in the database This requires you

to issue a transactionmethod and a storemethod:

broker.delete(msgObject); // Delete the Messagebroker.commitTransaction();

etc

In the preceding code, you now have all the necessary functionality to execute the Home.JSP programand see the results Figure 4.3 shows what the OJB message board looks like after it has retrieved all themessages that exist in a database

The Home.jsp code is now complete and functioning The following section describes how to add a sage to a database using the PersistenceBrokerAPI Add.jsp will demonstrate this functionality

mes-103

Trang 5

Figure 4.3

Add.jsp

This page is accessed when the user wants to submit a new article to the message board A form isshown to the user requiring them to enter information in several fields Once the user has filled out theform and pressed the Submit button, the information is actually submitted to the same Add.jsp page,which displays an embedded note to the user informing them that their article has been submitted to themessage board

The majority of the code is similar to the code in previous examples; the main exception is that you need

to construct the Messageobject and fill it with data before you can persistently store it Another point tonote here is that when the objects are stored, the PersistenceBrokerAPI will automatically create aunique ID for the object(s) and store it in the database Figure 4.4 exemplifies the Add.jsparticle sub-mission form

The addMessagemethod is called when the user clicks the Submit button The addMessagemethodprocesses the form data, converts it into a Messageobject, and then uses the PBAPI to store the object inthe database The following code displays the addMessagecode:

public Message addMessage(

String sSubmitter, String sSubject, String sMessage) {Message msgToStore = null;

try {broker = PersistenceBrokerFactory.defaultPersistenceBroker();

// Create Message to storemsgToStore = new Message();

Trang 6

// Add submitter to messagemsgToStore.setSubmitter(sSubmitter);

// Add subject to messagemsgToStore.setSubject(sSubject);

// Add article to messagemsgToStore.setMessage(sMessage);

Calendar clNow = Calendar.getInstance();

// Set the datemsgToStore.setDate(

Integer.toString((clNow.get(Calendar.MONTH) + 1)) + “/” +Integer.toString(clNow.get(Calendar.DAY_OF_MONTH)) + “/” +Integer.toString(clNow.get(Calendar.YEAR)));

Trang 7

// Store the new objectbroker.store(msgToStore);

PersistenceBrokerFactory.releaseAllInstances();

} catch(Exception e) {System.out.println(e);

broker.close();

PersistenceBrokerFactory.releaseAllInstances();

}return msgToStore;

}

View.jsp

This is the final JSP in the message board example It does not introduce any new code and utilizes thesame getMessagemethod found in Home.jsp What it does differently is display the full contents of aspecific message to the user Figure 4.5 is a screenshot of what the user would see when a message isaccessed with View.jsp

Figure 4.5

Trang 8

Developing with the ODMG API

This section briefly describes how to develop OJB applications using the ODMG API OJB has created itsown implementation of the ODMG APIs, which it stores in the package org.apache.ojb.odmg In order

to use the vast feature set of ODMG, you have to deal directly with an object that acts as the main entrypoint of the ODMG APIs This object is distinguished by the interface org.odmg.Implementation,which enables you to obtain OQLobjects, databaseobjects, persistent collectionobjects, andtransactionobjects The good news is that if you have used ODMG before with non-OJB applications,the code will be very similar to what you have created in the past, as all vendors must implement theorg.odmg.Implementationinterface The main difference is learning how OJB provides you access tothe ODMGobject

The examples that follow are based on creating the same type of functionality seen in the PersistenceBrokerAPI message board example, but utilizing ODMG instead The core functionalitycovered here includes opening a database, deleting and retrieving objects, and updating and storingobjects

Opening a Database

As stated earlier, OJB has its own specific implementation of the org.odmg.Implementationinterface;this is simply org.apache.ojb.odmg.OJB Now we need to obtain an instance of this class using thestatic factory method getInstance Using this instance, we can now open or create an ODMG database(org.odmg.Database) The complete code follows:

Database odmgDB = odmgObject.newDatabase();

//open databasetry {

odmgDB.open(“repository.xml”, Database.OPEN_READ_WRITE);

} catch (ODMGException e) {e.printStackTrace();

}return odmgDB;

}

Retrieving Objects

Obtaining objects using ODMG is quite a bit different than using the PersistenceBrokerAPI Youneed to use the Object Query Language (OQL) designated by ODMG and set up query statements,which are very similar to SQL statements With the PBAPI, you issue queries directly on the objects withQueryByCriteriamethods You need to obtain an OQLQueryobject first, and then create a query state-ment and execute it This returns the Messageobjects in a DList, which you can later iterate throughwhen you are ready to process them The following example shows the complete code for retrievingobjects using ODMG:

107

Trang 9

import org.apache.ojb.odmg.OJB;

import org.odmg.DList;

public DList getAllMessages() {

try {// Begin a transactionTransaction trans = odmgObject.newTransaction();

// Execute the queryDList allMessages = (DList) query.execute();

// Commit the transactiontrans.commit();

// Return the DList of messagesreturn allMessages;

}catch (Exception e) {System.out.println(e);

e.printStackTrace();

}return null;

}

Storing Objects

Storing objects is extremely easy with the ODMG API All you need to do is start a new transaction, create

a write lock on the object to store, and then commit the transaction The following example demonstratesthe code to store objects with ODMG:

public void storeObject(Message msg) {

Transaction trans = null;

try {// Obtain a new transaction objecttrans = odmgObject.newTransaction();

e.printStackTrace(System.out);

}}

Trang 10

Updating Objects

Updating objects requires more interaction than storing objects In order to update an existing object,you have to execute a query that can find the specific object that you are looking for Once the object isobtained, you then invoke a write lock on the object The final steps are to update the necessary datacontained in the object and then commit the transaction Following is the complete code needed forupdating objects using ODMG:

public void update(Message msg){

Transaction trans = null;

// Create a query to find a message with the specific IDString oqlQuery = “select * from “ + Message.class.getName() +

“ where id = “ + msg.getID();

// Get the current databaseDatabase odmgDB = odmgObject.getDatabase(null);

try {trans = odmgObject.newTransaction();

} catch (Exception e) {// RollBack

trans.abort();

System.out.println(e);

e.printStackTrace(System.out);

}}

Deleting Objects

Deleting objects with ODMG API requires the same methods as updating objects First, you have to obtain the object you want to delete Second, you need to mark it for deletion withDatabase.deletePersistent(Object) Third, you simply commit the transaction and the deleteoperation is carried out The following example displays the code for deleting objects:

109

Trang 11

public void delete(Message msg){

Transaction trans = null;

// Get the current databaseDatabase odmgDB = odmgObject.getDatabase(null);

// Create the OQL queryString oqlQuery = “select * from “ + Message.class.getName() +

“ where id = “ + msg.getID();

try { trans = odmgObject.newTransaction();

// Begin Transactiontrans.begin();

OQLQuery query = odmgObject.newOQLQuery();

query.create(oqlQuery);

// Execute queryDList dlMessage = (DList) query.execute();

Message msgFound = (Message) dlMessage.get(0);

// Mark message for deletionodmgDB.deletePersistent(msgFound);

// Commit the transactiontrans.commit();

} catch (Exception e) {// RollBack

trans.abort();

System.out.println(e);

e.printStackTrace(System.out);

}}

Developing with the JDO API

OJB does not currently have its own implementation of JDO OJB uses a plug-in called OJBStore, located

in the package org.apache.ojb.jdori.sql A full JDO implementation is scheduled for the 2.0release of OJB, and so is currently beyond the scope of this book

OJB Extras

This section contains various information that you should find helpful when using OJB It covers the lowing: the steps that should be taken to verify an OJB installation; the database platforms that OJB can besuccessfully used with; the JDBC types that OJB enables for your use when developing your applications;how to correctly deploy an OJB application; and, finally, some special performance notes regarding OJB

Trang 12

fol-Verifying an OJB Installation

Regardless of what API layer you chose to develop with, it is imperative that you make sure that OJB isproperly installed on your machine The OJB development team makes this process extremely easyusing JUnit and Ant You want to make sure that you have JDK 1.2 or later installed before proceedingwith the following tests

1. Ensure that the JAVA_HOMEenvironment variable points to the root directory of the Java SDKinstallation

2. Make sure that you have downloaded the latest binary or source distribution of OJB

3. From the base directory of your new installation of OJB, execute bin\build junit for win32 machines or bin/build.sh junit for Unix machines.

These steps should initiate a chain of regression tests that can take several minutes to complete After allthe tests have completed, a summary of the results will be displayed in the console Make sure that notests failed A typical output from these tests is as follows:

junit-no-compile-no-prepare:

[junit] Running org.apache.ojb.broker.AllTests[junit] Tests run: 187, Failures: 0, Errors: 0, Time elapsed: 26.228 sec[junit] Running org.apache.ojb.odmg.AllTests

A common error that can occur during the beginning of the tests is that the Antscript will not be able tolocate the j2ee.jarfile A simple solution is to put a copy of the file in the OJB_BASE\libdirectory.The other option is to edit the buildscript to point to the location of the j2ee.jar

Supported Database Platforms

OJB currently supports a large array of database platforms that can be used with OJB persistent objectdevelopment Each database system requires its own JDBC driver to enable access to it The currentlysupported database platforms are as follows:

Trang 13

❑ Axion

❑ NonstopSQL

Supported JDBC Data Types

OJB supports the most common JDBC data types that applications use today The following describesthe supported JDBC data types and their Java equivalent

Trang 14

Deploying OJB Applications

Deploying OJB applications requires specific knowledge of the OJB resources and configuration files thatare needed to run an OJB-supported application This section describes the resources and configurationsand explains how each fits into the OJB framework

Jar Files

The following table is a list of Jar files supplied with OJB in the ojb_root/libdirectory The files with anasterisk next to their name are required for OJB to run The other files are used for building purposes only

db-ojb-xxx.jar* Latest release

commons-beanutils-1.4-dev.jar* 1.4-devcommons-collections-2.0.jar* 2.0commons-dbcp-1.0.jar* 1.0commons-lang-1.0-b1.1.jar* 1.0-b1.1commons-logging-1.0.1.jar* 1.0.1commons-pool-1.0.1.jar* 1.0.1

Trang 15

Metadata Files

Two main files are needed in order for OJB to run correctly:

❑ The repository.xmlfile and any resources it points to are needed for deployment

❑ The ojb.propertiesfile is also need for runtime configurations

These files must also be stored in the CLASSPATH because OJB will attempt to load them via theClassLoaderresource look-up

OJB provides an API layer that makes it easy for developers to create O/R mapping applications Youbasically just need to weigh the options of capability, convenience, and rapid development time versusthe best possible performance solution OJB also provides built-in object caching features, whichenhance query times drastically

The bottom line is that the performance hit you may encounter using OJB versus straight queries isminor in comparison to the amazing feature set and functionality that is built in to OJB It is also impor-tant to note that all O/R mapping tools are slower than straight queries; this is not exclusive to OJB

Summar y

Object Relational Bridge (OJB) is a powerful, flexible, and exciting object-to-relational mapping tool thatcontains a vast array of functionality for incorporating persistent objects into your application designs OJBtakes all of the guesswork out of O/R mapping and is truly a transparent persistence O/R mapping tool

Trang 16

This chapter described Object-to-Relational mapping and then explained the main features of OJB Next,

it covered how to use OJB’s API layers and demonstrated a complete message board application that lizes OJB’s features You saw fully functional code that exploited the PersistenceBroker API and ODMGAPI Finally, you examined the configurations needed in order to deploy OJB in your own applications.The next chapter describes content management with Jakarta’s Slide

uti-115

Trang 18

Content Management with Jakar ta’s Slide

Jakarta’s Slide(http://jakarta.apache.org/slide) is an open-source content management and gration system It provides a robust API and a low-level content management framework, whichcan be used as a foundation for building your own, more complex content management systems.Slide is currently maintained by the Apache Software Foundation and was originally developed

an Internet Engineering Task Force (IETF) standard and is supported by many popular softwarecompanies (Microsoft, IBM, Novell, and more)

In this chapter, we explain the Slide architecture — specifically, namespaces, domains, and APIs;provide information on the setup and configuration of Slide; discuss WebDAV and Slide; andshow examples of Slide using a WebDAV-supported client

Slide Architecture

The architecture of Slide’s features and services were developed from a modular and pluggabledesign consisting of high-level and low-level services, with a concentration on security, versioning,locking, and structure The high-level services have strong dependencies on each other in order to

Trang 19

keep the security of Slide’s components intact The low-level services are not concerned with securityand are more related to functionality These services are all designed to be pluggable, meaning you canadd or remove services as needed This pluggable design of low-level services makes Slide extremelyflexible and readily adaptable to a wide variety of content management needs.

You should understand the five main architectural concepts of Slide:

The external architecture (EA), shown in Figure 5.1, is the highest-level architecture perspective

There are two simplistic layers in the EA: the client layer and the server layer.

The client layer contains three components, which are used to communicate with the server The first

component is the WebDAV client The WebDAV client is an application that supports and understands

the WebDAV protocol from a client perspective The WebDAV client connects to the WebDAV servletand communicates its requests to the WebDAV servlet Many WebDAV client tools are available, but two

of the most common are DAV Explorer and the Microsoft Windows Operating System (O/S) Windowshas WebDAV capabilities built right into the O/S You will see examples of using Windows to issueWebDAV operations later in this chapter, in the section, “WebDAV and Slide.” DAV Explorer is a stand-alone Java application developed by the University of California, Irvine DAV Explorer looks very similar to Windows Explorer and it supports most of the functionality specified in RFC 2518, which isthe WebDAV Distributed Authoring Protocol specification You can download DAV Explorer fromwww.ics.uci.edu/~Webdav/

The second component is the HTTP client, which is an application that communicates with the Slide

server via the HTTP protocol An example application could be any Web browser With the HTTP client,the content management system can be managed easily through a Web-based interface This falls rightinto play with portal development and is probably the best approach for administering content from aportal perspective

The final component of the client layer is a Java Application Client A Java Application Client can be

created to utilize Slide’s API layer directly without going through the WebDAV servlet layer This is nitely a plus when performance is a factor in the development task you are presented with

defi-From a portal development standpoint, you would most likely choose either the HTTP client approach

or the WebDAV approach for managing content, as both lend themselves to easy remote managementcapabilities The standalone Java application approach requires more configurations in order to get theapplication up and running If you want a portable standalone Java application as your approach for

Trang 20

managing content, then using Java Web Start (JWS) technology would be a great option Java Web Startenables you to download an application from the World Wide Web via a Web browser by simply clicking

on a hyperlink The only configuration requirement of the machine that is downloading the program isthat it has Java Web Start installed Added benefits of using JWS are the extra security and versioningfeatures built into its protocol You can always be sure that administrators are using the latest copy of anapplication and that the software is legitimate, as certificates and digital signatures are used Please seeChapter 12 for more in-depth information on Java Web Start

Trang 21

The server layer enables the client layer to communicate with it through one of two methods Onemethod is to use the WebDAV servlet for communication WebDAV clients and HTTP clients use thisapproach The second method is for the client to communicate directly with the Slide API StandaloneJava applications are the prime candidates for using the Slide API for communication.

Internal Architecture

The internal architecture digs deeper into the component realm of Slide, enabling you to see the ual pluggable interfaces that exist Figure 5.2 depicts the internal architecture

individ-The internal architecture can be depicted with four layers: individ-The Application layer, the Slide API layer,

the Helper layer, and the Data Store layer.

The Application layer provides the means by which clients can access the Slide API There are two methods for doing this One is to use the WebDAV servlet for communication As described in the pre-ceding section, the WebDAV client and HTTP client interface with the WebDAV servlet for communica-tion purposes The second method is to use a standalone Java application that will directly access theSlide API layer

The Slide API layer provides access to the content management Java classes called helpers, and acts as a

bridge between the Application layer and the Helper layer The Slide API accepts operation requestsfrom the Application layer and executes the requests accordingly

The Helper layer encapsulates all the functionality to which an application would need access Thehelpers that currently exist in Slide are described in the following table

Structure Provides access to the namespace tree

Lock Enables data-locking capabilities

Security Provides access to security functionality

Content Enables the management of content, revisions, and metadata

Macro Provides high-level object management functionality

Index Currently not implemented, this helper will provide indexing and searching

Trang 22

manage-Figure 5.2

Data sources

Slide API

Securityhelper

Lockhelper

Contenthelper

JNI

JDBC

FileSystem

LDAP

Java applicationWebDAV servlet

JTA Layer

121

Trang 23

Transaction Management

Slide implements a very robust transaction management system Transaction management is veryimportant when dealing with content management, especially in a system that is accessed by multipleusers at any given time This is definitely the case when building Java portals The transaction manage-ment architecture is shown in Figure 5.3

DataStores

Ngày đăng: 13/08/2014, 12:21

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN