Tải bản đầy đủ (.pdf) (991 trang)

OReilly jakarta commons cookbook

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.87 MB, 991 trang )



JakartaCommonsCookbook
ByTimothyM.O'Brien

Publisher :O'Reilly
PubDate :November2004

ISBN :0-596-00706-X
Tableof

Pages :400
Contents

• Index
• Reviews
Reader

Reviews
• Errata
• Academic



Thiscollectionprovidesexperttipsforusingtheutilitiesofthe
Java-basedJakartaCommonsopensourceproject.Youdon'thave
tobeanexpert,thebook'ssolution-basedformatcontainscode
examplesforawidevarietyofweb,XML,network,testing,and
applicationprojects.IfyouwanttolearnhowtouseJakarta
CommonsutilitiestocreatepowerfulJavaapplicationsandtools,
theJakartaCommonsCookbookisforyou.




JakartaCommonsCookbook




Tableof

Contents
• Index
• Reviews
Reader

Reviews
• Errata
• Academic

ByTimothyM.O'Brien

Publisher :O'Reilly
PubDate :November2004
ISBN :0-596-00706-X
Pages :400


Copyright

Preface
What'sInside


ConventionsUsedinThisBook




WhatYou'llNeed




TheApacheSoftwareLicense




We'dLiketoHearfromYou

TheJakartaCommonsCommunity
UsingCodeExamples
Acknowledgments


Chapter1.SupplementstotheJava2Platform
Introduction

Recipe1.1.ObtainingCommonsLang





Recipe1.2.JoiningtheCommons-UserMailingList




Recipe1.4.AutomatingtheGenerationoftoString()Content




Recipe1.6.AutomatinghashCode()andequals()

Recipe1.3.GettingtheCommonsLangSourceCode
Recipe1.5.CustomizingGeneratedtoString()Content
Recipe1.7.AutomatingcompareTo()








Recipe1.8.PrintinganArray




Recipe1.10.TransformingBetweenObjectArraysandPrimitiveArrays





Recipe1.12.CreatingaMapfromaMultidimensionalArray




Recipe1.14.RoundingDateObjects




Recipe1.16.CreatinganEnum




Recipe1.18.ValidationofMethodParameters

Recipe1.9.CloningandReversingArrays
Recipe1.11.FindingItemsinanArray
Recipe1.13.FormattingDates
Recipe1.15.TruncatingDateObjects
Recipe1.17.GeneratingUniqueNumericIdentifiers
Recipe1.19.MeasuringTime


Chapter2.ManipulatingText

Introduction

Recipe2.1.SettingUpStringUtilsandWordUtils




Recipe2.2.CheckingforanEmptyString




Recipe2.4.SplittingaString




Recipe2.6.StrippingandTrimmingaString




Recipe2.8.CreatinganEmphasizedHeader




Recipe2.10.WrappingWords





Recipe2.12.MeasuringtheFrequencyofaString




Recipe2.14.CalculatingStringDifference




Recipe2.16.GettingtheCommonsCodecSourceCode

Recipe2.3.AbbreviatingStrings
Recipe2.5.FindingNestedStrings
Recipe2.7.ChompingaString
Recipe2.9.ReversingaString
Recipe2.11.TestingtheContentsofaString
Recipe2.13.ParsingFormattedStrings
Recipe2.15.UsingCommonsCodec
Recipe2.17.CalculatingSoundex


Chapter3.JavaBeans
Introduction

Recipe3.1.RepresentingBeansGraphically





Recipe3.2.ObtainingCommonsBeanUtils




Recipe3.4.AccessingSimpleBeanProperties

Recipe3.3.GettingtheCommonsBeanUtilsSourceCode
Recipe3.5.AccessingNestedBeanProperties




Recipe3.6.AccessingIndexedBeanProperties




Recipe3.7.AccessingMappedBeanProperties




Recipe3.9.DeterminingtheTypeofaBeanProperty





Recipe3.11.CopyingBeanProperties




Recipe3.13.SettingaBeanProperty




Recipe3.15.ValidatingBeanswithPredicates




Recipe3.17.WrappingaBeanwithaMap

Recipe3.8.AccessingaSimple,Nested,Indexed,andMappedBeanProperty
Recipe3.10.ComparingBeans
Recipe3.12.CloningaBean
Recipe3.14.TestingPropertyAccess
Recipe3.16.CreatingaMapofBeanProperties
Recipe3.18.CreatingaDynamicBean

Recipe3.19.GettingandSettingPropertiesasStrings


Chapter4.Functors
Introduction





Recipe4.1.ObtainingCommonsCollections




Recipe4.3.ReversingaComparator




Recipe4.5.ComparingNulls




Recipe4.7.UsingSimplePredicates




Recipe4.9.CreatingCompositePredicates




Recipe4.11.CreatingaChainofTransformations





Recipe4.13.WritingaClosure




Recipe4.15.ModelingConditionalStatementswithClosures

Recipe4.2.GettingtheCommonsCollectionsSourceCode
Recipe4.4.ChainingComparators
Recipe4.6.Fixed-OrderComparison
Recipe4.8.WritingaCustomPredicate
Recipe4.10.TransformingObjects
Recipe4.12.ApplyingConditionalTransformations
Recipe4.14.ChainingClosures
Recipe4.16.ModelingLoopswithClosures


Chapter5.Collections
Introduction

Recipe5.1.ObtainingCommonsCollections




Recipe5.2.UsingaLoopingIterator





Recipe5.4.FilteringaCollectionwithaPredicate

Recipe5.3.IteratingOveranArrayList
Recipe5.5.IteratingThroughDistinctElements




Recipe5.6.UsingaBag




Recipe5.7.UsingaBuffer




Recipe5.9.UsingaBlockingBuffer




Recipe5.11.RetrievingaKeybyaValue





Recipe5.13.CreatingTypedCollectionsandMaps




Recipe5.15.ConstrainingListContents




Recipe5.17.CreatingaLeastRecentlyUsedCache




Recipe5.19.CountingObjectsinaCollection

Recipe5.8.CreatingaPriorityQueue
Recipe5.10.StoringMultipleValuesinaMap
Recipe5.12.UsingaCase-InsensitiveMap
Recipe5.14.ConstrainingMapValues
Recipe5.16.TransformingCollections
Recipe5.18.UsingaLazyMap
Recipe5.20.PerformingSetOperations

Recipe5.21.RetrievingMapValuesWithoutCasting


Chapter6.XML

Introduction




Recipe6.1.ObtainingJakartaCommonsDigester




Recipe6.3.Namespace-AwareParsing




Recipe6.5.VariableSubstitutionandXMLParsing




Recipe6.7.TurningBeansintoXMLDocuments

Recipe6.2.TurningXMLDocumentsintoObjects
Recipe6.4.CreatingaSimpleXMLCommandLanguage
Recipe6.6.ObtainingJakartaCommonsBetwixt
Recipe6.8.CustomizingXMLGeneratedfromanObject

Recipe6.9.TurningXMLDocumentsintoBeans



Chapter7.ApplicationInfrastructure
Introduction




Recipe7.1.ObtainingCommonsCLI




Recipe7.3.ParsingaComplexCommandLine




Recipe7.5.ObtainingCommonsConfiguration




Recipe7.7.ConfiguringApplicationswithXML




Recipe7.9.ObtainingCommonsLogging

Recipe7.2.ParsingaSimpleCommandLine
Recipe7.4.PrintingUsageInformation

Recipe7.6.ConfiguringApplicationswithPropertiesFiles
Recipe7.8.UsingCompositeConfiguration
Recipe7.10.UsinganAbstractLoggingInterface




Recipe7.11.SpecifyingaLoggingImplementation




Recipe7.12.ObtainingApacheLog4J
Recipe7.13.ConfiguringLog4JwithaPropertiesFile

Recipe7.14.ConfiguringLog4JwithXML


Chapter8.Math
Introduction




Recipe8.1.UsingFractions




Recipe8.3.UsingNumberRanges





Recipe8.5.ObtainingCommonsMath




Recipe8.7.SolvingaSystemofLinearEquations




Recipe8.9.EstablishingRelationshipsBetweenVariables

Recipe8.2.FindingtheMaximumandMinimuminanArray
Recipe8.4.GeneratingRandomVariables
Recipe8.6.CalculatingSimpleUnivariateStatistics
Recipe8.8.ArithmeticwithComplexNumbers
Recipe8.10.EstimatingtheAmountofTimeLeftinaProcess


Chapter9.Templating
Introduction

Recipe9.1.ObtainingCommonsJEXL





Recipe9.2.UsinganExpressionLanguage




Recipe9.4.ExternalizingLogicwithanExpressionLanguage




Recipe9.6.UsingaSimpleTemplatingLanguage




Recipe9.8.UsingMacrosinaTemplatingEngine




Recipe9.10.ObtainingFreeMarker




Recipe9.12.AccessingXMLDocumentsfromaTemplatingEngine





Recipe9.14.UsingFreeMarkerinaWebApplication

Recipe9.3.InvokingMethodsinanExpression
Recipe9.5.ObtainingJakartaVelocity
Recipe9.7.WritingTemplateswithConditionalsandLoops
Recipe9.9.InvokingMethodsinaTemplate
Recipe9.11.UsingaComplexScriptingEngine
Recipe9.13.UsingVelocityinaWebApplication
Recipe9.15.WritingTemplatesinEclipse


Chapter10.I/OandNetworking
Introduction

Recipe10.1.ObtainingCommonsIO




Recipe10.2.CopyingStreams,byte[],Readers,andWriters



Recipe10.4.PrintingaHuman-ReadableFileSize

Recipe10.3.ClosingStreams,Readers,andWriters





Recipe10.5.CopyingFiles,Strings,andURLs




Recipe10.6.DeletingDirectoriesRecursively




Recipe10.8.TouchingaFile




Recipe10.10.MeasuringStreamTraffic




Recipe10.12.ObtainingJakartaORO




Recipe10.14.ObtainingCommonsNet





Recipe10.16.SendingMailwithSMTP

Recipe10.7.ObtainingtheSizeofaDirectory
Recipe10.9.FilteringFiles
Recipe10.11.SplittinganOutputStream
Recipe10.13.UsingGlobsandPerl5RegularExpressionstoListFiles
Recipe10.15.WritinganFTPClient
Recipe10.17.CheckingaPOP3Mailbox


Chapter11.HTTPandWebDAV
Introduction

Recipe11.1.ObtainingJakartaHttpClient




Recipe11.2.GettingJakartaHttpClientSourceCode




Recipe11.4.SendingParametersinaQueryString




Recipe11.6.DebuggingHTTPCommunications





Recipe11.8.SendingPOSTDatafromaFile




Recipe11.10.BasicAuthentication




Recipe11.12.WorkingwithCookies




Recipe11.14.SSL




Recipe11.16.ObtainingJakartaSlide

Recipe11.3.PerforminganHTTPGET
Recipe11.5.RetrievingContentwithaConditionalGET
Recipe11.7.MakinganHTTPPOSTRequest
Recipe11.9.UploadingFileswithaMultipartPOST

Recipe11.11.NTLMAuthentication
Recipe11.13.HandlingRedirects
Recipe11.15.AcceptingaSelf-SignedCertificate
Recipe11.17.ConnectingtoWebDAVResources

Recipe11.18.ModifyingaWebDAVResource


Chapter12.SearchingandFiltering
Introduction




Recipe12.1.ObtainingCommonsJXPath




Recipe12.3.SearchaCollectionofSimpleObjects

Recipe12.2.QueryinganObjectGraphwithXPath
Recipe12.4.ApplyingXPathQueriestoComplexObjectGraphs




Recipe12.5.ObtainingJakartaLucene





Recipe12.6.CreatinganIndexofXMLDocuments
Recipe12.7.SearchingforaSpecificTerminaDocumentIndex

Recipe12.8.FindingtheFrequencyofTermsinanIndex


Colophon

Index


Copyright©2005O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheCookbookseriesdesignations,JakartaCommonsCookbook,
theimageofanaardvark,andrelatedtradedressare
trademarksofO'ReillyMedia,Inc.
JavaandallJava-basedtrademarksandlogosaretrademarks
orregisteredtrademarksofSunMicrosystems,Inc.,inthe
UnitedStatesandothercountries.O'ReillyMedia,Inc.is

independentofSunMicrosystems,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
Inthisbook,you'llfindinformationaboutasetoflibraries
developedwithintheJakartaCommons(alsoreferredtoas
"Commons").Commons( />isasetofsmall,popularcomponentsfromtheApacheSoftware
Foundation'sJakartaproject.Rangingfromtheelementaryto
thecomplex,manywouldconsidersomeoftheselibraries
indispensabletoanyJava©project.Thesecomponentsareso
widespread,theymayalreadybeonyourclasspath.Ifyou
developanapplicationusingJakartaStruts,ApacheTomcat,or
Hibernate,youhaveCommonsBeanUtilsandCommonsLogging
inyourclasspath.IfyoujustinstalledRedHatEnterpriseLinux
withthedefaultconfiguration,you'vegotCommonslibraries
somewherein/usr.IfyoudownloadedSun'sJ2EE1.4SDK,you
willhavealsodownloadedCommonsLoggingandCommons
Launcher.WhileJakartaCommonsmaybeeverywhere,many
arestillunawareofthecapabilitiesthesecomponentsprovide.
ThisbookusesJakartaCommonstofocusontactical
implementationdetails,answeringsuchquestionsas:Howdo

weparseXML?Howdoweserializebeans?Isthereaneasier
waytoworkwithCollections?HowdoweworkwithHTTPand
keeptrackofcookies?Thetacticalisoftensacrificedforthe
strategic.ConsideracomplexJ2EEsystemwithasolid,wellconceivedarchitecture.Thestrategic(orhigh-level)design
appearsreasonablefrom40,000feet,butassoonasyoudrill
intothedetails,younoticethateveryServletorJSPcontains
pagesuponpagesofunmaintainableandunnecessarycode
becausethedeveloperswerenotawareofsomevaluabletimesaverlikeBeanUtils,Collections,ortheDigester.Or,worse,the
developermayhavespentaweekreimplementingmostofthe
capabilitiesofCommonsBeanUtilseventhoughBeanUtilswas
alreadyintheclasspath.KnowingwhatJakartaCommonshas
toofferoftenhelpstoinformdecisionsmadeatthelowest


level.
Fewapplicationdeveloperswouldconsiderwritingacustom
XMLparser,butdeveloperswillfrequentlywritecustom
componentsthatduplicatefreelyavailablelibraries.Take,asan
example,asetofstaticutilitymethodsthatseemstopopupin
almosteverycomplexproject.Acommonprocesssuchas
readingafiletoaStringmayberefactoredintoa
CommonFileUtilsclass,orturningaDOMDocumentintoaset
ofbeansmaybeaccomplishedwithasetofclassesinsome
customcode.JakartaCommonsprovidessolutionstobothof
theseproblemsandmanymore,andreadingthisbookmay
helpyoutoavoidunnecessarywheelreinvention.
Manypeopleknowofthesecomponentsinageneralsense,but
fewhavethemonthsorweeksnecessarytositdownandread
therelevanttutorials,FAQs,blogs,andarchivedmailinglists
associatedwitheachcomponent.Theamountofworkinvolved

inkeepingup-to-datewithanarrayofopensourcecommunities
isnottrivial.ThisiswhyI'vetriedtocompactmuchofthis
informationintoeasilyaccessiblerecipes.Theserecipeswere
writtentoprovidetheinformationyouneedtostartusing
Commonsinafewminutes,buttheDiscussionandSeeAlso
sectionsgiveyouanopportunitytodigdeeperintothe
motivationbehindeachCommonscomponentifyouneedmore
information.
Thetoolsintroducedhereinsaveyouserioustimeandprovide
youwithasetofalternativesyoumaynotcurrentlybeaware
of.IwishIhadreadabooklikethisfiveyearsago;itwould
haveacceleratedmylearningandhelpedmetoavoidsome
costlydesigndecisions.Usethistextasyouwill;ifyouareonly
interestedinCommonsCollections,youshouldbeableto
quicklyfamiliarizeyourselfwithCollectionsbybrowsingChapter
5.Ontheotherhand,ifyouarelookingforasurveyofsomeof
themajorprojectsinJakartaCommons,readthisbookfrom
starttofinish.Partstructuredreference,partprose,the


cookbookformatletsyoucustomizeyourreadingexperience,
andIhopethisbookisasinterestingtoreadasitwastowrite.


What'sInside
ThisbookcoverscomponentsfromJakartaCommons,afew
projectsfromJakarta,andoneprojectoutsideoftheApache
SoftwareFoundation.Thisbookcoversthefollowing
components:
JakartaCommonsBeanUtils

JakartaCommonsBetwixt
JakartaCommonsCLI
JakartaCommonsCodec
JakartaCommonsCollections
JakartaCommonsConfiguration
JakartaCommonsDigester
JakartaCommonsHttpClient
JakartaCommonsID
JakartaCommonsIO
JakartaCommonsJEXL
JakartaCommonsJXPath
JakartaCommonsLang


JakartaCommonsLogging
JakartaCommonsMath
JakartaCommonsNet
ApacheLog4J
JakartaVelocity
FreeMarker
JakartaLucene
JakartaSlide
Alloftheseprojectsarecoveredindetailinthefollowing
chapters.Here'swhat'sineachchapter:

Chapter1,SupplementstotheJava2Platform
ThischapterintroducesCommonsLang.Automationof
toString(),workingwitharrays,formattingandrounding
dates,workingwithenumerations,generatingidentifiers,
andmeasuringtimearesomeofthetopicsdiscussedinthis

chapter.Thischapteralsocoversthegenerationofunique
identifierswithCommonsID.

Chapter2,ManipulatingText
WhileJavadoesnothavetheextensivetextmanipulation
capabilitiesofascriptinglanguagelikePerl,Commons


Lang'sStringUtilshasanumberofutilitymethodsthat
canbeusedtomanipulatetext.Thischapterdealswith
StringUtils,WordUtils,andCommonsCodec.

Chapter3,JavaBeans
BeansappearthroughoutJava;fromJakartaStrutsto
Hibernate,beansareaunitofinformationinanobject
model.ThischapterintroducesCommonsBeanUtils,oneof
themostwidelyusedcomponentsfromJakartaCommons.

Chapter4,Functors
Functorsareafundamentalwayofthinkingabout
programmingasasetoffunctionalobjects.Commons
Collectionsintroducedpredicates,transformers,and
closures,andfunctors,whichcanbeusedtomodelcontrol
structuresandloops.Thischapterdemonstrateshowone
wouldapplyfunctorstoanyprogram.

Chapter5,Collections
Iterators,filteringwithpredicates,buffers,queues,
bidirectionalmaps,type-safecollections,constraining
collections,lazymaps,andsetoperationsareafewofthe

topicsintroducedinthischapter.Thischapterdealswith
CommonsCollections,newcollectiontypesintroduced,and
theapplicationoffunctorstovariouscollections.

Chapter6,XML


IfyouareconstantlyparsingorcreatingXMLdocuments,
thischapterintroducessomealternativestothestandard
parserAPIs(SAX,DOM,andJDOM).Thischapterintroduces
CommonsDigester,CommonsBetwixt,andCommons
JXPath.

Chapter7,ApplicationInfrastructure
CommonsConfigurationisintroducedasawaytoparse
propertiesfilesandXMLconfigurationfiles.Otherrecipesin
thischaptershowhowCommonsCLIcanbeusedtoparse
acomplexsetofrequiredandoptionalcommand-line
options.Thischapteralsodetailstheconfigurationanduse
ofCommonsLoggingandApacheLog4J.

Chapter8,Math
Thischapterfocusesonsimplemathematicalcapabilitiesin
bothCommonsLangandCommonsMath.Thischapter
introducesclassestoworkwithfractions,complexnumbers,
matrices,andsimpleunivariatestatistics.

Chapter9,Templating
Thischapterdealswithsimpleexpressionlanguagessuch
asCommonsJEXLtomorecomplextemplatingengines

suchasJakartaVelocityandFreeMarker.Thischapteralso
demonstratestheintegrationofbothVelocityand
FreeMarkerwithaJ2EEservletcontainersuchasJakarta
Tomcat.


Chapter10,I/OandNetworking
ThischapterintroducesCommonsIO,whichcontainsa
numberofutilitiesforworkingwithstreamsandfiles,and
CommonsNet,whichcontainssimpleclientsfortheFTP,
POP,andSMTPprotocols.

Chapter11,HTTPandWebDAV
IfyouneedtocommunicatewithanythingoverHTTP,read
thischapter,whichdealswithJakartaHttpClientandthe
WebDAVclientlibraryfromJakartaSlide.

Chapter12,SearchingandFiltering
CommonsJXPathcanbeusedtoapplyXPathexpressionsto
collectionsandobjectgraphs.JakartaLuceneisafully
functionalsearchenginethatcanindexanystructured
document.ThischapterdemonstratestheuseofLucene
withCommonsDigester.
Limitedtimeandresourcesforcedmetomakesomedecisions
aboutwhichprojectstoincludeinthistext.Projectslike
Velocity,FreeMarker,andLog4J,whilenotCommons
components,wereincludedbecausetheyfitthemoldofa
small,easilyreusablecomponent.OtherCommonscomponents
werenotincludedinthisbookbecausetheywerestillbeing
developedatthetimeofwriting,orbecauseashortrecipe

wouldhavebeenimpossiblewithoutadetailed30-page
introduction.CommonsDbUtils,DBCP,Discovery,Jelly,
Launcher,Modeler,Pool,Primitives,Chain,andpromising
sandboxcomponentscouldfillanotherentirevolume.Some
projects,suchasJakartaHiveMind,startedascomponentsin
theCommonsSandboxonlytobepromoteddirectlyto


subprojectstatusoftheJakartaproject.Classificationof
projectsandcomponentsinJakartacanalsobesomewhat
arbitrary;JakartaOROandJakartaRegExpwouldbothseemto
beprimecandidatesfortheJakartaCommons,buttheyare
bothsubprojectsofJakarta.Otherprojects,suchasJakarta
CommonsHttpClient,haverecentlybeenpromotedtobe
subprojectsofJakarta,leavingtheCommonsentirely.Thinkof
thisbookasfocusingonJakartaCommonswithsomeother
projectsthrownintolivenupthediscussion.Iapologizein
advanceifIleftyourfavoriteprojectout.
Writingabookaboutaseriesoffrequentlyreleased
componentsisreminiscentofagamecalledwhack-a-mole.Just
whenyoufinishupdatingachapterforanewrelease,another
componenthasarelease.Onaverage,onecommons
componentisreleasedeveryoneortwoweeks;therefore,a
fewoftheversionsinthisbookmaybeobsoleteassoonasthis
bookhitstheshelves.Ingeneral,JakartaCommonsmakesa
concertedefforttopreservebackwardcompatibilityandkeepa
stablepublicinterface.LessonslearnedonCommonsBeanUtils
1.6shouldremainapplicabletoCommonsBeanUtils1.7.Ifyou
findthatamorerecentversionofacomponenthasbeen
released,youshoulddownloadthatmorerecentversionand

checktheO'Reillysiteforupdatesrelatedtothisbook.


ConventionsUsedinThisBook
I'lluseanumberofconventionsyoushouldknowaboutinthis
book.Forexample,menuitemsareseparatedwithan like
this:File New Project.Tomakethemstandout,newlinesof
codewillbedisplayedhighlightedwhenthey'readded.Example
codeisoftenpresentedoutofcontext;insteadofdevelopingan
entireclass,onlytherelevantblockofcodeispresented.Most
exampleswillincludethenecessaryimportstatementsfor
Commons-relevantclasses,andotherimportstatementswill
beimplied.Whencodeisomittedorimplied,itwillbe
representedbyellipses:
importorg.apache.commons.digester.Digester;
...
Digesterdigester=newDigester();
digester.doSomething();

Inaddition,thefollowingtypographicalconventionsarealso
usedinthisbook:

Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,directories,andUnixutilities.

Constantwidth


Indicatescommands,options,switches,variables,types,

classes,namespaces,methods,modules,properties,
parameters,values,objects,events,eventhandlers,and
XMLtags.

Constantwidthitalic
Showstextthatshouldbereplacedwithuser-supplied
values.

Constantwidthbold
Highlightsimportanttextwithincodeexamples.

Thisiconsignifiesatip,suggestion,orgeneralnote.

Thisiconindicatesawarningorcaution.


WhatYou'llNeed
Toexperimentwiththevariouslibrariesintroducedinthisbook,
youwillneedtheJ2SE1.4SDK,whichcanbeobtainedfrom
.Theexamplesinthisbookwere
developedinanIDEnamedEclipse,whichcanbedownloaded
fromtheEclipseprojectsiteat.Each
chaptercontainsinstructionsfordownloadingthevarious
JakartaCommonscomponents;todownloadanycomponent
fromJakartaCommons,gototheJakartaCommonspageat
andclickon"Binaries"
under"Download"intheleftmenu.


TheJakartaCommonsCommunity

TheJakartacommunityandthelargercommunityofthe
ApacheSoftwareFoundationiscommittedtodevelopingopen
sourcesoftware.TheApacheSoftwareFoundationisanonprofit
corporationregisteredinDelawarethatsupportsongoing
collaborativesoftwaredevelopmentaccordingtoasetofsimple
ideals:transparency,meritocracy,consensus,andmutual
respect.Tolearnmoreaboutthefoundation,startatthe
FrequentlyAskedQuestionspageonwww.apache.org
(Jakartaisa
projectundertheApacheSoftwareFoundation,anditis
managedbywhatisknownasaProjectManagement
Committee(PMC).Thiscommitteemanagesanumberof
JakartasubprojectsincludingtheJakartaCommons.
TheJakartacommunityandApacheXMLcommunitybothhad
tremendousgrowthspurtsfrom1999to2003,withboth
projectsbecomingdominantforcesinopensourceJava.
Tomcat,Struts,Xerces,Xalan,Ant,Cocoon,andotherprojects
wereembracedbythelargercommunityandJavadevelopeda
verystrongassociationwithopensourcebecauseofthe
influenceofJakarta.Towardtheendofthisgrowthspurt,the
corporatestructureofApacherequiredacertainlevelof
oversightandaccountability,whichcouldnotbeachievedinan
umbrellaprojectlikeJakartawithhundredsofcommitters.A
decisionwasmadetoencourageJakartasubprojectstomove
towardsmaller,morefocusedPMCs.Oneofthefirstprojectsto
leaveJakartawasApacheAnt,andotherprojectssuchas
Maven,Struts,andLog4jfollowedsuit.Thisnew,morenimble
approachtothestructureofcollaborativesoftwaredevelopment
avoidsthecreationofamanagementlayerbetweenproject
participantsandthePMC.Apacheismakingwayforanew

generationofprojectsthatwillsetthestandardforopensource
Java,includingGeronimo,Pluto,Directory,Derby,andAxion.Be


awarethatthestructureofprojectsandsubprojectsinJakarta
issomewhatfluidatthemoment,and,asthesituationevolves,
certaincomponentscouldbesplitoffintoseparateApache
projects.
Ifyoufindthecomponentsinthisbookhelpful,Iencourageyou
totakesometimetoobservethecommons-devdeveloper
mailinglist.TheASFis(mostly)transparent,andthismeans
thatthegeneralpublichasawindowintothecollaborative
developmentprocessthatisusedtocreatealargebodyof
greatsoftware.Iwouldencourageanydevelopertotakean
interestinapieceofsoftwareandwatchthedevelopment
process.Followthedecisions,releases,arguments,flame-wars,
andevolutionofsomethinglikeJakartaCommonsandyoucan
seeforyourselfwhatworksandwhatdoesn'twork.Thisisalso
agreatwaytokeepyourselfinformedofthechangesand
directionofcertainprojects.
Idon'tintendtospeakforthiscommunity,and,honestly,no
onecanspeakforagroupasdiverseastheonethathas
formedaroundJakartaCommons.Iwantedtowritethisbookto
helpattractmorepeopletotheconceptofJakartaCommons
andtotakesometimetoencouragepeopletothinkabouthow
theycouldcontributetothateffort.Iftherearemorepeople
payingattentiontothesoftware,Commonscomponentswill
havehigherquality,morebugreportswillbefiled,andmore
peoplemighttakesometimetosubmitdocumentationpatches.
IfyoufindJakartaCommons(oranyotherApachesoftware)

useful,youshouldconsidertakingalittlebitoftimetohelpa
fellowuserontheusermailinglistorsubmitdocumentation
patches.Ifyoufindatypoorabug,fileareportonApache's
Bugzillainstallation(orJira
installation( />Thereisalwaysaneedforgreaterunittestcoverage,andany
timeyoufindaninconsistencyincodeyoushouldfileabug.
Contributionscancomeinmanyformsansweringuser
questions,writingdocumentation,writingunittests,submitting


patches,orprovidingfeedback.Allofthesecontributionshelp
sustainalivingcommunity.Ifyoufindyourselfunableto
participateinthecommunity,youcanmakeasmall(possibly
tax-deductible)donationtotheApacheSoftwareFoundationto
helpoffsetthecostofinfrastructureandbandwidth
( />

TheApacheSoftwareLicense
EverythinginthisbookiscoveredbytheApacheSoftware
License2.0(exceptFreeMarker,whichiscoveredbyasimilar
BSD-stylelicense).Alldeveloperswhotouchopensource
shouldbefamiliarwiththevariouslicensesandcometotheir
ownconclusions;mostimportantly,youshouldbecomefamiliar
withtheApachelicense(andotherBSD-stylelicenses)andhow
itdiffersfromtheGNUGeneralPublicLicense(GPL)andGNU
LesserGeneralPublicLicense(LGPL).ReadtheApache
SoftwareLicense2.0at />Iamnotalawyer(IANAL),butIwouldurgeyoutolearnas
muchasyoucanabouttheselicensesbeforeyoustarttouse
them.Formoreinformationaboutopensource,andfora
comprehensivelistoflicenses,seetheOpenSourceInitiative

(OSI)at.TheApachelicensedoes
notplacerestrictionsonpeopleororganizationsthatwishto
redistributethesoftwareitcovers,and,ingeneral,theApache
licensecreatesfewerlicensingheadachesforindividualsand
organizationsthatwanttoincorporateopensourcesoftware
intoacommercialproduct.


×