0% found this document useful (0 votes)
2 views

Flex On Java 1st Edition Bernerd Allmon Jeremy Anderson pdf download

The document provides information about the book 'Flex on Java' by Bernerd Allmon and Jeremy Anderson, which focuses on building Rich Internet Applications (RIAs) using Adobe Flex and Java. It includes a detailed table of contents outlining various topics such as application structure, web services, BlazeDS remoting, and testing Flex applications. Additionally, it offers links to download the book and other related titles from the publisher, Manning Publications.

Uploaded by

adehheelan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Flex On Java 1st Edition Bernerd Allmon Jeremy Anderson pdf download

The document provides information about the book 'Flex on Java' by Bernerd Allmon and Jeremy Anderson, which focuses on building Rich Internet Applications (RIAs) using Adobe Flex and Java. It includes a detailed table of contents outlining various topics such as application structure, web services, BlazeDS remoting, and testing Flex applications. Additionally, it offers links to download the book and other related titles from the publisher, Manning Publications.

Uploaded by

adehheelan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Flex On Java 1st Edition Bernerd Allmon Jeremy

Anderson download

https://ebookbell.com/product/flex-on-java-1st-edition-bernerd-
allmon-jeremy-anderson-34416118

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Pro Flex On Spring 1st Edition Chris Giametta Auth

https://ebookbell.com/product/pro-flex-on-spring-1st-edition-chris-
giametta-auth-4390884

Flexible Rails Flex 3 On Rails 2 Peter Armstrong

https://ebookbell.com/product/flexible-rails-flex-3-on-rails-2-peter-
armstrong-1354962

Joe Weiders Flex Magazine February 2014 One On One With Wwe Diva
Natalya Grow Massive Legs Flex Lewis Training Guide To Huge Arms Brian
Shaw Shaw

https://ebookbell.com/product/joe-weiders-flex-magazine-
february-2014-one-on-one-with-wwe-diva-natalya-grow-massive-legs-flex-
lewis-training-guide-to-huge-arms-brian-shaw-shaw-22233232

Heterogeneous Integration Of Microwave And Millimeterwave Diodes On


Silicon And Flex Substrates Amanpreet Kaur

https://ebookbell.com/product/heterogeneous-integration-of-microwave-
and-millimeterwave-diodes-on-silicon-and-flex-substrates-amanpreet-
kaur-10850250
Maniac Monkeys On Magnolia Street When Mules Flew On Magnolia Street
Angela Johnson

https://ebookbell.com/product/maniac-monkeys-on-magnolia-street-when-
mules-flew-on-magnolia-street-angela-johnson-47511648

The Complete Dambusters The 133 Men Who Flew On The Dams Raid 1st
Edition Charles Foster

https://ebookbell.com/product/the-complete-dambusters-the-133-men-who-
flew-on-the-dams-raid-1st-edition-charles-foster-60016888

With God On Our Side Steven Flixjger

https://ebookbell.com/product/with-god-on-our-side-steven-
flixjger-59377170

Nuclear Engineering Handbook Hands On With Python Nuclear Engineering


Essentials 1st Edition Jamie Flux

https://ebookbell.com/product/nuclear-engineering-handbook-hands-on-
with-python-nuclear-engineering-essentials-1st-edition-jamie-
flux-201892700

Nazis On The Run Hitlers Henchmen Fled Justice Steinacher Gerald

https://ebookbell.com/product/nazis-on-the-run-hitlers-henchmen-fled-
justice-steinacher-gerald-55441072
www.it-ebooks.info
Flex on Java
BERNERD A L L M O N
JEREMY ANDERSON

11
M A N N ING

Greenwich
(74 ü w. l o n g . )

www.it-ebooks.info
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact

Special Sales Department


Manning Publications Co.
180 Broad St.
Suite 1323
Stamford, CT 06901
Email: [email protected]

©2011 by Manning Publications Co. All rights reserved.

N o part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

© Recognizing the importance of preserving what has been written, it is Manning's policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.

Manning Publications Co. Development Editors: Nermina Pascal-Miller


180 Broad St. Sebastian Stirling
Suite 1323 Copyeditor: Betsey Henkels
Stamford, CT 06901 Typesetters: Dennis Dalinnik
Cover designer: Marija Tudor

ISBN 9781933988795
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 - M A L - 16 15 14 13 12 11 10

www.it-ebooks.info
contents
foreword xi
preface xiii
acknowledgments xv
about this book xvii
author online xix
about the authors xx
about the cover illustration xxi

PARTI LAYING THE FOUNDATION 1

J Some Flex with yourJava? 3


1.1 A whirlwind tour of Flex 5
MXMLandActionScript 5' The Rex SDK 6
Flash Player 10 6

1.2 Creating an application in Flex 7


1.3 Finding the right tools and patterns 8
Building a Flex interface. 9 • Integrating with web
services 9 • Integration with BlazeDS, logging, and
messaging 10 • Securing Hex applica tions 10 • Crea ting
custom Flex controls with Dégrafa I I ' Desktop 2.0
with Adobe AIR I I ' Flex and Grails 11

1.4 Summary 11

www.it-ebooks.info
X CONTENTS

Beginning with Java 12


2.1 Working with AppFuse 13
2.2 Generating the application structure with Maven 13
Download and install the JDK 14 • Download and install
MySQL 15 • Download and install Maven 15 • Create a
Maven multimodule project 16 1 Maven provides a build able
project 18* Running the NexBugs web application 19

2.3 Build the model objects 20


2.4 Build the DAOs 23
2.5 Build the services 24
2.6 Wiring things together with Spring 2V
2.7 Constructing the web tier 28
Building Struts 2 action classes 28 • Editing the issue
menu item 30 • Adding JSP resources 30 • Adding
property resources 33 • Configuring the struts.xml 34
Configuring Hibernate 36

2.8 Summary 37

Getting rich with Flex 38


3.1 Generating the application structure 38
3.2 Configuring the flex-bugs-ria module 40
3.3 Configure Maven for the flex-bugs-web module 42
3.4 Adding a wrapper for our SWF 44
3.5 "Hello World!" in Flex 44
3.6 Developing the FlexBugs application 46
Introducing ViewStack 47 * HeaderView 49 • FooterView
Master view 52 • Detail view 53 • Commen ts view 54

3.7 Laying out the components 55


3.8 Creating a pop-up component 57
3.9 The finished application 58
3.10 Summary 59

Connecting to web services 60


4.1 Model View Presenter 61
4.2 Web services in Flex 62
4.3 Dispatching and handling events 63
Creating a custom ei>ent, 63 • Event, dispatching 64

www.it-ebooks.info
CONTENTS vii

4.4 Creating Issue and Comment transfer objects 65


4.5 Enhancing the master view 66
Creating a Presenter for the master view 67 * Creating an
Issue Model 69 • Updating the master view 70

4.6 Enhancing the detail view 72


Creating a DetailPresenter 72 • Updating the
IssueModel 75 • Updating the detail view 76

4.7 Enhancing the comments view 77


Creating a comments presenter 77 • Creating a
comment model 80 • CommentView 81

4.8 Adding a pop-up form for editing comments 83


Updating the CommentPresenter 83 • Updating the
CommentModel 85 • Creating the pop-up
component 85* Updating CommentsListView 87

4.9 Summary 88

PART II BLAZEDS REMOTING 89

5 BlazeDS remoting and logging 91

5.1 Introducing BlazeDS 92


5.2 Getting BlazeDS 93
5.3 Building a BlazeDS configuration Maven module 94
Configuring BlazeDS 96
5.4 Exposingjava services to Flex remoting 100
Web module configura tion upda tes 100 • Expose AMF
remoting destinations 102

5.5 Connecting to Java with BlazeDS 104


5.6 Logging 105
BlazeDS logging 105 • Built-in BlazeDS benchmarking 107

5.7 Summaiy 110

Flex messaging 112


6.1 Setting up BlazeDS for messaging 113
Modifying the:services-config.xml 113 • Updating the
webapp server-side module 114

www.it-ebooks.info
viii CONTENTS

6.2 Modifying the client for messaging 117


Creating a ChannelSetFactory 117 • Changing
the IssueModel 118

6.3 Summaiy 120

PART I I I THE JOYS OF FLEX ON JAVA 121

7 Securing and personalizing your application 123


7.1 Authentication 124
Modifying the ChannelSetFactory 124 • Creating a
UserEvent 125 • Creating a login panel 126 • Creating a
login Presenter 128 • Creating a login manager 130
Upda ting the header 131 • Enabling security for Flex 132

7.2 Authorization 133


Hex Spring Security primer 133 • Spring Integration
Security 135 • @Secured annotations 135
Overriding default security settings 137 • Updating
IssueModel and CommentModel 138

7.3 Personalization 139


Adding the• UserServiceto the: LoginModel 140 • Updating
the LoginPresenter 141 • Updating the DetailPresenter
and CommentsListPresenter 142

7.4 Summaiy 145

8 Charting with Degrafa 147


8.1
8.2
Drawing in Flex 148
Common Degrafa concepts 149
8.3 Creating a pie chart for fun and profit 150
New custom ei>ent. 151 • PieChart component 152
PieChartSlice 154 • Custom ItemRenderer 155 • Presenter
for the PieChart 156 • Model for the PieChart, 158

8.4 Adding your pie chart to the application 159


Updating the GraphView 159 • Creating a Presenter for
the GraphView 161 • Creating the graph model 163

8.5 Beyond the example 165


8.6 Summaiy 167

www.it-ebooks.info
X CONTENTS

Desktop 2.0 with AIR 168


9.1 Creating a common library 169
Creating an SWC project 170 ' Extracting common
classes 172 ' Extracting a MainCanvas 172

9.2 Creating the AIR application 174


9.3 Packaging the AIR application 176
Crea ting a project to package the AIR app 177 * Genera ting
a certificate 177 * Adding icons 178 * Adding the AIR
configuration 179 * Configuring the package build 180

9.4 Distributing the AIR application 186


Assembly configuration 187 * Updating the
build 187 * Creating a download badge 189

9.5 Summaiy 191

Testing your Flex application 192


10.1 Unit testing and TDD 193
10.2 Updating the project 194
10.3 Testing the Presenter 196
Testing refresh issues 198* Issues result event
test 199* Testing issue removed 200
Remove issue result test 201

10.4 Testing the View 202


Testing the issues set property 203 * Testing resetlssueGrid
function 204 * Testing refresh issues button click 204
Testing DataGrid item select 205

10.5 Testing the Model 206


Mocking and Remote-Object 207 * Testing
getlssues 209 * Testing get single issue 209

10.6 Continuous integration with Hudson 210


Downloading and installing Hudson 211 * Configuring
Hudson 211 * Con figuring a Hudson job 214

10.7 Summaiy 217

Flex on Grails 218


11.1 Why Groovy and Grails? 218
11.2 Downloading and installing Grails 219

www.it-ebooks.info
X CONTENTS

11.3 Creating the Grails application 220


Create the Contact domain model 221 • Create the
ContactService 222 • Bootstrap sample data 223

11.4 Getting rich with Flex 223


Installing the Flex plugin 223 • Creating the domain classes
in Flex 224 • Creating the Flex application 225 • Adding the
RemoteSeruice 228 • Putting it all together 228

11.5 Install the Grails JMS and ActiveMQ plugins 229


11.6 Add the ActiveMQ Spring bean 230
11.7 Subscribe the Flex client to the Grails JMS service 230
Update the services-config.xml 231 • Modifying the
ContactService 232 • Update the Main, mxml 233

11.8 Summary 234

index 235

www.it-ebooks.info
foreword
Every ten to fifteen years there is a radical software paradigm shift. Many of us experi-
enced die last shift as die web gained momentum and software was rebuilt f o r a new
and game-changing deployment model. Today we are in die midst of anodier great
software paradigm shift. User and business needs now require software to be more
usable, extensible, and portable.
Rich Internet Applications (RIAs) represent a new generation of software. As the
name implies, RIAs provide users with a rich and interactive experience. A t the same
time, they o f f e r the ease of deployment that made early web applications so successful.
RIAs are the future of software because they combine the strengths of the web deploy-
ment model with the full client capabilities of thick-client software.
Since 2004 A d o b e Flex has been die most prolific toolkit f o r building RIAs. A pri-
mary advantage of Flex for RIA development is that it integrates easily with any back-
end technology. By providing native XML, SOAP, and Data Remoting capabilities, Flex
enables developers to build rich new UIs on top of existing services. For Java develop-
ers this combination is especially compelling because many Java systems have already
embraced service-oriented architectures with SOAP W e b Services, Spring, or one of
numerous other technologies.
T h e union of Java on the backend and Flex on die frontend is so powerful that
hundreds of thousands of developers have already embraced this new paradigm to
create better software. You've probably picked up this book because you want to do
the same tiling—build better software. W e all want to build software that we are proud
of—software that users will love. Flex on Java will teach you how to d o just that.

xi

www.it-ebooks.info
xii FOREWORD

T h e r e are many aspects to building great software. If software looks sexy but does
not p e r f o r m well or is not maintainable, its value is diminished. W h a t I love about this
b o o k is that it teaches a holistic approach to building great software with Flex and
Java. As you would expect, you will learn how to create rich data visualizations. But,
just as importantly, you will learn how to efficiently move data between the client and
server using BlazeDS, set up unit tests, add security to an application, and more. These
are the problems we have to solve in real software. Knowing how to address these fun-
damental issues frees us to focus on what matters most—creating software that users
will love.
These are exciting times f o r software developers! Today we are building the next
generation of software—a generation that will be r e m e m b e r e d as the first to be
usable, beautiful, and truly helpful. Flex on Java empowers you to create that future! I
look forward to seeing the future that Y O U build with Flex and Java.

JAMES WARD
TECHNICAL EVANGELIST FOR FLEX AT ADOBE
www.jamesward.com

www.it-ebooks.info
preface
If you'd asked me a few years ago if I'd ever write a book, I would have laughed at the
thought. All through high school and college I loathed writing anything more than a
short answer, and when it came to writing papers, I was usually one of the people ask-
ing about the minimum length required f o r a passing grade. N o w here we are, thou-
sands of words and hundreds of pages later, and BJ and I have survived writing our
first book, twice.
So how did I g o f r o m absolutely loathing writing to being willing to dedicate so
many nights and weekends to writing this book? Since the first 1.0 release of the Flex
framework, I've been a fan. I discovered Flex while I was distaining HTML/JavaScript
and browser compatibility issues. I was trying to prototype a form-heavy application
with complex business rules and validation, struggling with g o o f y layout issues and
JavaScript errors, and was looking f o r a better solution. Although it's possible to make
rich web applications using HTML and JavaScript, it's easy to make ugly ones. Most of
the nice AJAX frameworks we take for granted today didn't exist at the time, and many
developers had absolutely no idea what AJAX was.
O n e night, while searching for an alternative, I ran across this excellent framework
that allowed you to write Flash-based applications using a declarative syntax and a pro-
totyping scripting language similar to JavaScript, without the cross browser issues
because it all ran in the Flash Player. So I picked up a copy of Developing Rich Clients
with Macromedia Flex by Steven Webster and Alistair M c L e o d and immediately fell in
love with the Flex framework. T h e r e was only one problem: it was expensive. It was
going to be a hard sell f o r any but the largest projects.

www.it-ebooks.info
xiv PREFACE

Flex effectively d r o p p e d o f f my radar as billable projects took precedence, and I


didn't have the time or desire to work o n any side projects. T h e n in 2007 A d o b e
announced that it would o p e n source the Flex framework and portions o f the Live-
Cycle Data Services server components as an o p e n source project of its own called
BlazeDS. W h e n I heard this announcement I figured it was time to start learning Flex
again. I had discovered a self-published b o o k called Flexible Rails, about integrating Flex
with Ruby o n Rails, and because I was already learning Ruby o n Rails, this b o o k was a
g o o d choice. So I purchased the PDF and a few short weeks later the author, Peter Arm-
strong, announced that M a n n i n g Publications was g o i n g to publish the book.
Being a Java developer f o r most o f my professional career, I began to think about
the lack of g o o d books on integrating Flex with a server-side backend. T h e r e was a
plethora of Flex books available on the market; however most were written f r o m the
perspective o f a Flash developer and used techniques that would make any seasoned
Java developer cringe. Few discussed connecting to either LiveCycleDS or BlazeDS. So
I proposed the idea of writing a b o o k on Flex f r o m a web developer perspective to
Michael Stephens at Manning.
T h e b o o k took many shapes. A t one time, we contemplated writing a b o o k on both
Java and .NET with Flex; we finally settled on an early version of what you now h o l d in
your hands. T h e main premise of the b o o k is that you can add a Flex f r o n t e n d to an
existing application. T h e first version of this b o o k attempted to use an existing o p e n
source Java w e b application as its sample application. W h e n we were about two-thirds
of the way through the book, we realized that the sample application wasn't working
as intended. W e ' d planned to have a sample application that would be m o r e than just
a throwaway. W e wanted the readers to develop an application that would incorporate
techniques they could apply to their everyday work, but not something so c o m p l e x
that it would distract readers f r o m what we were trying to accomplish—demonstrating
Flex and Java.
A f t e r much reflection and discussion o n the sample application, we decided to
scrap it and use AppFuse, an o p e n source platform f o r quickly building Java w e b appli-
cations, as the basis f o r our application. This allowed us to construct a sample applica-
tion in just one short chapter. AppFuse provided many functions out o f the b o x that
we would have otherwise had to spend time discussing and setting up. Unfortunately
this also meant that much of what we had already written had to be changed, but I f e e l
this was a necessary change f o r the better.
H e r e we are, two years later, with a final product that I can proudly say I h e l p e d to
write. I h o p e that you enjoy this b o o k and that it helps you in your j o u r n e y of integrat-
ing Flex into your everyday work.

JEREMY ANDERSON

www.it-ebooks.info
acknowledgments
This book would not have been possible if not f o r the hard work of many people.
W e ' d like to thank everyone at Manning, especially Maijan Bace and Michael Ste-
phens, f o r giving us the opportunity to write—and rewrite—the book. Without the
hard work and dedication of our development editors, Nermina Pascal-Miller and
Sebastian Stirling, this book would not have happened. Thanks f o r your guidance
and encouragement. Thanks to Karen Tegtmeyer, our review editor, f o r arranging
the peer reviews and to Stephen Hong, f o r helping to market and promote the book.
T h e rest of Manning's staff was patient and supportive and provided us with invalu-
able assistance to help make this book a success, in particular our copyeditor Betsey
Henkels and our proofreader Elizabeth Martin.
Special thanks go to Richard Dammkoehler f o r doing such an excellent j o b in his
technical review of the final manuscript shortly before it went to press.
W e ' d also like to express our thanks to Michael Kimsal f o r publishing a two-part
article based on the Grails chapter of this book in the excellent GroovyMag.
Thank you to Matt Raible for giving us AppFuse, which allowed us to build a sam-
ple application in just one short chapter, and f o r promoting our book in his travels.
Thanks to the A d o b e team f o r giving the Flex framework, BlazeDS, and more to
the open source community.
Thanks to Marvin Froeder (also known as V e l o ) for his hard work in developing
the FlexMojos Maven plugin, which we use extensively throughout the book.
Thank you to Giacomo "Peldi" Guilizzoni, founder of the outstanding Balsamiq
Mockups tool (a fine example of an A d o b e AIR application) f o r providing us with

xv

www.it-ebooks.info
xvi ACKNOWLEDGMENTS

licenses. Many of die mockups you see as illustrations throughout this book were cre-
ated using this tool.
Thanks to the following reviewers who read die manuscript at different stages of its
development and contributed invaluable feedback: Jeremy Flowers, Sopan Shewale,
Rick Evans, Christophe Bunn, Phil Hanna, Nikolaos Kaintantzis, John Griffin, Doug
Warren, Brian Curnow, and Peter Pavlovich. Thanks also to everyone who contributed
on die MEAP forum.
Last but not least, thank you to James Ward for contributing the foreword to
our book.

Jeremy Anderson
F d like to thank God f o r blessing me with the talent necessary to write this book.
Second only to God is my wife Karla, who had the patience to see me through this
and keep me on task. T o my children, Emily and Isaac, thanks for allowing Daddy to
hide in his basement office to write. Without their support, understanding, and sacri-
fice, this book would not have been possible.
Next, big thanks to my coauthor and partner in crime, BJ. If he hadn't j o i n e d me
on this venture, there might not have been a Flex on Java.
Thanks to everyone at Pillar Technology, especially Gary Gentry, Bob Meyers, Chris
Beale, Patrick Welsh, Matt VanVleet, Rich Dammkoehler—and everyone else who pro-
vided support.
Thank you to Carl Erickson and everyone at Atomic Object f o r helping me solidify
my interpretation of die Passive View pattern in the sample application.

BJ Allmon
Thanks to my God and Father in heaven who is the author of life. Your love
endures forever.
I ' m humbled by the patience and die love demonstrated to me by my wonderful
bride Sarah and our kids Hannah, Zacharee, Elliot, and Jennessee. Thank you for
allowing me to steal precious time away to work on this book. I love you so much!
Without my coauthor Jeremy Anderson's talent and thoughtfulness, I wouldn't
have been able to contribute to this project. Thank you Jeremy f o r your hard work in
leading this project!
Others who have helped me along in m y j o u r n e y include Bob Myers, Christopher
Judd, Kevin Smith, Charlie Close, Gary Gentry, Richard Dammkoehler, Matt VanVleet,
Randy Thomas, and Dan Wiebe; die many talented developers at Pillar Technology
Group including Mark Flickinger, Ankur Gupta, Beth Seabloom, and Shawn Steinb-
runner; the wonderful staff at Mettler-Toledo; die entire staff at Click4Care; the Dela-
ware City Vineyard, Vineyard Church Delaware County, Vineyard Columbus; and my
extended family.

www.it-ebooks.info
about this book
T h e r e are many books available that are purposed f o r teaching technology topics
inside and out. These books are necessary f o r understanding how to use a technology
correctly but many times are not meant to teach you what a normal day of a develop-
ment would look like using that technology. This book was written to demonstrate prac-
tical development with two powerhouse technologies, Flex on Java. It will guide you in
building your own applications that scale f o r real-world business needs, leaving you
feeling equipped with the fundamentals that are pertinent to the software feature or
task at hand.
Throughout the book, the fundamentals of building testable and rich UIs that
communicate with a powerful server side are brought together in bite-sized chunks.
T h e topic of building a robust Flex client that sits on top of a Java server-side applica-
tion will be discussed throughout as it pertains to the integration of the two and pass-
ing data back and forth.
A l o n g with the main topic of integrating Flex with Java, topics such as Maven,
Spring integration, adding security and personalization, charting, messaging, AIR
desktop applications, logging, continuous integration, AppFuse, and even Flex on
Grails will be demonstrated.

Who should read this book


This book is geared toward developers with a need for creating rich applications, on a
budget, with Flex 4 and Java. All the tools we use f o r our examples are open source or
free and very proven.

xvii

www.it-ebooks.info
xviii ABOUT THIS BOOK

This book assumes familiarity with software development in general, specifically


Flex and Java. T h o u g h it was written with the intent to teach integration techniques
f o r Flex and Java, not language fundamentals, it was done so to make it easy f o r even
Flex or Java beginners to get rolling quickly with both.

How the book is organized


Flex on Java is made up of three parts:

• Part 1 Getting started


• Part 2 Strengthening the backend
• Part 3 Going above and beyond

W e start off by introducing the two technologies and building a sample Java applica-
tion you can play with. W e g o on to build a Flex client f o r the Java application that ties
into some Java web services. Part 1 covers the first four chapters.
In chapters 5 and 6 we dive deeper into backend integration with Java on the
server side. Part 2 introduces topics that allow Flex to connect to Java through object
remoting, logging, and messaging. Using the Spring Framework f o r Flex integration is
very powerful and we demonstrate how that can be done.
Part 3, chapters 7-11, covers topics that are o f f the beaten path, such as security
and personalization, building graphs, desktop development with AIR, unit testing, and
building a Flex and Grails application.

Code conventions
All source code in listings or in text is in a f i x e d - w i d t h f o n t l i k e t h i s to separate it
f r o m ordinary text. Code annotations accompany many of the listings, highlighting
important concepts. In some cases, numbered bullets link to explanations that follow
the listing. A t times, only the important segments of a code listing are displayed on the
page. T h e source code f o r all of the examples in full can be downloaded f r o m the pub-
lisher's website atwww.manning.com/FlexonJava.

www.it-ebooks.info
Author Online
T h e purchase of Flex on Java includes free access to a private forum run by Manning
Publications where you can make comments about die book, ask technical questions,
and receive help f r o m die autiiors and otiier users. To access and subscribe to die
forum, point your browser to www.manning.com/FlexonJava. This page provides
information on how to get on the forum once you are registered, what kind of help is
available, and the rules of conduct in the forum.
Manning's commitment to our readers is to provide a venue where a meaning-
ful dialogue between individual readers and between readers and die autiiors can
take place. It's not a commitment to any specific amount of participation on the
part of the autiiors, whose contribution to the book's forum remains voluntary
(and unpaid). W e suggest you try asking die authors some challenging questions,
lest their interest stray!
T h e Author Online forum and die archives of previous discussions will be accessi-
ble f r o m die publisher's website as long as the book is in print.

xix

www.it-ebooks.info
about the authors
JEREMY ANDERSON is a software developer f o r Pillar Technology Group, an A g i l e con-
sulting f i r m in the Michigan and O h i o Valley region. H e is a self-proclaimed autodi-
dact, constantly tinkering with cutting edge technologies such as Groovy, Grails, and
Flex. He's b e e n developing web-based applications o n the JVM in one shape or
another f o r over five years. W h e n he's not sitting behind a keyboard hacking away at
code, you can usually find him out o n the single-track on his bike or sometimes even
on foot. H e sometimes has time to update his b l o g http://blog.code-adept.com.

BJ ALLMON is a software developer f o r Pillar Technology Group. H e enjoys participat-


ing in local user groups and conferences and b e c o m i n g a m o r e seasoned software
practitioner. W h e n he is n o t dabbling in software d e v e l o p m e n t he can be f o u n d
spending time with his family o f six and playing the six-string.

xx

www.it-ebooks.info
about the cover illustration
T h e figure on the cover of Flex on Java is a "Soldier." T h e illustration is taken f r o m a
collection of costumes of die Ottoman Empire published on January 1, 1802, by Wil-
liam Miller of O l d Bond Street, L o n d o n . T h e tide page is missing f r o m die collec-
tion and we have been unable to track it down to date. T h e book's table of contents
identifies die figures in both English and French, and each illustration bears die
names of two artists who worked on it, both of w h o m would no doubt be surprised
to find dieir art gracing die front cover of a computer programming book...two hun-
dred years later.
T h e collection was purchased by a Manning editor at an antiquarian flea market in
the "Garage" on West 26th Street in Manhattan. T h e seller was an American based in
Ankara, Turkey, and die transaction took place just as he was packing up his stand f o r
the day. T h e Manning editor did not have on his person the substantial amount of
cash that was required f o r the purchase and a credit card and check were both politely
turned down. Witii die seller flying back to Ankara tiiat evening the situation was get-
ting hopeless. What was die solution? It turned out to be notiiing more than an old-
fashioned verbal agreement sealed witii a handshake. T h e seller simply proposed that
the money be transferred to him by wire and die editor walked out witii the bank
information on a piece of paper and the portfolio of images under his arm. Needless
to say, we transferred die funds die next day, and we remain grateful and impressed by
this unknown person's trust in one of us. It recalls something that might have hap-
pened a long time ago.

www.it-ebooks.info
xxii ABOUT THE COVER ILLUSTRATION

T h e pictures f r o m the Ottoman collection, like the other illustrations that appear
on our covers, bring to life the richness and variety of dress customs of two centuries
ago. They recall the sense of isolation and distance of that period—and of every other
historic period except our own hyperkinetic present. Dress codes have changed since
then and the diversity by region, so rich at the time, has faded away. It is now often
hard to tell the inhabitant of one continent f r o m another. Perhaps, trying to view it
optimistically we have traded a cultural and visual diversity f o r a more varied personal
life. O r a more varied and interesting intellectual and technical life.
W e at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the
computer business with book covers based on the rich diversity of regional life of two
centuries ago, brought back to life by the pictures f r o m this collection.

www.it-ebooks.info
Part 1

Laying the foundation

J L a r t 1 lays the foundation of Flex on Java by touring Flex, Java, and other sup-
porting technologies that you will use throughout the book.
In these first four chapters, you will build a sample Java web application to
use with numerous code examples throughout the book. T h e Java web applica-
tion is built using a service-oriented architecture (SOA).
A f t e r making a whirlwind tour of Flex (chapter 1), your first step (chapter 2)
is to create a Java application that will expose web services you will later use to
connect to them f r o m a Flex client.
In chapter 3, you will create a Flex application and words like AppFuse, Flex
Mojos, and FNA enter your vocabulary.
T h e focus of chapter 4 is to continue building the client-side application and
you will begin building a Flex client that will connect to the Java web services
that you will choose to expose.

www.it-ebooks.info
Some Flex iimh
your JoBi?

This chapter covers


• A brief h i s t o r y of J a v a and Flex
• A w h i r l w i n d t o u r of Flex
• M X M L and A c t i o n S c r i p t

In 1995, Sun introduced the first Java platform and gave birtii to die applet which
allowed Java applications to run inside die browser with rich functionality and all
the benefits of die Java framework, including connecting to die server side. The
applet became hugely popular for a couple of years before its popularity waned
mainly because of problems surrounding die browser plugin.
Macromedia embraced the idea of having a dedicated runtime environment for
the browser, like die Java applet, and in 1997 released die Flash Player. Adobe has
since taken over die rights to die Macromedia suite of products and helped to
evolve what is now die Flex framework and development API.
Building features in an applet from scratch or even witii other rich imple-
mentations can be expensive compared to die simplicity of using die Flex frame-
work. Figure 1.1 displays a simple Java applet data grid next to a Flex data grid.
T h e Flex data grid right out of die box not only looks better tiian die applet, it's

www.it-ebooks.info
27 CHAPTER 1 Some Flex with yourJava ?

Spreadsheet

kim. a
IIHI' d I .. I — Euntpb
-icDac

R**«. l.r^^y Territory Rep Actual EltiAUl*


T & Sevthw**t
V &A

k|Q South«*tt M m Barbara J-ennm-gp 36865 <0000


Q *Outhw»»t Dana Hmn 29885 10000
¥ L3 Central California
[J Seuttivwit Central California Jo« Smith 291X4 aoooo
* U Nevada
• Northern California
• _j Southern Cahfornu

Figure 1.1 Comparing a Java applet DataGrid (left) to a Flex Advanced DataGrid

much m o r e functional with much less c o d e overhead. T h e Flex DataGrid and


AdvancedDataGrid c o m p o n e n t s provide built-in support f o r tasks such as sorting,
dragging columns, row highlighting, data nesting, and styling.
T h e Flash runtime provides lightweight graphics and animation capabilities in
manageable file sizes, making the player hugely successful across OSs and browser
platforms. T h e Flash runtime allows f o r rich applications to have true stateful experi-
ences and a high level o f security.

NOTE A stateful e x p e r i e n c e with Flex means that the client ( F l e x ) will man-
age or r e m e m b e r everything it needs to without having to: submit to the
server side, update and manage a session or request through H T T P , and
refresh the client side with updated data after a submit with data f r o m the ses-
sion or request.

In general, Java developers have successfully leveraged the principles o f object-


oriented p r o g r a m m i n g ( O O P ) to build extremely stable, testable, and extensible
applications. Flex has b e c o m e a rich internet application ( R I A ) solution f o r Java
developers because it n o t only bridges the gap between a solid server side and a
great UI, it is also built o n top o f OOP principles such as encapsulation, inheritance,
and polymorphism.
These advantages b e n e f i t other technologies besides pure Java, as you'll see in
chapter 11, w h e n we demonstrate Flex integration with Grails, o n e o f the hottest w e b
d e v e l o p m e n t platforms. W e ' l l build a simple contact m a n a g e m e n t system and learn
h o w to get rolling with Groovy and Grails development. Integrating Flex with Grails is
in many respects easier than integrating Flex with Java.
Flex d e v e l o p m e n t is n o w bolstered by many o f the benefits o f Java-like frameworks
f o r p e r f o r m i n g unit testing, functional testing, and continuous integration. T h e com-
bination o f Java and the Flex Software D e v e l o p m e n t Kit (SDK) allows developers new
to the business to start building applications immediately.

www.it-ebooks.info
A whirlwind tour of Flex 5

A thriving Flex o p e n source community can o f f e r Java developers GUI c o m p o n e n t s


as simple and as c o m p l e x as required. Most o f tiiese custom c o m p o n e n t s extend stock
Flex objects f o u n d in d i e Flex SDK. A d o b e m a d e Flex 3 o p e n source, and it n o w has
numerous community resources. T h e Flex SDK witii A d o b e ' s built-in charting compo-
nents is still commercial.
W e have chosen Flex 4 witii Java because o f the duality o f a rich and stateful
client in conjunction witii a p o w e r f u l server side. Also, Java is broadly used in d i e
mainstream and is d i e existing server-side p l a t f o r m f o r many Flex migration proj-
ects. A l t h o u g h there are alternative ways f o r d o i n g RIA development, Flex will most
likely prove to be the superior RIA framework because o f d i e simplicity and test-
ability it provides to developers. W e ' r e n o w ready to discuss some o f Flex frame-
w o r k features.

1.1 A whirlwind tour of Flex


It's time to take a p e e k at the c o m p o n e n t s we'll use throughout this book. W e
w o n ' t g o into too much detail about the components as that is b e y o n d d i e scope o f
this book. Instead, w e ' l l focus o n d i e usage o f c o m p o n e n t s and framework in real-
w o r l d development.

1.1.1 MXML and ActionScript


A t d i e heart o f every Flex application you'll f i n d a combination o f M X M L files ( X M L
files with the .mxml extension) and ActionScript classes. These two c o m p o n e n t s are
the basic building blocks o f d i e Flex framework. T h e Flex c o m p i l e r takes these files
and creates a small w e b f o r m a t (SWF) file, which is executed in the Flash Player.

MXML
M X M L is an XML-based markup language similar to H T M L / X H T M L . T h e M X M L syn-
tax, used to declaratively d e f i n e your application, has numerous tags f o r c o m m o n UI
objects, such as text input fields, radio buttons, and drop-down lists. It also has many
UI c o m p o n e n t s and layout c o m p o n e n t s that are c o m m o n in rich client development,
such as m e n u bars, tabbed panels, data grids, and navigational trees. In addition, it's
possible to build custom c o m p o n e n t s that extend existing ones or p r o d u c e something
completely d i f f e r e n t like the f l o w visualization chart. Figure 1.2, which was m a d e with
Degrafa, shows this function.
In chapter 8 w e ' l l be covering the Degrafa drawing API f o r Flex to create a pie
chart f o r a sample application.

ACTIONSCRIPT
ActionScript, and m o r e specifically ActionScript 3.0, is a dynamic scripting language
based o n d i e ECMAScript L a n g u a g e Specification, T h i r d Edition. It is c o m p o s e d o f
the language specification and d i e Flash Player API. It is similar to JavaScript in syntax,
so it should l o o k familiar to any e x p e r i e n c e d w e b developer. Unlike JavaScript, Action-
Script is c o m p i l e d into byte c o d e b e f o r e b e i n g executed, instead o f b e i n g parsed and
interpreted at runtime.

www.it-ebooks.info
6 CHAPTER 1 Some Flex with yourJava ?

Figure 1.2 Flow visualization chart

NOTE Dozens o f user controls, p o w e r e d by ActionScript, are available witii


Flex out o f the b o x . As we demonstrate later in tiiis book, existing c o m p o -
nents can b e e x t e n d e d to create your own custom components. Because your
application will always run inside d i e Flash Player, you d o n ' t have to worry
about cross-browser compatibility issues either. In chapter 8 w e ' l l g o over h o w
to utilize custom components in your Flex applications using ActionScript f o r
d i e purpose o f reuse.

ActionScript is a dynamically typed language similar to Pytiion or Groovy and does its
type checking at runtime instead o f at c o m p i l e time. You have d i e option o f directing
d i e c o m p i l e r to p e r f o r m type checking at c o m p i l e time by enabling strict m o d e o n d i e
compiler, but tiiis is n o t a g o o d substitute f o r a comprehensive set o f unit tests.
T h e Flex SDK and Flash Player are d i e two key elements in making a Flex applica-
tion c o m e to life.

1.1.2 The Flex SDK


T h e Flex 4 SDK comes in two flavors: d i e Free A d o b e Flex SDK and the Open
Source Flex SDK. Both contain everytiiing you n e e d f o r developing, optimizing, and
d e b u g g i n g Flex applications. T h e SDKs include d i e ActionScript and M X M L compil-
ers, tools f o r creating JavaDoc-like documentation, and d i e Flex Framework. T h e
only d i f f e r e n c e between d i e two is tiiat d i e Free A d o b e Flex SDK contains addi-
tional c o m p o n e n t s that enhance the Flex application, such as tools f o r advanced
f o n t encoding, tools f o r packaging A d o b e Integrated Runtime ( A I R ) applications,
and d i e Flash Player. These extra c o m p o n e n t s are n o t o p e n source but have b e e n
m a d e available by A d o b e . T o learn m o r e about the Flex SDK downloads visit http://
opensource.adobe.com/wiki/display/flexsdk/downloads.

1.1.3 Flash Player 10


O f course n o n e o f tiiis could be possible without the Flash Player 10 runtime. It is the
heart and soul o f every Flex application. A l t h o u g h Flash Player itself is n o t o p e n

www.it-ebooks.info
Creating an application in Flex 7

source, it has been free since its inception and can be found on nearly every computer
in the world. Flash Player gives your Flex applications the ability to execute in the
same manner and look the same no matter what browser your application runs in.
Because your Flex application runs inside Flash Player, you do not have to be con-
cerned with cross browser issues.

Adobe contributes ActionScript engine source to Mozilla


In November 2006, Adobe contributed the source code for its ActionScript virtual
machine to the Mozilla foundation, spawning the Tamarin project. Tamarin will sup-
port E C M A S c r i p t Edition 3 and be integrated into the SpiderMonkey project, Mozil-
la's next generation JavaScripting engine to be included with future versions of
Mozilla (https://developer.mozilla.org/en/Tamarin).

Because of the widely popular Flash Player and a powerful open source SDK, Flex is a
great fit for Java developers building rich clients.
Now comes the part we've all been waiting patiently for—we're going to create a
"Hello World!" styled application in Flex.

Creating an application in Flex


Let's start by modeling our directory structure, shown
a . J helloviofldaop
in figure 1.3, after the Maven default project struc-
- i j src
ture. This will prove useful because we're using Maven
1= roain
to build the FlexBugs sample application in chapter 2.
O flex
T h e sample application can be placed in a proj-
resources
ect directory such as C:\de\\projects for Windows, or B Q test
/home/<YOUR_USERNAME>/development for Linux. Q flex
The main source code location for our "Hello Q resources
World!" sample application will be contained in the
src/main/flex folder. Because ActionScript follows a Figure 1 3 The folder structure for
pattern similar to Java for packages, if your Action- our "Hello World!" application is
Script class belongs to the com. example package, the formatted for the Maven build
source for this class will be contained in the src/main/
flex/com/example folder. The src/main/resources
folder should contain any resources that belong to the application but are not com-
piled with the sources. For example, any configuration files or message bundles belong
in the resources folder. T h e src/test/flex and src/test/resources folders are identical
to the src/main/flex and src/main/resources folders respectively, except these folders
are for the test code of the application.
For the purpose of introducing Flex code, listing 1.1 demonstrates a trivial exam-
ple of a simple Flex application. We're going to create a single .mxml file that will
print the words "Flex 4 is Fun" as seen in figure 1.4.

www.it-ebooks.info
31 CHAPTER 1 Some Flex with yourJava ?

| File : ///C :/D ocum e.. .n-debug/t est.h t m I

Flex 4 is Fun Figure 1.4


A simple Flex application

As you can see there's n o t h i n g fancy h a p p e n i n g here and the code presented in list-
i n g 1.1 is also simple.

Listing 1.1 Main.mxml

<?xml version= "1.0" encoding= "utf-8" ?> < • - © XML document declaration
<s:Application <—.
xmlns : fx= "http: //ns. adobe. com/mxml/2009 " Q MXML application root
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:s="library://ns.adobe.com/flex/spark">

<s:layout>
<s:VerticalLayout />
</s:layout>

< fx:Style>
.helloText { Flex ess style support
padding-top:2 5px;
padding-left:25px;
font-weight: bold;
color: haloBlue;
}
</fx:Style>
<s:RichText styleName="helloText">
<s:text>
Flex 4 is Fun
1» RichText element

</s:text>
</s:RichText>
</s:Application>

If you've ever d o n e any w e b development, this should l o o k familiar. MXML, like


X H T M L , is n o d i i n g m o r e tiian X M L . A t the b e g i n n i n g o f d i e file you'll see d i e stan-
dard X M L declaration Q . N e x t you'll see d i e r o o t n o d e witii the d e f i n e d x m l
namespaces Q , which in most Flex applications will b e witiiin d i e <mx: A p p l i c a t i o n
element. In chapter 3, w e ' l l evolve this example by creating a nice Flex application. In
chapter 9, w h e r e we talk m o r e about A d o b e AIR, w e ' l l explain that d i e r o o t n o d e f o r
an A I R application is typically <mx:WindowedApplication>. Inside d i e < m x : A p p l i c a -
t i o n > e l e m e n t is a style e l e m e n t Q and a single R i c h T e x t e l e m e n t Q witii its text
attribute set to "Flex 4 is Fun".

Finding the right tools and patterns


As diis book's tide suggests, Flex on Java will focus o n Flex integration with Java. Witii
that in mind, we diligently searched f o r d i e p e r f e c t ingredients to equip you with d i e
right tools f o r real-world scenarios without overcomplicating tilings.

www.it-ebooks.info
Finding the right tools and patterns 9

W e ' r e n o t focusing o n t e a c h i n g j a v a , but we build a simple Java w e b application in


chapter 2. W e chose frameworks that should ease the Java learning curve necessary to
g e t a sample application up and running fast. W e w o n ' t dive d e e p into every part o f
Flex development. Instead, Flex on Java will provide you with simple yet p o w e r f u l
examples o f integrating the two technologies.
T h e r e f o r e , we'll b e tackling in detail the topics outlined in the sections that follow.

1.3.1 Building a Flex interface


O f t e n developers begin building naked UI c o m p o n e n t s without b e i n g connected to a
backend server and database. A disconnected Flex client can take advantage o f m o c k
data and allow developers to easily prototype the UI without the complexity o f exter-
nal dependencies.
This approach is demonstrated in chapter 3 w h e r e we create the beginnings o f a
rich UI f o r the FlexBugs sample application shown in figure 1.5.

1.3.2 Integrating with web services


W h a t may seem unfamiliar to you in this chapter is that w h e n we c o n n e c t to the server
side w e ' l l be m o d e l i n g our application using the Model-View-Presenter (MVP) design
pattern instead o f e m p l o y i n g the typical approach o f using the mxml tag e l e m e n t that
doesn't scale well f o r most applications. Using the MVP approach, all w e b services calls

Lo»n j

FlexBugs OsiaitVtew ( Gfa&ft Vte*

Shirty Saius
10:

Project [ i
De&Cfp
iDon: I

Sovony |

| Retrain US! |
Rftpor»3 By
Reported On: J3
Aasiflned To:
Efrbtiaiad HOLTS:

Add Ndw Convrtdfil Ed* U I Da;e» Commam . Acdisfrue | Can» Cf-anges j

Copyr«ill C 2009 Fie* On Java

Figure 1.5 The FlexBugs sample Flex application

www.it-ebooks.info
10 CHAPTER 1 Some Flex with yourJava ?

will b e w r a p p e d in a M o d e l object written in ActionScript. This makes changing d i e


implementation less painful.
C o n n e c t i n g to server-side services, event dispatching, and event handling are all
diings diat are critical to any Flex business application and are built into the core o f
d i e framework. That's why in chapter 4 w e ' l l demonstrate connecting to d i e Java
server side and h o w to leverage the p o w e r f u l Flex API f o r connecting to w e b services.
Plenty o f literature, including d i e Flex online documentation, covers the typical
approach o f connecting to services. In this book, w e ' l l create clean interfaces and
views as we build a well-designed Flex client that will scale o n demand.

1.3.3 Integration with BlazeDS, logging, and messaging


Until fairly recently if you wanted to connect your data-driven application to a Java-
based backend, your choices were fairly limited. You could expose your Java services
as X M L w e b services, eitiier as SOAP-based or RESTful and connect to d i e m tiiis way,
write your own custom marshaler/unmarshaler based o n the A d o b e AMF protocol,
or p o n y up big bucks f o r a license f o r A d o b e ' s LiveCycle Data Services. W i t h d i e
release o f Flex 3, A d o b e decided to spawn BlazeDS, an o p e n source p r o j e c t that con-
tains much o f d i e functionality specific to connecting Flex to a Java-based service.
Integrating Flex witii Java is what tiiis b o o k is all about. That's why chapter 5 will
demonstrate furtiier h o w to connect a Flex client m o r e direcdy to d i e server side
using d i e o p e n source BlazeDS framework. BlazeDS provides a mechanism f o r allow-
i n g Flex to call methods o n Java objects through binary serialization with d i e A c t i o n
Message Format o r AMF. This is much faster tiian what's possible witii w e b services or
X M L / H T T P ( s ) because it uses real objects and doesn't have to marshal X M L .
Because l o g g i n g is a critical c o m p o n e n t o f any application and d e v e l o p m e n t envi-
ronment, chapter 5 also covers BlazeDS l o g g i n g in detail.
Real-time messaging is an important feature in most enterprise applications. Chap-
ter 6 will demonstrate h o w to develop Flex applications diat take advantage o f simple
polling; in chapter 11 we'll discuss h o w to connect using Java Message Service (J MS).
T h e Flex framework provides an API diat enables distributed communication witii the
server side or communication between clients that is loosely c o u p l e d and asynchro-
nous. Flex has both a p o w e r f u l and simple API f o r handling messaging.

1.3.4 Securing Flex applications


Many technical books skip security, but it's always the elephant in d i e living r o o m
w h e n gathering requirements f o r an application. It's important to understand d i e
security issues o f Flex both to decrease risk and to minimize d i e cost o f what can be
o n e o f the most expensive features in any business application. Chapter 7 will d e m o n -
strate building authentication, authorization, and personalization with Spring Secu-
rity ( A c e g i ) integration.

www.it-ebooks.info
Summary 11

1.3.5 Creating custom Flex controls with Degrafa


Custom c o m p o n e n t s are first class citizens inside the Flex framework, and many
ActionScript frameworks take advantage o f this. O n e that really stands out is Degrafa,
which is a declarative graphics framework that provides a suite o f graphics classes.
D e g r a f a is o p e n source and can be used to build robust charts, tools, and other graph-
ical elements with less e f f o r t and complexity than other frameworks.
W e ' l l create a custom pie chart c o m p o n e n t that will be appropriately tied into our
sample application in chapter 8. W h i l e w e ' r e at it w e ' l l also demonstrate creating a
DataGrid ItemRenderer and p e r f o r m dynamic object creation.

1.3.6 Desktop 2.0 with Adobe AIR


A business sometimes can't live with the w e b alone, and w h e n a desktop client is the
best way to go, Flex goes beyond the w e b with A d o b e AIR. A Flex application can easily
b e p o r t e d to a desktop e n v i r o n m e n t with AIR. This is especially easy f o r well-designed
applications that allow f o r optimal reuse o f code. Chapter 9 will demonstrate h o w to
allow a Flex application to live in two worlds—by demonstrating h o w to package and
distribute an AIR application.

1.3.7 Flex and Grails


T h e Groovy p r o g r a m m i n g language is the first dynamic scripting language to b e
a d o p t e d as a standard through the Java Community Process 0 C P ) . T h e specification
f o r Groovy can be f o u n d u n d e r Java Specification Request (JSR) 241 at http://jcp.org/
en/jsr/detail?id=241. Groovy supports p o w e r f u l features that can be f o u n d in other
languages like Python, Ruby, and Smalltalk; Grails is a full d e v e l o p m e n t stack f o r
Groovy that provides a rapid d e v e l o p m e n t e n v i r o n m e n t f o r both server side and the
w e b that resembles and rivals the Ruby o n Rails ( R o R ) framework. W i t h Flex and
Grails you can quickly create a dynamic application that runs o n the JVM with much
less effort. Flex integration with Groovy and Grails is covered in chapter 11.

1.4 Summary
W h e t h e r you're e x p e r i e n c e d o r i n e x p e r i e n c e d in building w e b or desktop applica-
tions with Flex o n Java, this b o o k will teach you h o w to integrate Flex o n Java quickly
and effectively. C o m b i n i n g Flex with Java allows developers to provide rich UIs with
robust server-side technologies and does so with minimal e f f o r t and cost. Flex and Java
are p r o v e n technologies and have continued to be i m p r o v e d over time and used by
many companies around the world.
In chapter 2, we lay a f o u n d a t i o n by building a sample Java w e b application f o r use
throughout the majority o f the examples in the rest o f this book. This should b e use-
ful if you d o n ' t already have an application o r n e e d assistance in getting started with
setting up a Flex o n Java d e v e l o p m e n t environment. Setup-type chapters can f e e l
slightly mechanical because o f the d o w n l o a d i n g and installation they cover. W e ' v e
tried to keep it interesting and painless while using popular d e v e l o p m e n t environ-
m e n t frameworks that the majority o f you will b e pleased to see utilized.

www.it-ebooks.info
This chapter covers
• Generating the application structure with
Maven
• Building J a v a s e r v e r - s i d e domain o b j e c t s
and s e r v i c e s
• Building a simple JSP Ul

We'll begin by creating a Java application that will expose web services so we can
later connect to them from a Flex client. We have attempted to avoid tying die
book to a specific sample application by focusing more on the concepts and tech-
niques of using various frameworks and tools. This should allow you to pick a topic
in die book tiiat interests you and get rolling on it. We'll demonstrate many topics
by using an application built in tiiis chapter called FlexBugs. If you want to follow
the samples in die book you can download die full code listings on die book's web-
site at http://manning.com/allmon. You could also replace the application con-
tents with something tiiat's more meaningful to you by changing the domain
objects to manage whatever you want, like contacts or movie favorites.
Throughout die book, especially in tiiis chapter, we leverage a few Java frame-
works diat help to lighten die amount of work required to build a fully func-
tional web application. This chapter is a bit mechanical because we need to set up

12

www.it-ebooks.info
Generating the application structure with Maven 13

a d e v e l o p m e n t environment. A few downloads and installs must take place if you


choose to use our samples. Feel f r e e to browse through this chapter and skip what
you already know.
T h e Java frameworks used will help k e e p d e v e l o p m e n t to a m i n i m u m while
creating a sample application to w o r k with f o r integration purposes. This will allow
us to focus o n teaching and demonstrating h o w to build synergy between Flex
and Java.
W e ' r e building a Java application first as a basis f o r work in chapter 3, but you
can start witii Flex in chapter 3 if y o u ' d like o r m o v e around d i e b o o k as conve-
nient. T h e Java application comes first because we expect most readers to be refac-
toring existing applications to include a Flex client and tiiis will give you sometiiing
to play with quickly.
W e ' l l start by generating d i e project structure witii A p a c h e Maven, a convention-
over-configuration p r o j e c t m a n a g e m e n t framework. Maven will build d i e applica-
tion f o r us and speed up the d e v e l o p m e n t process. A f t e r we have a p r o j e c t structure
generated, w e ' l l start building the server-side components while leveraging MySQL
f o r d i e database.
For d i e Java server-side pieces, we'll start with creating plain old Java objects
(POJOs), Data Access Objects (DAOs), and service objects that will b e exposed to a
w e b tier.
Let's write a simple Java server-side application using the AppFuse framework.
AppFuse was created by Matt Raible o f Raible Designs to simplify d i e construction o f
Java w e b applications through convention. Using AppFuse o n d i e server side will allow
us to focus o n d i e integration o f Flex witii Java creating simple d o m a i n and service
Java objects.

Working with AppFuse


Because d i e layers o f architecture and complexity can make approaching d i e building
o f a Java w e b application a bit daunting, AppFuse is a great technology choice because
it simplifies dealing with the layers and delivering value faster.
AppFuse allows a Java d e v e l o p e r to quickly start focusing o n business domain con-
cerns. A typical Java application will be POJO-driven and wired together through
Spring, the o p e n source d e p e n d e n c y injection ( D I ) framework. T h e DI design pattern
helps to build applications with loosely coupled c o m p o n e n t s making your application
m o r e flexible and testable. In addition, AppFuse comes stocked with Maven integra-
tion to make tilings even easier. Let's get things rolling by installing Maven.

Generating the application structure with Maven


T o p i g e o n h o l e Maven by calling it a build system doesn't d o it justice. A p a c h e Maven
is a software p r o j e c t m a n a g e m e n t and c o m p r e h e n s i o n tool. W h a t exactly does that
mean? A t the core o f every M a v e n p r o j e c t is a p r o j e c t o b j e c t m o d e l , m o r e affec-
tionately known as d i e POM, and f r o m this POM Maven can build our application,

www.it-ebooks.info
14 CHAPTER 2 Beginning with Java

generate reports, generate documentation, and m o r e , all f r o m a single description


o f the project. T o learn m o r e about M a v e n check out the A p a c h e Maven p r o j e c t site
at http://maven.apache.org or d o w n l o a d the f r e e e b o o k f r o m Sonatype at http://
www.sonatype.com/book.
B e f o r e m o v i n g ahead with Maven, be sure you have the Java D e v e l o p m e n t Kit
(JDK) version 1.5 or greater properly installed. You can f o l l o w the n e x t section f o r that
or skip it if you're ready to go. A f t e r you install the JDK, b e sure to install the MySQL
database as well. You'll n e e d MySQL installed b e f o r e generating the p r o j e c t with the
AppFuse Maven archetype.

2.2.1 Download and install the JDK


T o run any Java server-side environment, you must install and configure the JDK.
D o w n l o a d and install JDK 1.5+ f r o m the Sun website at http://java.sun.com/javase/
downloads/index.jsp. R e f e r to the Java documentation f o r instructions o n h o w to
install Java o n your specific platform. Set up an e n v i r o n m e n t variable f o r JAVA_HOME
that points to the JDK directory. It's also h e l p f u l to add the JDK's bin directory to the
path. O p e n a c o m m a n d p r o m p t and type in the Java version to verily that Java is
installed correctly. T h e version i n f o r m a t i o n o f the c o n f i g u r e d JDK should be pre-
sented as shown in figure 2.1.
A f t e r Java is c o n f i g u r e d you can m o v e o n to setting up the o p e n source
MySQL database.

Figure 2.1 Verify that Java is set up correctly by checking the version

www.it-ebooks.info
Generating the application structure with Maven 15

2.2.2 Download and install MySQL


T o demonstrate database integration and persistence you'll use MySQL, which is an
o p e n source database that is extremely lightweight. D o w n l o a d and install MySQL 5.x
o r h i g h e r f r o m the MySQL website at http://dev.mysql.com/downloads/mysql.
H e r e you'll set up a database f o r the FlexBugs sample application. A f t e r you have
MySQL installed pull up the c o m m a n d p r o m p t and l o g in to MySQL using the r o o t
account, then create the flexbugs database as shown in figure 2.2. Using the com-
m a n d mysql -u r o o t - p will instruct MySQL to l o g in to the local host instance o f
MySQL using the r o o t account. It will ask f o r the password. Please r e c o r d the a d m i n
account's user and password f o r later r e f e r e n c e . Creating the database is as simple as
executing the c o m m a n d c r e a t e d a t a b a s e f l e x b u g s .
Let's m o v e o n to installing Maven to create the p r o j e c t structure, m a n a g e the
dependencies, and build the application.

2.2.3 Download and install Maven


Maven can be d o w n l o a d e d at http://maven.apache.org/download.html. Be sure to
download version 2.0.9 or above. A f t e r Maven is d o w n l o a d e d you should set up an
M2_HOME e n v i r o n m e n t variable that points to the directory w h e r e Maven was
installed. T h e M2_HOME/bin directory will n e e d to be set o n t o the path as well or
e x p o r t e d f o r any U N I X platform. For m o r e assistance o n installing or c o n f i g u r i n g
Maven refer to the Maven documentation at http://www.sonatype.com/books/
mvnex-books/reference/installation-sect-maven-install.html.

c\ C:\WIND0WS\systeiri32\cmd.exe - mysql -u root -p -Ja)x


A
C:\Documents and S e t t i n g s \ b a l l m o n > m y s q l -u root - ip
Enter password: hmmhkmmmm
Welcome t o t h e MySQL m o n i t o r . Commands end w i t h ; o i> .
Vour MySQL c o n n e c t i o n i d i s 4
S e r v e r v e r s i o n : 5 . 1 . 3 1 - c o m m u n i t y MySQL Community Sei-uei- <CPL>

Type Jhelp;* or '\h* f o r help. Type J\c* to cleai the bill f e r .

mysql> c r e a t e database f l e x b u g s ;
Query OK, 1 row a f f e c t e d < 0 . 0 0 s e c )

mysql> 1

Figure 2.2 Using the MySQL commands to log into the database instance and create the flexbugs
database

www.it-ebooks.info
16 CHAPTER 2 Beginning with Java

2.2.4 Create a Mavert multimodule project


W e ' r e g o i n g to create a Maven multimodule project called FlexBugs. A multimodule
p r o j e c t could be c o n f i g u r e d manually by creating a top-level super POM, adding proj-
ects u n d e r the super POM directory, and editing the super POM to include d i e mod-
ules with the modules element. W e ' r e g o i n g to use a technique that exploits a little
known feature o f the archetypexreate plugin, and the Maven site archetype to kick-
start d i e project.
Creating a multimodule project has many benefits, d i e two most important b e i n g
( 1 ) the ability to build every artifact in a p r o j e c t with a simple mvn c o m p i l e c o m m a n d
and ( 2 ) if you are using either the Maven eclipse:eclipse plugin or the idea:idea
plugin, you can enter this c o m m a n d at d i e r o o t o f the project, and it will generate all
d i e p r o j e c t files f o r all o f the contained modules.
First you'll generate d i e top-level p r o j e c t using the maven-archetype-site-
s i m p l e archetype:

mvn archetype:create
-DgroupId=org.foj
-Dartifactld=flex-bugs
-DarchetypeArtifactld=maven-archetype-site-simple

This generates a Maven project with the directory structure as


£ } flex-bugs
shown in figure 2.3.
E src
T h e p r o j e c t generated is d i e m i n i m u m p r o j e c t setup nec-
• Q site
essary to generate site documentation. T h e index.apt file is
Q apt
d i e main i n d e x page f o r d i e site, and is written in d i e A l m o s t
Plain Text ( A P T ) format, which is a wiki-like format. You can Figure 2.3 The
also generate a m o r e c o m p l e t e site p r o j e c t using the maven- generated top-level
Maven project
a r c h e t y p e - s i t e archetype like this:

mvn archetype:create
-DgroupId=[Java:the project's group id]
-Dartifactld=[Java:the project's artifact id]
-DarchetypeArtifactld=maven-archetype-site

This will generate a p r o j e c t structure similar to figure 2.4.


A f t e r you have generated d i e site project, edit d i e p o m . x m l created f r o m d i e site
archetype plugin. Make sure that the packaging type is set to pom. W e ' v e left sections
out ( d e n o t e d by ...) to be brief.

Listing 2.1 P a c k a g i n g of t y p e p o m indicates a multimodule project

<proj ect>
<modelVersion>4.0.0</modelVersion>
<groupId>org.foj</groupId>
<artifactld>flex-bugs</artifactld>
<version>l. 0-SNAPSHOT</version> Q Artifact type
<packaging>pom</packaging> <1—' (jar, war, ear)

</project>

www.it-ebooks.info
Generating the application structure with Maven 17

Because you set the packaging type to pom Q , any proj-


I multi-module- project
ects you generate f r o m the r o o t o f the p r o j e c t direc-
* srt
tory will insert tiiemselves into the p r o j e c t by creating
j site
an entry into the modules section o f the p o m . x m l f o r
apt
the site. J* fml
AppFuse comes stocked with custom Maven arche- - fr
types, which allow AppFuse to create d i f f e r e n t flavors o f J , apt
Java w e b applications with varying technology stacks. J „ fml
You'll use d i e Struts 2 Basic archetype f o r d i e FlexBugs xdoc
sample application. *doc

In d i e r o o t directory o f your p r o j e c t tiiat you created


previously, type d i e c o m m a n d in listing 2.2. Figure 2.4 A fully dressed up
Maven site project

Listing 2.2 C r e a t e the f l e x - b u g s - w e b module for t h e Java server side

mvn archetype:create
-DarchetypeGroupId=org.appfuse.archetypes <—©
-DarchetypeArtifactld=appfuse-basic-struts <—Q
-DremoteRepositories=http://static.appfuse.org/releases
-DarchetypeVersion=2 . 0 . 2 <1 .
-DgroupId=org. foj . flex-bugs <1—© Q
-Dartif actld=f lex-bugs-web <1—Q

T h e appfuse-basic-struts © archetype isn't a built-in Maven resource. Instead, it's


p r o v i d e d through a r e m o t e repository © . You provide Maven witii coordinates to d i e
archetype by also providing d i e archetypeGroupId O an d archetypeVersion O
a l o n g with d i e rest o f d i e required details. T h e groupld © points to d i e top-level proj-
ect and the artifactld © is the n a m e o f d i e m o d u l e you are about to create.
A f t e r you've executed d i e c o m m a n d , l o o k inside d i e top-level p o m . x m l f r o m
d i e main project. T h e r e should n o w be an entry toward d i e bottom o f d i e file like
the following.

<modules>
<module>flex-bugs-web</module>
</modules>

Executing d i e c o m m a n d in listing 2.2 should generate d i e project structure shown


in figure 2.5. D o n ' t be c o n c e r n e d witii d i e warnings while creating your project; tiiey
are expected. As l o n g as you see BUILD SUCCESSFUL at the end, your p r o j e c t was
created successfully.
As you can see f r o m figure 2.5 Maven generated d i e p r o j e c t structure and a d d e d a
couple o f files f o r testing.

www.it-ebooks.info
18 CHAPTER 2 Beginning with Java

B i L J flex-bugs
B ¡j J flex-bugs-web
B Q src
B l O main
B U java
B Q org
B t2| foj
_ j flex-bugs
B resources
Q META-1NF
B Q webapp
O common
o WEB-INF
Q site
B I Q test
B Q java
B ^ org
B l c l foj
.. i flex-bug5
i. *l resources Figure 2.5
S src Generated module structure using the
appfuse-basic-struts archetype

2.2.5 Maven provides a buildable project


If you look in die src/main/java/org/foj package you'll find a source file
called App.java, and in d i e src/test/java/org/fo j package you'll f i n d a unit
test called AppTest.java. R e m o v e both files as you will n o t n e e d d i e m .
N o t i c e that Maven appears to be building something. In fact, d i e f l e x - b u g s - w e b
POM tries to build a deployable Java W e b Archive or WAR but will first choke o n a con-
figuration issue. If running the mvn j e t t y : r u n - w a r c o m m a n d witiiout changing the
configuration you'll most likely g e t this error.

[INFO]
[ERROR] BUILD ERROR
[INFO]
[INFO] Error executing database operation: CLEAN_INSERT

Embedded error: Access denied for user 1 root 1 0 1 localhost 1 (using password: NO)
[INFO]
[INFO] For more information, run Maven with the -e switch

Let's first edit the POM f o r d i e f l e x - b u g s - w e b m o d u l e . This POM will be located


at d i e r o o t o f that m o d u l e . T h e r e ' s a g o o d deal g o i n g but w e ' r e g o i n g to focus o n
d i e piece we n e e d to change. A t d i e b o t t o m you n e e d to specify your MySQL user
and password witii the values we specified w h e n you set up MySQL earlier. H e r e ' s
an example:

www.it-ebooks.info
Generating the application structure with Maven 19

<jdbc.urlx![CDATA[jdbc:mysql://localhost/
f lex_bugs_web?createDatabaseIfNotExist=trueS;amp; useUnicode=true&:amp;
characterEncoding=utf-8]]></jdbc.url>
<jdbc.username>root</jdbc.username>
<jdbc.password>j ava4ever</jdbc.password>

T h e Maven archetype we used, b r o u g h t to us by AppFuse, m a d e it extremely easy to


g e t to this p o i n t — f a r easier tiian starting f r o m scratch.

2.2.6 Running the FiexBugs web application


Maven equips a d e v e l o p e r with d i e ability to use d i e application immediately witiiout
manually deploying it anywhere. Executing d i e Maven j e t t y : r u n - w a r goal f r o m d i e
f l e x - b u g s - w e b m o d u l e will gather all d i e resources, c o m p i l e all the c o d e and tests,
execute d i e unit tests, generate test reports, build a deployable WAR file, and launch
the WAR file in an e m b e d d e d instance o f the popular and lightweight Jetty servlet
container. Using the a p p f u s e - b a s i c - s t r u t s archetype will also generate d i e default
database f o r us and add configuration files to allow developers to quickly b e g i n devel-
o p i n g features.
A f t e r you've run d i e j e t t y : run-war c o m m a n d , you can g o to http://localhost:
8080/flex-bugs-1.0-SNAPSHC)T and l o g in f r o m tiiere. By default, you can l o g in to the
application using a d m i n f o r botii d i e username and password. A f t e r l o g g i n g in, you
are redirected to the administration panel as seen in figure 2.6. F r o m tiiere you can
d o basic things like editing your user p r o f i l e and m a n a g i n g users.

AppFuse
Providino integration and style to open source Java.

Main M e n u Edit Profile Administration Logout

Welcome!
Congratulations, you have logged in successfully! Now that you've logged in, you
have the following options:

0 Edit Profile
o Upload A File

Version l . O - S N A P S H O T | XHTML Valid | C S S Valid | Logged in as: admin © ZOOS Y

Figure 2.6 AppFuse default application

www.it-ebooks.info
43 CHAPTER 2 Beginning with Java

T h e application shows n o t h i n g glamorous at this p o i n t although everything you see


and can d o has required a m i n o r setup effort. AppFuse does much u n d e r d i e cov-
ers f o r us f r o m a framework and technology perspective. It's possible tiiat getting a
p r o j e c t t o g e d i e r witii help f r o m Maven saved us a w e e k or m o r e o f typical Java
d e v e l o p m e n t time.
B e f o r e we start d e v e l o p m e n t o f d i e FlexBugs sample application download the
source code at https://ilexonjava.googlecode.com/svn/ilex-bugs/trunk.

Build the model objects


A m o d e l object is a POJO tiiat is persistable and m a p p e d to d i e database. In our exam-
ple w e ' r e using AppFuse with d i e Spring f r a m e w o r k and Hibernate to manage per-
f o r m i n g database operations f o r objects tiiat are m a p p e d to a database.
Let's start with Issue. j ava as seen in listing 2.3. For the FlexBugs application you
n e e d sometiiing to store issues and comments. A n issue describes sometiiing that
needs f i x i n g to m e e t a requirement. This could b e a bug, a new feature, a refactor, or
an optimization. A single issue can have many comments so a relationship is built
between the issue and c o m m e n t objects.

Listing 2.3 The I s s u e model o b j e c t

package org. foj . model; <1—Q Model Java package

import org. apache. commons . lang. builder. EqualsBuilder; <—Q Import declarations

J
Java persistence
©Entity framework
public class Issue extends BaseObject implements Serializable {

private Long id;

1
private String project; Class instance Issue extends
private String description; variables AppFuse BaseObject
private String type;
private String severity;
private String status;
private String details;
private String reportedBy;
private Date reportedOn;
private String assignedTo;
private Double estimatedHours; Declares

J
database pk
?k O Indicates
relationship
"PJ
@Id how to
@GeneratedValue(strategy = GenerationType.AUTO) generate Id
public Long getldO {
"getter" method
return id;
1> returns Id

public void setId(Long id)


"setter" method
this.id = id;
1) sets Id

www.it-ebooks.info
Build the model objects 21

(iOverride <1—.
public int hashCodeO { ^jj) hashCode
return new HashCodeBuilder(11, 37).append(id).toHashCode();
}

(iOverride <1—.
public boolean equals (Object o) { fn equals
if (null == o) return false;
if (!(o instanceof Issue)) return false;
if (this == o) return true;

Issue input = (Issue) o;


return new EqualsBuilder()
.append(this.getld(), input.getld())
.isEquals();

'' {ft toString provides


(iOverride <-J object info
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append(id)
.append(proj ect)
.append(description)
.toString();
}

Y o u ' l l be storing the m o d e l objects in d i e org. foj .model Java package © and will use
the AppFuse framework in conjunction witii d i e Spring Framework and Hibernate to
simplify our application d e v e l o p m e n t . Spring provides DI and m o r e while Hibernate
is a database persistence framework that enables object relational m a p p i n g framework
Q . T h e Id Q and GeneratedValue O annotation help to facilitate the persistence by
designating a field as a database primary key.
T h e Issue object is a subclass o f d i e AppFuse BaseObject © and contains d i e
instance variables © you n e e d to describe an issue. A l l o f the instance variables or
fields have d i e getters © and setters © required by the JavaBean specification.

NOTE Extending BaseObject requires us to override die toString


equals Q , and hashCode (JJ) metiiods because they're d e f i n e d as abstract in
the BaseObject class. T o i m p l e m e n t these metiiods w e ' r e leveraging the
A p a c h e C o m m o n s Builder package © f o r creating the elements f o r these
metiiods. W h e n e v e r y o u ' r e i m p l e m e n t i n g the Serializable interface, it's a
g o o d idea to also i m p l e m e n t the equals and hashCode metiiods and provide
a serialVersionUID m e m b e r .

N e x t you'll create a m o d e l object f o r a c o m m e n t . T h e Comment will be another persis-


table object. T h e r e can be many comments to a single issue. For the r e m a i n d e r o f the
c o d e snippets in this chapter w e ' l l use "..." f o r trivial things like imports and getters
and setters o f similar objects.

www.it-ebooks.info
22 CHAPTER 2 Beginning with Java

Listing 2.4 The comment model object

©Entity
public class Comment extends BaseObject implements Serializable { <1—

private Long id;


private Issue issue; Comment 1
private String author; declaration V
private Date createdDate;
private String commentText;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long g e t l d O {
return id;

public void setId(Long id) {


this.id = id;
A Comment has many-to-one
@ManyToOne(fetch = FetchType.EAGER) ^ T relationship with Issue
public Issue getlssueO {
return issue;

public void setlssue(Issue issue) {


this.issue = issue;

(iOverride
public int hashCodeO {
return new HashCodeBuilder(11, 37).append(id).toHashCode();
}
(iOverride
public boolean equals(Object o) {
if (null == o) return false;
if (!(o instanceof Issue)) return false;
if (this == o) return true;

Issue input = (Issue) o;


return new EqualsBuilder()
.append(this.getld(), input.getld())
.isEquals();

(iOverride
public String toStringO {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append(id)
.toString();
}
}

www.it-ebooks.info
Build the DAOs 23

There's not much difference between an Issue and a Comment The class fields are
related to comments and tiiere is a many-to-one relationship Q with Issue. We've also
told Hibernate that we'd like it to eagerly fetch the Issue when returning die
Comment. In typical Java web development you would keep the session open to lazily
load die Issue object only when it's referred to at runtime, but because your Flex
application runs external to the JVM you cannot take advantage of this luxury.
Now that you have your model objects built you can create a set of DAOs. You'll
need a DAO for issue and comment.

2.4 Build the DAOs


AppFuse provides generic implementations for DAOs that you can leverage if your
DAOs do nothing more than the basic create, retrieve, update, delete (CRUD) opera-
tions. Because your IssueDao will do only basic operations, there is no need to define
a concrete IssueDao. You can instead use die GenericHibernateDao which you'll see
later when you wire the beans in the application context. The CommentDao needs to
implement a couple of operations that go beyond die basic CRUD operations so you'll
first create an interface for the CommentDao.

Listing 2.5 The CommentDao.java

public interface CommentDao extends GenericDao<Comment, Long> {


List<Comment> getCommentsBylssueld(Long issueld);
void deleteAHCommentsForlssueld(Long issueld);

T h e CommentDao has two simple methods, one that returns a list of Comment objects by
passing in the issueld argument, and another to delete all of die Comment objects for
an issue. The second method facilitates the deleting of Issue objects. Because
Comment has a foreign key relationship with Issue, you cannot delete an Issue if any
Comments refer to it.

NOTE W e defined die relationship between Comment and Issue by annotat-


ing die field with a OOneToOne annotation, and could have also defined die
reverse of that relationship in the Issue class by including a Set of Comment
objects belonging to an Issue. Because we could not lazy load those objects, it
would have forced us to eager load die Comment objects into the Set, which
would force those Comment objects to eager load their Issue objects. This
forces the Issue objects to eager load their Comments, and so on. This usually
results in a stack overflow because you've effectively got a circular reference
that causes an infinite loop of eager fetching.

Now let's implement the ComrnentDaoIm.pl.

www.it-ebooks.info
47 CHAPTER 2 Beginning with Java

Listing 2.6 The CommentDaolmpl.java

public class CommentDaoImpl extends GenericDaoHibernate<Comment, Long>


implements CommentDao {

public CommentDaoImpl() {
super(Comment.class);
}
(iOverride
(iSuppressWarnings ("unchecked")
public List<Comment> getCommentsBylssueld(Long issueld) {
return getHibernateTemplate().find
("from Comment where issue_id = ?", issueld);
}

M u c h like tlie IssueDaoImpl, CommentDaoImpl extends GenericDaoHibernate but


implements CommentDao. T h e only interesting thing h a p p e n i n g h e r e is tiiat you have a
m e t h o d tiiat returns a list o f Comment objects by leveraging the Hibernate template
and a query. Spring and Hibernate are a w o n d e r f u l combination and make f o r clean
and intuitive DAOs.
N o w that you've constructed d i e DAOs you can build services.

Build the services


N o w you n e e d to expose services to d i e w e b tier. Y o u ' l l b e able to take advantage o f
tiiese services f o r the Flex client you'll be building. A g a i n you'll start with interfaces
like IssueManager in listing 2.7.

Listing 2.7 The IssueManager.java

package org.foj.service;

import org.foj.model.Issue;
import javax.jws.WebService; A IssueManager interface
import java.util.List; declaration with
WebService annotation
(iWebService
public interface IssueManager
Q Return all
R
List<Issue> g e t A H O ; <j_J issues
is A Get specific
Issue get(Long id); <,_r
< -J issue
is by its ID
Issue save(Issue issue);
void remove(Long id);
1>
_ Save issue
1> Delete issue

You d e f i n e the IssueManager as a w e b service by annotating it using OWebService


O - IssueManager contains m e t h o d s d e f i n i n g your basic CRUD operations f o r read-
ing © and © , creating and updating Q , and deleting Q . N o w let's take a l o o k at
the CommentManager.

www.it-ebooks.info
Build the services 25

Listing 2.8 The C o m m e n t M a n a g e r . j a v a

package org.foj.service;

import org.foj.model.Comment;
CommentManager
import javax.jws.WebService; interface declaration
import java.util.List; with WebService
@WebService annotation
public interface CommentManager { Get comments
for issue Id
List<Comment> findCommentsBylssueld(Long issueld);
void deleteAHCommentsForlssueld(Long issueld);
Delete all
Comment get(Long id);
comments
Comment save(Comment comment); for issue
Save
void remove(Long id); comment
Remove
1 , comment
CommentManager is also a w e b service O by virtue o f it having the OWebService anno-
tation just as with the IssueManager. It contains a m e t h o d to return a list o f Comment
objects by providing an issueld a m e t h o d f o r deleting all comments f o r an issue
id Q , a m e t h o d f o r saving a c o m m e n t Q and a m e t h o d f o r deleting a c o m m e n t Q .
N o w let's p r o v i d e i m p l e m e n t a t i o n f o r the services like IssueManagerlmpl.

Listing 2.9 The IssueManagerlmpl.java

package org.foj.service.impl;

import org.AppFuse.dao.GenericDao;
import org.foj.model.Issue;
import org.foj.service.IssueManager;
import org.foj.service.CommentManager;
import java.util.List;
import javax.jws.WebService; A IssueManagerlmpl
declaration with
(iWebService(serviceName = "IssueService", WebService
annotation
endpointlnterface = "org.foj.service.IssueManager")
public class IssueManagerlmpl implements IssueManager {

private GenericDao<Issue, Long> issueDao;


private CommentManager CommentManager;

J
Default no arg
public IssueManagerlmpl!) { constructor
}

public IssueManagerlmpl(GenericDao<Issue, Long> issueDao,


CommentManager CommentManager) {
this.issueDao = issueDao;
this.CommentManager = CommentManager;
1> Constructor

public List<Issue> g e t A H O {
Method that
return issueDao.getAll(); returns all Issues
}

www.it-ebooks.info
CHAPTER 2 Beginning with Java

public Issue get(Long id) {


return issueDao.get(id); Get specific issue
}

public Issue save(Issue issue) {


return issueDao.save(issue); Save issue
}

public void remove(Long id) {


commentManager.deleteAHCommentsForlssueld(id);
issueDao.remove(id);
1> Remove an issue

T h e IssueManagerlmpl also uses the OWebService annotation just as in the interface,


but provides d i e serviceName and e n d p o i n t l n t e r f a c e attributes Q . You provide a
default n o args constructor Q as well as o n e tiiat will be used by Spring to inject d i e
IssueDao and CommentManager © . N e x t i m p l e m e n t d i e methods f o r returning the list
o f I s s u e objects Q , returning a specific I s s u e Q , and saving an I s s u e Q by delegat-
i n g d i e calls to diose metiiods to d i e IssueDao. T h e implementation f o r r e m o v i n g an
issue Q first deletes any comments f o r d i e issue by calling d i e CommentManager, tiien
removes d i e issue by calling d i e r e m o v e m e t i i o d o n d i e IssueDao. N o w let's l o o k at
d i e CommentManager.

Listing 2.10 The CommentManagerlmpl.java

package org.foj.service.impl;

import org.foj.dao.CommentDao;
import org.foj.model.Comment;
import org.foj.service.CommentManager;
import java.util.List; CommentManagerlmpI
declaration with
import javax.jws.WebService;
WebService annotation
(iWebService (serviceName = "CommentService",
endpointlnterface = "org.foj.service.CommentManager")
public class CommentManagerlmpI implements CommentManager {

private CommentDao commentDao;


Default no args
public CommentManagerlmpI() {
}
J? constructor
Constructor sets
injected CommentDao
public CommentManagerlmpI(CommentDao commentDao) { <— instance to use
this.commentDao = commentDao;
Find all

public List<Comment> findCommentsBylssueld(Long issueld)


return commentDao.getCommentsBylssueld(issueld);
J comi
comments
fori!issue

1
public void deleteAHCommentsForlssueld(Long issueld) {
Delete all
commentDao.deleteAHCommentsForlssueld(issueld); comments
} for issue

www.it-ebooks.info
Wiring things together with Spring 27

public Comment get(Long id) {


Get specific
return commentDao.get(id) ;
1, comment
}
public Comment save(Comment comment) {
return commentDao.save(comment); Save comment
}
public void remove(Long id) {
commentDao.remove(id); Delete comment
}

L i k e IssueManagerlmpl, CommentManagerlmpl declares itself to be a WebService O -


N e x t using d i e @WebService annotation and defines its e n d p o i n t interface and
service n a m e you create a default n o args constructor Q as well as o n e that will b e
used by Spring to inject your CommentDao You i m p l e m e n t the methods to get the
Comment objects f o r an issue deleting all the Comment objects f o r an issue Q , get-
ting a specific Comment saving a Comment Q , and deleting a Comment © by delegat-
i n g to d i e CommentDAO.

NOTE AppFuse provides GenericManager implementation base classes just as


it does f o r DAOs, but we chose n o t to use them h e r e because certain Web-
Service consumers such as Flex have difficulty dealing with w e b services that
return objects such as ArrayOfAnyType, which is what AppFuse will return if
we leverage the GenericManagers. T o work around this issue you'll be defin-
i n g and i m p l e m e n t i n g your CRUD operations f o r the w e b services explicitly.

W e ' r e n o w officially d o n e with the server-side objects and can wire tilings together
with the Spring configuration and w o r k o n the w e b tier components.

Wiring things together with Spring


Spring enables developers to easily c o n n e c t objects while k e e p i n g application c o m p o -
nents loosely coupled and testable. N o t i c e h o w w e ' v e wired d i e m o d e l , DAO, and ser-
vice objects together in d i e f o l l o w i n g listing. T h e applicationContext.xml is located in
the src\main\webapp\WEB-INF directory, with other configuration files.

Listing 2.11 The a p p l i c a t i o n C o n t e x t . x m l

<!-- Add new DAOs here -->


<bean id= " issueDao" class= 0 issueDao
is
"org.AppFuse.dao.hibernate.GenericDaoHibernate">
<constructor-arg value="org.foj.model.Issue"/>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

1
<bean id="commentDao" class="org.foj.dao.impl.CommentDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean> commentDao

www.it-ebooks.info
28 CHAPTER 2 Beginning with Java

<!-- Add new Managers here -->


<bean id="issueManager" class="org.foj.service.impl.IssueManagerlmpl">
<constructor-arg ref="issueDao"/>
</bean> issueManager• 1
<bean id= " commentManager" class= |J5f COmmentManager
"org.foj.service.impl.CommentManagerlmpl">
<constructor-arg ref="commentDao"/>
</bean>

T h e first bean you d e f i n e is GenericDao f o r d i e issueDao Q . T h e commentDao Q is


d e f i n e d widi your concrete implementation. Next, you create Spring beans f o r issue-
Manager Q and commentManager Q . T h e constructor-arg e l e m e n t is used to inject
d i e dependencies into the service class constructor.
N o w tiiat we've wired things up witii Spring let's construct the w e b tier starting
with Struts 2 framework action classes.

2.7 Constructing the web tier


Struts 2 applications i m p l e m e n t the Model-View-Controller ( M V C ) design pattern,
which is n o t to b e confused witii the M V P design pattern used to develop d i e Flex
application. T h e pattern encourages separation between the data m o d e l , view ele-
ments, and controllers that sit between tiiem. T h e M V C pattern, widely a d o p t e d in d i e
Java community, has m a d e its way into otiier languages and frameworks, like Flex.

2.7.1 Building Struts 2 action classes


You'll start by building controller o r action classes first, like IssueAction.

Listing 2 . 1 2 T h e IssueAction.java

package org.foj.action;

import org.AppFuse.webapp.action.BaseAction;
IssueAction extends
public class IssueAction extends BaseAction { AppFuse BaseAction

private IssueManager issueManager;


private CommentManager commentManager;
private List<Issue> issues;
private List<Comment> comments; Setters for A
private Issue issue; IssueManager and
private Long id; CommentManager

public void setlssueManager (IssueManager issueManager) { <1—


this.issueManager = issueManager;
}
public void setCommentManager(CommentManager commentManager) { <—
this.commentManager = commentManager;
}

www.it-ebooks.info
Constructing the web tier 29

public String list() {


Returns list of
issues = issueManager.getAll();
issueManage Issue objects
return SUCCESS;

public String deleted {


issueManager.remove(issue.getld()); Deletes Issue
saveMessage(getText("issue.deleted"));

return SUCCESS;
}
public String edit() {
if (id != null) { Edits by Issueld
issue = issueManager.get(id);
} else {
issue = new Issued;
}
comments = commentManager.findCommentsBylssueld(issue.getld());

return SUCCESS;

public String saved throws Exception {


if (cancel != null) { Saves Issue
return CANCEL;

if (delete != null) {
return delete();
}
boolean isNew = (issue.getld() == null);

issue = issueManager.save(issue);

String key = isNew ? "issue.added" : "issue.updated";


saveMessage(getText(key));

if (!isNew) {
return INPUT;
} else {
return SUCCESS;

IssueAction extends d i e AppFuse BaseAction © that contains many c o m m o n metli-


ods diat actions rely on. IssueAction has setters f o r the service objects These set-
ters will b e called by Spring, and their instances will be injected into the action class
during runtime. IssueAction facilitates controlling communications to the server
side f r o m d i e w e b tier. It contains the methods f o r d i e view pages to list © , delete Q ,
edit Q or, most importantly, save Issue objects © .
T h e CommentAction object serves the same purpose f o r d i e Comment object as the
IssueAction object does f o r d i e Issue object. A l l the m e t h o d s o n CommentAction are

www.it-ebooks.info
30 CHAPTER 2 Beginning with Java

facilitating CRUD f o r the Comment POJO by calling the commentManager service. T h e


CommentAction class can b e d o w n l o a d e d f r o m the website if n e e d e d .
N o w that d i e actions are in place, let's w o r k o n JSP files to create a simple UI f o r
m a n a g i n g issues.

2.7.2 Editing the issue menu item


First you have to m o d i f y d i e menu.jsp to g e t to the issues list.

Listing 2.13 T h e menu.jsp

<menu:displayMenu name="MainMenu"/>
<menu:displayMenu name= "UserMenu"/> O Adding IssueMenu item
<menu: displayMenu name= " IssueMenu"/> <—' to the JSP view file
<menu:displayMenu name="AdminMenu"/>
<menu:displayMenu name="Logout"/>

T h e m e n u JSP file reads in d i e m e n u x m l data. T o add the I s s u e m e n u item you


n e e d only add a single line O to tiiis file that is located in d i e flex-bugs-web/src/
m a i n / w e b a p p / c o m m o n directory. In d i e f o l l o w i n g listing you'll provide d i e x m l
data f o r that m e n u item.

Listing 2.14 T h e menu-config.xml

<Menu name="IssueMenu" title="menu.issue" IA Add Issue menu item


description="Issues Menu" f to menu data xml file
roles="ROLE_ADMIN,ROLE_USER" page="/issues.html">
<Item name="Viewlssues" title="menu.viewlssues" page="/issues.html"/>
</Menu>

By adding to d i e existing AppFuse p l u m b i n g that creates m e n u items O , you quickly


gain access to new features. Let's create the IssueList.jsp that will be displayed w h e n
you click d i e issues m e n u item.

2.7.3 Adding JSP resources


T h e issueList.jsp will display a list o f issues and allow you to add o r m o d i f y existing
issues. T h e issue and c o m m e n t JSP files will reside in the ../src/main/webapp/WEB-
INF/pages directory.

Listing 2.15 T h e issueList.jsp

<%@ include file="/common/taglibs.jsp" %>


Essential tag
<head> O libraries bundle
<titlexfmt: message key="issueList.title"/></title>
<meta content="<fmt: message key= 1 issueList.heading 1/> " name="heading"/>
</head>

www.it-ebooks.info
Discovering Diverse Content Through
Random Scribd Documents
reading which would be justified not only as humor but as literature
and art. This is only one of many instances of Mark Twain's lifelong
revolt against a rôle which he apparently felt had been thrust upon
him. It is enough to corroborate all our intuitions regarding the
reluctance with which he accepted it.
But there is plenty of other evidence to corroborate these intuitions.
Mr. Paine tells us that henceforth, in his letters home, "the writer
rarely speaks of his work at all, and is more inclined to tell of the
mining shares he has accumulated," that there is "no mention of his
new title"—the pen-name he had adopted—"and its success." He
knew that his severe Calvinistic mother could hardly sympathize with
his scribblings, worthy or unworthy, that she was much more
concerned about the money he was making; he who had sworn
never to come home again until he was a rich man was ashamed in
his mother's eyes to have adopted a career that promised him
success indeed, but a success incomparable with that of the mining
magnate he had set out to be. Still, that success immediately proved
to be considerable, and if he had felt any essential pride in his new
work he would certainly have said something about it. What we
actually find him writing is this: "I cannot overcome my repugnance
to telling what I am doing or what I expect to do or propose to do."
That he had no essential pride in this work, that it was not personal,
that he did not think of it as a true expression of himself but rather
as a commodity we can see from the motives with which he chose
his pen-name: "His letters, copied and quoted all along the Coast,
were unsigned," says Mr. Paine. "They were easily identified with
one another, but not with a personality. He realized that to build a
reputation it was necessary to fasten it to an individuality, a name.
He gave the matter a good deal of thought. He did not consider the
use of his own name; the nom de plume was the fashion of the
time. He wanted something brief, crisp, definite, unforgettable. He
tried over a good many combinations in his mind, but none seemed
convincing," etc., etc. In short, he wanted a trade mark in order to
sell what he instinctively regarded as his merchandise; and the fact
that the pen-name was the fashion of the time—in pioneer circles,
especially, observe—simply argues that all the other writers in the
West were in a similar case. The pen-name was a form of "protective
coloration" for men who could not risk, in their own persons, the
odium of the literary life, and it is an interesting coincidence that
"Mark Twain," in the pilot's vocabulary, implied "safe water." We shall
see later how very significant this coincidence was in Mark Twain's
life: what we observe now is that he instinctively thought of his
writing as something external to himself, as something of which he
was proud only because it paid.
It is quite plain, then, that far from having found himself again, as
he had once found himself on the Mississippi, Mark Twain had now
gone astray. He had his ups and downs, his success, however
prodigious, was intermittent; but whether he was up or whether he
was down he was desperately ill-at-ease within: his letters and
memoranda show all the evidence of a "bad conscience." Hear him
in San Francisco: "We have been here only four months, yet we have
changed our lodgings five times. We are very comfortably fixed
where we are now and have no fault to find with the rooms or the
people.... But I need change and must move again." Whatever else
that incessant, senseless movement may mean, it is certainly not the
sign of a man whose work absorbs him, whose nature is crystallizing
along its proper lines. "Home again," he notes in his journal, after
those weeks of respite in the Sandwich Islands. "No—not home
again—in prison again, and all the wild sense of freedom gone. The
city seems so cramped and so dreary with toil and care and business
anxiety. God help me, I wish I were at sea again!" Work, writing,
had become in his eyes identical with toil: "Clemens once declared
he had been so blue at this period," says Mr. Paine, "that one
morning he put a loaded pistol to his head, but found he lacked
courage to pull the trigger." And observe, finally, what he writes to
his mother from New York as he is about to start on the Quaker City
excursion which is to result in "The Innocents Abroad" and his great
fame. There are two letters, written within the same week of June,
1867; the eagerness of his youth does not suffice to explain their
agitation. In the first he says: "I am wild with impatience to move—
move—move!... Curse the endless delays! They always kill me—they
make me neglect every duty and then I have a conscience that tears
me like a wild beast. I wish I never had to stop anywhere a month."
The second is even more specific: "I am so worthless that it seems
to me I never do anything or accomplish anything that lingers in my
mind as a pleasant memory. My mind is stored full of unworthy
conduct toward Orion and toward you all, and an accusing
conscience gives me peace only in excitement and restless moving
from place to place.... You observe that under a cheerful exterior I
have got a spirit that is angry with me and gives me freely its
contempt." The reason he assigns for this frame of mind is wholly
unacceptable: far from being guilty of "unworthy conduct" toward
his family, there is every evidence that he had been, as he remained,
the most loyal and bountiful of sons and guardians. "Under a
cheerful exterior I have got a spirit that is angry with me and gives
me freely its contempt." Could he say more plainly that he has
committed himself to a course of action which has, in some quite
definite way, transgressed his principle of growth?
One further, final proof. In 1865 "The Jumping Frog" was published
in New York, where, according to one of the California
correspondents, it was "voted the best thing of the day." How did
Clemens, who was still in the West, receive the news of his success?
"The telegraph," says Mr. Paine, "did not carry such news in those
days, and it took a good while for the echo of his victory to travel to
the Coast. When at last a lagging word of it did arrive, it would seem
to have brought disappointment, rather than exaltation, to the
author. Even Artemus Ward's opinion of the story had not increased
Mark Twain's regard for it as literature. That it had struck the
popular note meant, as he believed, failure for his more highly
regarded work. In a letter written January 20, 1866, he says these
things for himself: 'I do not know what to write; my life is so
uneventful. I wish I was back there piloting up and down the river
again. Verily, all is vanity and little worth—save piloting. To think
that, after writing many an article a man might be excused for
thinking tolerably good, those New York people should single out a
villainous backwoods sketch to compliment me on!—"Jim Smiley and
His Jumping Frog"—a squib which would never have been written
but to please Artemus Ward.'" He had thought so little of that story
indeed that he had not even offered it to The Californian, the
magazine to which he was a staff contributor: "he did not," says Mr.
Paine, "regard it highly as literary material." We can see in that letter
the bitter prompting of his creative instinct, in rebellion against the
course he has drifted into; we can see how his acquisitive instinct,
on the other hand, forbids him to gainsay the success he has
achieved. "I am in for it," he writes to his brother. "I must go on
chasing [phantoms] until I marry, then I am done with literature and
all other bosh—that is, literature wherewith to please the general
public. I shall write to please myself then." Marriage, he says to
himself, is going to liberate him, this poor, ingenuous being!—this
divided soul who has never been able to find any other criterion than
that of an environment which knows no criterion but success. His
destiny, meanwhile, has passed out of his own hands: that is the
significance of the "victory" of "The Jumping Frog." As Mr. Paine
says, with terrible, unconscious irony: "The stone rejected by the
builder was made the corner-stone of his literary edifice."
So much for Mark Twain's motives in becoming a humorist. He had
adopted this rôle unwillingly, as a compromise, at the expense of his
artistic self-respect, because it afforded the only available means of
satisfying that other instinct which, in the unconsciousness of his
creative instinct, had become dominant in him, the gregarious,
acquisitive instinct of the success-loving pioneer. And what a
corroboration that instinct now received! Was ever a choice more
thrillingly ratified by public opinion! "Limelight and the center of the
stage," says Mr. Paine, "was a passion of Sam Clemens's boyhood, a
love of the spectacular that never wholly died.... Like Tom Sawyer,
he loved the glare and trappings of leadership." The permanent
dream of his childhood, indeed, had been to become "something
gorgeous and active, where his word—his nod, even, constituted
sufficient law." Here we see exhibited what Alfred Adler calls the
"masculine protest," the desire to be more than manly in order to
escape the feeling of insecurity, for Mark Twain, who was a weak
child, could never have survived in the rough-and-tumble of
Hannibal life if he had not exerted his imagination and prevailed over
his companions by means other than physical. This dream had been
fulfilled in his piloting career, which was at once autocratic and
spectacular. United now, a deep craving to shine, with his other
desire to make money, to please his family, to "make good" in
pioneer terms, it received a confirmation so prodigious that the
despised, rejected, repressed, inarticulate poet in Mark Twain was
immediately struck dumb and his doubts and chagrins and
disappointments were lulled to rest.
Already, in Nevada, Mark Twain had been pointed out as one of the
sights of the territory; his sayings were everywhere repeated on the
streets. Tom Sawyer was walking the stage and "revelling in his
power." Crashes of applause greeted his platform sallies; "the
Comstock, ready to laugh," says Mr. Paine, "found delight in his
expression and discovered a vast humor in his most earnest
statements"; the opera-houses of the mining-towns wherever he
went were packed at two dollars a seat; "his improved dress and
increased prosperity commanded additional respect." He had
"acquired," in short, "a new and lucrative profession at a bound";
and before he went East, and owing to the success of "The Jumping
Frog," "those about him were inclined to regard him, in some degree
at least, as a national literary figure, and to pay tribute accordingly."
When he set out on the voyage of the Quaker City he found himself
"billed as an attraction" with General Sherman and Henry Ward
Beecher. But this was only a faint promise of the glory that was to
follow the publication of "The Innocents Abroad." It was his second
book: his profits were $300,000, and it brought him into instant and
intimate contact with the most distinguished people in America.
Besides this, it brought him the recognition of The Atlantic Monthly.
It brought him offers of political preferment: a diplomatic position,
the postmastership of San Francisco, with a salary of $10,000 a year,
a choice of five influential offices in California, anything he might be
disposed to accept—"they want to send me abroad, as a Consul or a
Minister," he writes from Washington: judges pledge the President's
appointment, senators guarantee the confirmation of the Senate. It
brought him presently a tremendous reception from "the brains of
London, assembled at the annual dinner of the sheriffs of London—
mine being (between you and me)," he writes to his publisher, "a
name which was received with a flattering outburst of spontaneous
applause when the long list of guests was called." It brought him an
offer from at least one magazine of "$6,000 cash for twelve articles,
of any length and on any subject." It brought him lecture
engagements that paid him $1,600 in gold for a single evening; and
so popular were these lectures that when one night in Pittsburgh he
"played" against Fanny Kemble, the favorite actress of the period,
"Miss Kemble had an audience of two hundred against nearly ten
times the number who gathered to hear Mark Twain." Could this
divided soul, who had rebelled against the career into which he was
drifting, question a verdict like that? Almost from the outset his filial
conscience had been appeased: of his first lecture tour in Nevada
and California we are told that "it paid him well; he could go home
now, without shame." But even the promptings of his artistic
conscience were now parried and laid at rest: "he had grown more
lenient in his opinion of the merits of the 'Frog' story itself since it
had made friends in high places, especially since James Russell
Lowell had pronounced it 'the finest piece of humorous writing yet
produced in America.'" Thus whatever doubts Mark Twain might still
have harbored regarding the vital propriety of his new career were
opportunely overlaid by the very persons he could not fail to respect
the most.
It was this last fact, without doubt, that sealed his destiny. James
Russell Lowell and "the brains of London"! There was little criticism
in their careless judgments, but how was Mark Twain to know that?
He was a humorist, they accepted him as a humorist; they had no
means of knowing that he was intended to be something else, that
he really wished to be something else. They found him funny, and
he was just as funny as they found him; but to Mark Twain their
praise meant more than that; it meant something like a solemn
sanction of his career from the world of culture. "Certainly," says Mr.
Paine, of one of his first triumphal visits to London, "certainly he was
never one to give himself airs; but to have the world's great literary
center paying court to him, who only ten years before had been
penniless and unknown, and who once had been a barefoot Tom
Sawyer in Hannibal, was quite startling." Innocent barefoot boy! As
if the true forces of criticism ever operated in the presence of a
visiting foreigner! Mark Twain had not seen Englishmen applaud
when Joaquin Miller, at a London dinner-table, thrust half a dozen
cigars into his mouth at once and exclaimed: "That's the way we do
it in the States!" He didn't know how much the tribute was a tribute
to his oddity, his mere picturesqueness; he didn't know that he was
being gulled, and partly because he wasn't—because the beautiful
force of his natural personality would have commanded attention
anywhere, because, also, "the brains of London," the brains of
Guildhall banquets, are not too discriminating when it comes to
"laughter and tears" with slow music, or books like "The Innocents
Abroad." But Mark Twain's was not the mind to note these subtle
shades. What he saw was that he was being heartily slapped on the
back, in no too obviously patronizing way, by the people who really
knew, whose judgment could really be trusted. Yet England, as a
matter of fact, so far as he was concerned, was simply
countersigning the verdict of America.
For if, observe, Mark Twain's first counselors at home had been plain
men of business, with an eye single to returns in cash, he might
have seen a light and made a stand against the career of self-
exploitation into which he was drifting. It would not have been easy:
from the moment when "The Jumping Frog" had "set all New York in
a roar," business agents and other brokers in fame and bullion had
begun to swarm about this popular young man like ravenous gulls in
the wake of a ship. But the counsels of some of the most famous
and revered men in America played into the hands of these agents,
and surrendered Mark Twain over to them. Anson Burlingame, Henry
Ward Beecher, even Artemus Ward—these must have been great
names to the Nevada miner of the sixties. One was a diplomat, one
a clergy-man, one a writer; their national prestige was not based
upon money; to Mark Twain they could not have seemed anything
less than masters, in some degree, of the life of the spirit. And all
their influence corroborated the choice Mark Twain had already
made.
It was during the "flush times" in Virginia City that he had met
Artemus Ward who, on the pinnacle of his career, was, for all that
little Nevada world, the very symbol of the literary life itself.
"Clemens," we are told, "measured himself by this man who had
achieved fame, and perhaps with good reason concluded that Ward's
estimate was correct, that he too could win fame and honor, once he
got a start." We can see what Ward's counsel had been: he had
accepted Mark Twain, not as a creative spirit with possibilities of
inner growth before him—what could Artemus Ward have known
about such things?—but as an embryonic institution, so to speak, as
a "going concern," a man who had already capitalized himself and
wanted only a few practical hints. Concretely he told him that he
ought to "extend his audience eastward." Burlingame's advice was
subtler, but it came to much the same thing. "You have great ability,"
said he; "I believe you have genius. What you need now is the
refinement of association. Seek companionship among men of
superior intellect and character. Refine yourself and your work.
Never affiliate with inferiors; always climb." If Dostoievsky and
Dickens and Victor Hugo had been constrained to accept such advice
in their youth, where should we look now for "Crime and
Punishment" and "Bleak House" and "Les Miserables"? We cannot
blame Artemus Ward and Anson Burlingame for knowing nothing
about the creative life and its processes; and how can we blame the
poor, ignorant, unawakened poet in Mark Twain for not withstanding
the prestige of men who, more than any others he had known, had
won their spurs in the field of the spirit? Even if it had not already
been too late, there were probably not ten souls in all America
capable of so divining the spirit of this lovable child as to have said
to him: "You were right in wishing to repudiate that line of least
resistance. Put money and fame, superiors and inferiors, out of your
mind. Break your ties now and, instead of climbing, descend—into
life and into yourself." Mark Twain had followed Ward's injunction
and "extended his audience eastward" by going East himself. He
"never forgot," we are told, "that advice" of Anson Burlingame:
indeed, he acted upon it immediately by associating himself with the
"choice and refined party" of the Quaker City excursion which led
him to the feet of his future wife. But it led him first to the feet of
Henry Ward Beecher, the most celebrated spiritual leader in all
America. What bread and wine did Beecher offer to the unworldly
poet in him? "Now here," said he—Mark Twain reports the interview
in one of his letters, "now here, you are one of the talented men of
the age—nobody is going to deny that—but in matters of business I
don't suppose you know more than enough to come in when it rains.
I'll tell you what to do and how to do it." And thereupon this priest
of the ideal sat him down and showed him how to make a contract
for "The Innocents Abroad" in which his percentage was a fifth more
than the most opulent publishing house in the country had ever paid
any author except Horace Greeley. Such were the lessons in self-help
this innocent soul received from the wise men of statecraft, literature
and divinity.
Thus Mark Twain was inducted into the Gilded Age, launched, in
defiance of that instinct which only for a few years was to allow him
inner peace, upon the vast welter of a society blind like himself, like
him committed to the pursuit of worldly success.
That in becoming a humorist he had relinquished his independence
as a creative spirit we can see from his general attitude toward his
career. He had lapsed for good and all into a state of what is called
moral infantility. We know that the rôle of laugh-maker had, from
early adolescence, come, as people say, natural to him. At sixteen, in
Hannibal, when he told the story of Jim Wolfe and the cats, "his
hearers laughed immoderately," says Mr. Paine, "and the story-teller
was proud and happy in his success." At twenty, at a printers'
banquet in Keokuk, where he made his first after-dinner speech, his
humor "delighted his audience, and raised him many points in the
public regard." After that, he found, he was always the center of
attraction when he spoke in public. It is significant, however, that
from all his triumphs he had returned faithfully to his work as a
printer, just as later he had held so passionately to the guiding-line
of his trade as a pilot. That persistent adherence of his, in a society
given over to exploitation, to a métier in which he could exercise the
instinct of workmanship, of craftsmanship, is the outstanding fact of
Mark Twain's adolescence. It was the earnest of the artist in him: his
humor was the line of least resistance. When he adopted humor as a
profession, therefore, he was falling back upon a line he had
previously rejected, and this implied that he had ceased to be the
master of his own destiny. In short, the artist in him having failed to
take the helm, he had become a journalist, and his career was now
at the mercy of circumstance.
Glance forward a little. After the triumph of "The Innocents Abroad,"
he wrote to his publisher: "I have other propositions for a book, but
have doubted the propriety of interfering with good newspaper
engagements, except my way as an author could be demonstrated
to be plain before me." To which Mr. Paine adds, specifically: "In
spite of the immense success of his book—a success the like of
which had scarcely been known in America—Mark Twain held himself
to be, not a literary man, but a journalist. He had no plans for
another book; as a newspaper owner and editor he expected, with
his marriage, to settle down and devote the rest of his life to
journalism." Hardly the frame of mind of the writer with a living
sense of his vocation! And this expressed an attitude that Mark
Twain never outgrew. Hear Mr. Paine again, at the time of Clemens's
fiftieth year, when his vital powers seem to have been at their
highest point: "As Mark Twain in the earlier days of his marriage had
temporarily put aside authorship to join in a newspaper venture, so
now again literature had dropped into the background, had become
an avocation, while financial interests prevailed." Financial interests!
—there were whole years during which he thought of hardly
anything else.
This conception of his literary career as interchangeable, so to say,
with his financial career is borne out by his thoroughly journalistic
attitude toward his work. Thus we find him at the outset proposing
to "follow up" his success with the story of the "Hornet" disaster
with a series of articles on the Sandwich Islands, and then to "take
advantage of the popularity of the Hawaiian letters and deliver a
lecture on the same subject." While he was writing "Roughing It" he
planned a book of adventures in the diamond mines of South Africa,
and so impersonal was this work that he proposed that the material
for it should be gathered by an agent, whom he actually despatched.
Then, says Mr. Paine, "the success of 'Roughing It' naturally made
him cast about for other autobiographical material." Years later, after
the failure of the Paige machine, in which he had invested all his
money, we find him returning to literature and counting up his
"assets," exactly as if his literary life were indeed a business
enterprise. "I confined myself to the boy-life out on the Mississippi,"
he writes, "because that had a peculiar charm for me, and not
because I was not familiar with other phases of life." And then he
enumerates all the various rôles he has played, concluding that "as
the most valuable capital or culture or education usable in the
building of novels is personal experience I ought to be well-equipped
for that trade." It does not concern him that under all these different
costumes of the miner, the prospector, the reporter, the publisher, he
has been the same man, that he has really experienced not life but
only modes of living: the costumes are all different, and each one is
good for a new performance. It is not the artist but the salesman
that speaks here, the salesman with an infallible finger for the public
pulse. No more lectures in churches, he tells his agent Redpath:
"People are afraid to laugh in a church"; and again, to his publishing
manager regarding "Pudd'nhead Wilson": "There was nothing new in
that story"—"The American Claimant"—"but the finger-prints in this
one is virgin ground—absolutely fresh, and mighty curious and
interesting to everybody." Mark Twain, who prophesied a sale of
300,000 sets of General Grant's "Memoirs" and then proceeded to
sell almost exactly that number, knew very well what the public
wanted: that had become his chief study. Habitually, in connection
with what he was planning to do, he used the word "possibilities"—
the possibilities of this, the possibilities of that—in the commercial,
not in the artistic, sense; he appears always to have been occupied
with the promise of profit and reputation a theme contained for him,
never with its elements of artistic interest and value. That authorship
was to him, in fact, not an art but a trade, and only the chief trade
of a series that he had followed, in true pioneer fashion, that he
thought of it not as a means of free individual expression but as
something naturally conditioned by the laws of supply and demand,
all the evidence of his life goes to show. I have quoted his eulogy of
the old Mississippi pilot and his description of the writer, by contrast,
as "a manacled servant of the public": "we write frankly and
fearlessly," he adds, naïvely, "but then we 'modify' before we print."
One might imagine that such a thing as an artist had never existed.
Am I anticipating? Go back now; go back to 1867, to the moment of
Mark Twain's Cooper Union lecture, when he finds himself, in the
hands of his agent Fuller, advertised to "play against Speaker Colfax
at Irving Hall, Ristori, and also the double troupe of Japanese
jugglers." Mark Twain hesitates. Fuller is obdurate. "What we want
this time," he says, "is reputation anyway—money is secondary." So
he floods the house with complimentary tickets to the school-
teachers of the city. "Mark," he says, after the lecture is over, "Mark,
it's all right. The fortune didn't come, but it will. The fame has
arrived; with this lecture and your book just out you are going to be
the most talked of man in the country." It was true. But in that
moment—that typical moment, in that reluctance, in that
acquiescence, in that corroboration, Mark Twain's die had been cast.
... Who is this apparition we see "hobnobbing with generals and
senators and other humbugs"? The Mark Twain who is going to walk
the boards of the Gilded Age. In the hour of his triumph he writes to
his mother: "You observe that under a cheerful exterior I have got a
spirit that is angry with me and gives me freely its contempt"; it is a
formidable spirit, that alter ego within him,—he is going to hear its
bitter promptings later on. Now, however, his triumph drowns its
voice: his private, personal and domestic interests have wholly
supplanted the dim and wavering sense of his vocation. "Clemens
was chiefly concerned over two things," says Mr. Paine; "he wished
to make money and he wished to secure a government appointment
for Orion."
Mark Twain often spoke of the rigidity of determinism, of the
inexorable sequence of cause and effect. As Mr. Paine says—with an
emphasis of his own—he had but to review his own life for
justification of his belief. From this point on, his career was a steady
process of what is called adaptation to environment. He had
abdicated that spiritual independence without which the creative life
is impossible. He was to "lose himself" now, to quote Whitman's
phrase, in "countless masses of adjustments."

CHAPTER V

THE CANDIDATE FOR GENTILITY

"Follow his call? Good heavens! That is what men do as


bachelors; but an engaged man only follows his bride."
IBSEN: The Comedy of
Love.

The Free-Thinkers' Society in "Pudd'nhead Wilson," as I have


recalled, consisted of two members, Judge Driscoll, the president,
and Pudd'nhead himself. "Judge Driscoll," says our author, "could be
a free-thinker and still hold his place in society, because he was the
person of most consequence in the community, and therefore could
venture to go his own way and follow out his own notions." As for
Pudd 'nhead, with his crazy calendar, he was a sort of outcast,
anyway; no one cared a straw what Pudd'nhead believed. It was
Mark Twain's little paraphrase, that fable, of Tocqueville's comment:
"I know of no country in which there is so little independence of
mind and real freedom of discussion as in America." Mark Twain has
corroborated this, in so many words, himself: "in our country," he
says, "we have those three unspeakably precious things: freedom of
thought, freedom of speech, and the prudence never to practise
either." An American can have a mind of his own, in short, upon one
of two conditions only: either he must be willing to stay at the
bottom of the ladder of success or he must be able to climb to the
top. No one cares to impugn a fool; no one dares to impugn a
captain of industry.
Now when Mark Twain abdicated his independence as a creative
spirit, he put his foot on the first rung of that ladder. The children of
light are all Pudd'nheads in the eyes of the children of this world,
and if Mark Twain had been able and willing to remain in the ranks
of the children of light he would have been perfectly free—to starve
and to shine. But once he had made his bid for success, he had to
accept its moral consequences. The freedom he had lost at the foot
of the ladder he could hope to regain only at the top. Meanwhile he
had to play the recognized American game according to the
recognized American rules.
Here Mark Twain was utterly at sea. His essential instinct, the
instinct of the artist, had been thwarted and repressed.
Nevertheless, just because he was essentially an artist, he was a
greenhorn in the tricks of getting on. Why, it was a constant surprise
to him at first that people laughed at his stories and gave him gold
and silver for telling them! His acquisitive instinct, no doubt, had
asserted itself with the lapse of his creative instinct; still, it was not,
so to speak, a personal instinct, it was only the instinct of his
heredity and his environment which had sprung up in a spirit that
had been swept clear for it; it was wholly unable to focus Mark
Twain. He, all his life the most inept of business men, without
practical judgment, without foresight, without any of Poor Richard's
virtues, was "never," says Mr. Howells, "a man who cared anything
about money except as a dream, and he wanted more and more of
it to fill out the spaces of this dream." Yes, to fill out the spaces the
prodigious failure of his genius had left vacant! To win fame and
fortune, meanwhile, as his parents had wished him to do, had now
become his dominant desire, and almost every one he met knew
more about the art of success than he did. He had to "make good,"
but in order to do so he had to subject himself to those who knew
the ropes. Consequently, whoever excelled him in skill, in manners,
in prestige, stood to him in loco parentis; and, to complete the ironic
circle, he was endlessly grateful to those who led him about, like a
Savoyard bear, because he felt, as was indeed true, that it was to
them he owed the success he had attained. This is the real meaning
of Mr. Paine's remark: "It was always Mark Twain's habit to rely on
somebody."
The list of those to whom he deferred is a long and varied one. In
later years, "he did not always consult his financial adviser, Mr.
Rogers," we are told, "any more than he always consulted his
spiritual adviser Twitchell, or his literary adviser Howells, when he
intended to commit heresies in their respective provinces." But these
were the exceptions that proved the rule: in general, Mark Twain
abandoned himself to the will and word of those who had won his
allegiance. There was Artemus Ward, there was Anson Burlingame,
there was Henry Ward Beecher: what they told him, and how he
obeyed, we have just seen. There was Bret Harte, who, he said,
"trimmed and trained and schooled me patiently until he changed
me from an awkward utterer of coarse grotesquenesses to a writer
of paragraphs and chapters that have found a certain favor in the
eyes of even some of the very decentest people in the land." Above
all, and among many others, there was Mr. Howells, who, from the
first moment, "won his absolute and unvarying confidence in all
literary affairs": indeed, adds Mr. Paine, "in matters pertaining to
literature and to literary people in general he laid his burden on
William Dean Howells from that day." It was to Howells that he said,
apropos of "The Innocents Abroad": "When I read that review of
yours I felt like the woman who was so glad her baby had come
white." It has become the custom with a certain school of critics to
assert that Mark Twain's spiritual rights were in some way infringed
by his associates and especially by his wife, the evident fact being
that he craved authority with all the self-protective instinct of the
child who has not learned safely to go his own way and feels himself
surrounded by pitfalls. "There has always been somebody in
authority over my manuscript and privileged to improve it," he wrote
in 1900, with a touch of angry chagrin, to Mr. S.S. McClure. But the
privilege had always emanated from Mark Twain himself.
In short, having lost the thread of his life and committed himself to
the pursuit of prestige, Mark Twain had to adapt himself to the
prevailing point of view of American society. "The middle class," says
a contemporary English writer, Mr. R.H. Gretton, "is that portion of
the community to which money is the primary condition and the
primary instrument of life"; if that is true, we can understand why
Matthew Arnold observed that the whole American population of his
time, belonged to the middle class. When, accordingly, Mark Twain
accepted the spiritual rule of the majority, he found himself leading,
to use an expression of bridge-players, from his weakest suit. It was
not as a young writer capable of great artistic achievements that he
was valued now, but as a promising money-maker capable of
becoming a plutocrat. And meanwhile, instead of being an
interesting individual, he was a social inferior. His uncouth habits, his
lack of education, his outlandish manners and appearance, his very
picturesqueness—everything that made foreigners delight in him, all
these raw materials of personality that would have fallen into their
natural place if he had been able to consummate his freedom as an
artist, were mill-stones about the neck of a young man whose
salvation depended upon his winning the approval of bourgeois
society. His "outrageousness," as Mr. Howells calls it, had ceased to
be the sign of some priceless, unformulated force; it had become a
disadvantage, a disability, a mere outrageousness! That gift of
humor was a gold-mine—so much every one saw: Mark Twain was
evidently cut out for success. But he had a lot of things to live down
first! He was, in a word, a "roughneck" from the West, on probation;
and if he wanted to get on, it was understood that he had to qualify.
We cannot properly grasp the significance of Mark Twain's marriage
unless we realize that he had been manœuvered into the rôle of a
candidate for gentility.
But here, in order to go forward, we shall have to go back. What had
been Mark Twain's original, unconscious motive in surrendering his
creative life? To fulfill the oath he had taken so solemnly at his dead
father's side; he had sworn to "make good" in order to please his
mother. In short, when the artist in him had abdicated, the family
man, in whom personal and domestic interests and relations and
loyalties take precedence of all others, had come to the front. His
home had ever been the hub of Mark Twain's universe: "deep
down," says Mr. Paine, of the days of his first triumphs in Nevada,
"he was lonely and homesick; he was always so away from his own
kindred." And at thirty-two, able to go back to his mother "without
shame," having at last retrieved his failure as a miner, he had
renewed the peculiar filial bond which had remained precisely that of
his infancy. Jane Clemens was sixty-four at this time, we are told,
"but as keen and vigorous as ever—proud (even if somewhat,
critical) of this handsome, brilliant man of new name and fame who
had been her mischievous, wayward boy. She petted him, joked with
him, scolded him, and inquired searchingly into his morals and
habits. In turn, he petted, comforted and teased her. She decided
that he was the same Sam, and always would be—a true prophecy."
It, was indeed so true that Mark Twain, who required authority as
much as he required affection, could not; fail now to seek in the
other sex some one who would take his mother's place. All his life,
as we know, he had to be mothered by somebody, and he
transferred this filial relation to at least one other person before it
found its bourn first in his wife and afterward in his daughters. This
was "Mother" Fairbanks of the Quaker City party, who had, we are
told, so large an influence on the tone and character of those travel
letters which established his fame. "She sewed my buttons on," he
wrote—he was thirty-two at the time—"kept my clothing in
presentable form, fed me on Egyptian jam (when I behaved),
lectured me awfully ... and cured me of several bad habits." It was
only natural, therefore, that he should have accepted the rule of his
wife "implicitly," that he should have "gloried," as Mr. Howells says,
in his subjection to her. "After my marriage," he told Professor
Henderson, "she edited everything I wrote. And what is more—she
not only edited my works—she edited me!" What, indeed, were Mark
Twain's works in the totality of that relationship? What, for that
matter, was Olivia Clemens? She was more than a person, she was a
symbol. After her death Mark Twain was always deploring the
responsibility he had been to her. Does he not fall into the actual
phrase his mother had used about him?—"she always said I was the
most difficult child she had." She was, I say, more than a person,
she was a symbol; for just as she had taken the place of his mother,
so at her death her daughters took her place. Mr. Paine tells how,
when Mark Twain was seventy or more, Miss Clara Clemens, leaving
home for a visit, would pin up a sign on the billiard-room door: "No
billiards after 10 P.M."—a sign that was always outlawed. "He was a
boy," Mr. Paine says, "whose parents had been called away, left to
his own devices, and bent on a good time." He used to complain
humorously how his daughters were always trying to keep him
straight—"dusting papa off," as they called it, and how, wherever he
went, little notes and telegrams of admonition followed him. "I have
been used," he said, "to obeying my family all my life." And by virtue
of this lovable weakness, too, he was the typical American male.
As we can see now, it was affection rather than material self-interest
that was leading Mark Twain onward and upward. It had always
been affection! He had never at bottom wanted to "make good" for
any other reason than to please his mother, and in order to get on
he had had to adopt his mother's values of life; he had had to
repress the deepest instinct in him and accept the guidance of those
who knew the ropes of success. As the ward of his mother, he had
never consciously broken with the traditions of Western society.
Now, a candidate for gentility on terms wholly foreign to his nature,
he found the filial bond of old renewed with tenfold intensity in a
fresh relationship. He had to "make good" in his wife's eyes, and
that was a far more complicated obligation. As we shall see, Mark
Twain rebelled against her will, just as he had rebelled against his
mother's, yet could not seriously or finally question anything she
thought or did. "He adored her as little less than a saint," we are
told: which is only another way of saying that, automatically, her
gods had become his.
It is not the custom in American criticism to discuss the relations
between authors and their wives: so intensely personal is the
atmosphere of our society that to "stoop and botanize" upon the
family affairs even of those whose lives and opinions give its tone to
our civilization is regarded as a sort of sacrilege. Think of the way in
which English criticism has thrashed out the pros and cons of
Thomas and Jane Carlyle, Percy and Harriet Shelley, Lord and Lady
Byron, and the Bronte family and the Lambs and the Rossettis! Is it
to satisfy the neighborly village ear or even a mere normal concern
with interesting relationships? At bottom English critics are so
copious and so candid in these domestic analyses because they
believe that what great writers think and feel is of profound
importance to society and because they know that what any man
thinks and feels is largely determined by personal circumstances and
affections. It is, no doubt, because of this frank, free habit of mind
that all the best biographies even of our American worthies—
Hamilton, Franklin and Lincoln, for instance—have been written by
Englishmen! No one will deny, I suppose, that Mark Twain's influence
upon our society has been, either in a positive or in a negative way,
profound. When, therefore, we know that, by his own statement, his
wife not only edited his works but edited him, we feel slightly
annoyed with Mr. Howells who, whenever he speaks of Mrs.
Clemens, abandons his rôle as a realist and carefully conceals that
puissant personage under the veil of "her heavenly whiteness." We
feel that the friend, the neighbor, the guest has prevailed in Mr.
Howells's mind over the artist and the thinker and that he is far
more concerned with fulfilling his personal obligations and his private
loyalties than the proper public task of a psychologist and a man of
letters. Meanwhile, we know that neither the wives of European
authors nor, for that matter, the holy women of the New Testament
have suffered any real degradation from being scrutinized as
creatures of flesh and blood. If one stoops and botanizes upon Mrs.
Clemens it is because, when her standards became those of her
husband, she stepped immediately into a rôle far more truly
influential than that of any President.
Olivia Langdon was the daughter of "a wealthy coal-dealer and
mine-owner" of Elmira, New York. Perhaps you know Elmira?
Perhaps, in any case, you can imagine it? Those "up-State" towns
have a civilization all their own: without the traditions of moral
freedom and intellectual culture which New England has never quite
lost, they had been so salted down with the spoils of a conservative
industrial life that they had attained, by the middle of the nineteenth
century, a social stratification as absolute as that of New England
itself. A stagnant, fresh-water aristocracy, one and seven-eighths or
two and a quarter generations deep, densely provincial, resting on a
basis of angular sectarianism, eviscerated politics and raw money,
ruled the roast, imposing upon all the rest of society its own type,
forcing all to submit to it or to imitate it. Who does not know those
august brick-and-stucco Mansard palaces of the Middle States, those
fountains on the front lawn that have never played, those bronze
animals with their permanent but economical suggestions of the
baronial park? The quintessence of thrifty ostentation, a maximum
of terrifying effect based upon a minimum of psychic expenditure!
They are the Vaticans of the coal-popes of yesteryear, and all the
Elmiras with a single voice proclaimed them sacrosanct.
We can imagine how Mark Twain must have been struck dumb in
such a presence. "Elmira," says Mr. Paine, "was a conservative place
—a place of pedigree and family tradition; that a stranger, a former
printer, pilot, miner, wandering journalist and lecturer, was to carry
off the daughter of one of the oldest and wealthiest families, was a
thing not to be lightly permitted. The fact that he had achieved a
national fame did not count against other considerations. The social
protest amounted almost to insurrection." One remembers the story
of Thomas Carlyle, that Scottish stone-mason's son, who carried off
the daughter of Dr. Welsh of Dumfries. One conceives what Carlyle's
position would have been if he had not found his own soul before he
fell in love, and if Jane Welsh had been merely the passive reflection
of a society utterly without respect for the life of the spirit. He would
have been, and would have felt himself, the interloper then—he
would not have been Carlyle but the stone-mason's son, and she
would have been the Lady Bountiful. For Mark Twain had not
married an awakened soul; he had married a young girl without
experience, without imagination, who had never questioned
anything, understood anything, desired anything, who had never
been conscious of any will apart from that of her parents, her
relatives, her friends. To win her approval and her pride, therefore—
and love compelled him to do that—he had to win the approval and
the pride of Elmira itself, he had to win the imprimatur of all that
vast and intricate system of privilege and convention of which Elmira
was the symbol. They had all said of Olivia Langdon, who was the
"family idol," that "no one was good enough for her—certainly not
this adventurous soldier of letters from the West." Charles Langdon,
her brother and Mark Twain's old comrade, was so mortified at
having brought this ignominy upon his own household, that he set
off on a voyage round the world in order to escape the wedding.
Furthermore, Mark Twain's friends in California replied unanimously
to Mr. Langdon's enquiries about his character, that, while he was
certainly a good fellow, he would make the "worst husband on
record." Would not all these things have put any lover on his mettle?
Mark Twain was on probation, and his provisional acceptability in this
new situation was due not to his genius but to the fact that he was
able to make money by it. What made the Langdons relent and
consider his candidacy was quite plainly, as we can see from Mr.
Paine's record, the vast success Mark Twain was having as a
humorous journalist and lecturer. With the publication of "The
Innocents Abroad," as we know, "he had become suddenly a person
of substance—an associate of men of consequence": even in New
York people pointed him out in the street. He was a lion, a
conquering hero, and Elmira could not help yielding to that: "it
would be difficult," as Mr. Paine says, "for any family to refuse
relationship with one whose star was so clearly ascending." But
could he, would he, keep it up? To be sure, he considered himself,
we are specifically told, not as a literary man but as a journalist; his
financial pace had been set for him; "I wasn't going to touch a
book," he wrote, "unless there was money in it, and a good deal of
it"; he had already formed those habits of "pecuniary emulation" and
"conspicuous waste" which Mr. Veblen has defined for us and which
were almost a guarantee that he would take a common-sense view
of his talent and turn it to the best financial account; three months
before his marriage, this erstwhile barefoot boy was already—the
best possible omen for one with his resources—$22,000 in debt! He
had put his shoulder to the wheel and had proved that he was able
to make money even faster than he spent it; and the instincts of the
family man had so manifested themselves in his new devotion that,
other things being equal—and his wife would see to that—he really
was a safe, conservative risk as a wealthy coal-dealer's son-in-law.
Jervis Langdon capitulated: he was a hearty soul, he had always
liked Mark Twain, anyway; now he felt that this soldier of fortune
could be trusted to cherish his daughter in the style, as people say,
to which she had been accustomed. His own household expenses
were $40,000 a year: of course they couldn't begin on that scale; it
wasn't to be expected, and besides, it wasn't the custom. But, at any
rate, he was going to start them off, and he was going to do it
handsomely. One remembers how, in "The Gilded Age," when Philip
Sterling conquers the mountain of coal that makes his fortune, he
"became suddenly a person of consideration, whose speech was
freighted with meaning, whose looks were all significant. The words
of a proprietor of a rich coal mine," our author adds, naïvely, "have a
golden sound, and his common sayings are repeated as if they were
solid wisdom." Mark Twain must have had Jervis Langdon in his
mind when he wrote that: as an aspirant to fortune, he naturally
stood in awe of a man who had so conspicuously arrived, and now
that this man had become his own bountiful father-in-law he could
not, in his gratitude, sufficiently pledge himself to keep his best
financial foot forward. Jervis Langdon gave the young couple a
house in a fashionable street in Buffalo, a house newly and fully
fitted up, with a carriage and a coachman and all the other
appointments of a prosperous ménage. It was a surprise, one of the
unforeseen delights of Mark Twain's wedding day!—he woke up, so
to speak, and found himself, with the confused and intoxicating
sensations of a bridegroom, absolutely committed to a scale of living
such as no mere literary man at the outset of his career could ever
have lived up to. He had been fairly shanghaied into the business
man's paradise! But Jervis Langdon had foreseen everything. Mark
Twain's ambition at this time, we are told, "lay in the direction of
retirement in some prosperous newspaper enterprise, with the
comforts and companionship of a home." That was the ambition,
already evoked, which his new situation confirmed, the ambition
which had now fully become his because the Langdons encouraged
it. And as he had no money actually on hand, his father-in-law
bound himself to the extent of $25,000 and advanced half of it in
cash so that Mark Twain could acquire a third interest in the Buffalo
Express. Thus, almost without realizing it, he had actually become a
business man, with love and honor obliging him to remain one.
The full consequences of this moral surrender—shall we call it?—can
only appear as we go on with our story. Meanwhile, we may note
that, precisely because of his divided soul, Mark Twain could not
consistently and deliberately pursue the main chance. Had he been
able to do so he might, in a few years, have bought his liberty; but
he lost interest in his journalistic enterprise just as he was to lose
interest in so many other lucrative enterprises in the future. And
every time he was driven back to make a fresh attempt. "I have a
perfect horror and heart-sickness over it," Mrs. Clemens wrote to her
sister after the bankruptcy of the publishing house of Charles L.
Webster and Co. "I cannot get away from the feeling that business
failure means disgrace. I suppose it always will mean that to me.
Sue, if you were to see me you would see that I have grown old
very fast during this last year: I have wrinkled. Most of the time I
want to lie down and cry. Everything seems to me so impossible."
Naturally, inevitably; but imagine an author, who was also a devoted
lover, having to respond to a stimulus like that! His bankruptcy was,
to Mark Twain, like a sudden dawn of joyous freedom. "Farewell—a
long farewell—to business!" he exclaimed during those weeks of
what might have seemed an impending doom. "I will never touch it
again! I will live in literature, I will wallow in it, revel in it; I will swim
in ink!" But when his release finally comes he writes as follows to his
wife, whom he has left in France: "Now and then a good and dear
Joe Twitchell or Susy Warner condoles with me and says, 'Cheer up
—don't be downhearted' ... and none of them suspect what a
burden has been lifted from me and how blithe I am inside. Except
when I think of you, dear heart—then I am not blithe; for I seem to
see you grieving and ashamed, and dreading to look people in the
face.... You only seem to see rout, retreat, and dishonored colors
dragging in the dirt—whereas none of these things exist. There is
temporary defeat, but no dishonor—and we will march again.
Charley Warner said to-day, 'Sho, Livy isn't worrying. So long as
she's got you and the children she doesn't care what happens. She
knows it isn't her affair.' Which didn't convince me!" No, Mrs.
Clemens, who was so far from being the votary of genius, was not
quite the votary of love either; she was, before all, the
unquestioning daughter of that "wealthy coal-dealer" of Elmira, who
had "held about a quarter of a million in her own right"; her husband
might lag and lapse as a literary man, but when he fell behind in the
race of pecuniary emulation she could not help applying the spur.
She had even invested her own patrimony in her husband's
ventures, and all that the Paige Typesetting Machine had spared
went up the chimney in the failure of Charles L. Webster and Co. Of
course Mark Twain had to retrieve that! And so it went: as the years
passed, owing to the very ineptitude that ought to have kept him out
of business altogether, he was involved more and more deeply in it.
As we can see now, the condition of Mark Twain's survival, on
probation as he was and morally pledged to make a large income,
was that he should adopt the whole code of his new environment. It
was for love's sake that he had put his head, so to say, into the
noose; in his case the matrimonial vow had been almost literally
reversed and it was he who had promised not only to love and honor
but also to obey. His loyalty was laid under further obligations by
certain family disasters that followed his marriage and by the
weakness of his wife. A neurotic, hysterical type—at sixteen, through
a fall upon the ice, she had become a complete invalid, confined to
her bed for two years in a darkened room, unable to sit, even when
supported, unable to lie in any position except upon her back till a
wizard came one day and told her, with miraculous results, to arise
and walk—Mrs. Clemens was of an almost unearthly fragility, and
she seems to have remained so during the greater part of her life. "I
am still nursing Livy night and day. I am nearly worn out," Mark
Twain writes, shortly after his marriage; and the death of their first
child, not long after, naturally intensified his almost abnormal
absorption in domestic interests, his already excessive devotion to
his wife. We recall that passionate promise he had made to his
brother: "I am in for it. I must go on chasing [phantoms] until I
marry, then I am done with literature and all other bosh—that is,
literature wherewith to please the general public. I shall write to
please myself then." What chance did he have now, preoccupied at
home, driven to support the pretentious establishment his father-in-
law had wished on him, to find his own bearings and write to please
that "self" which had never possessed any truly conscious existence?
The whole tenor of this new life was to feminize Mark Twain, to
make him feel that no loyalties are valid which conflict with domestic
loyalties, that no activities are admirable which do not immediately
conduce to domestic welfare, that private and familiar interests are,
rightly and inevitably, the prime interests of man.
"Eve's Diary," written by Mark Twain shortly after his wife's death, is
said to figure their relationship: Adam there is the hewer of wood
and the drawer of water, a sort of Caliban, and Eve the arbiter in all
matters of civilization. "It has low tastes," says Beauty of this Beast.
"Some instinct tells me that eternal vigilance is the price of
supremacy." And how Mrs. Clemens exercised it! There is something
for the gods to bewail in the sight of that shorn Samson led about by
a little child who, in the profound somnolence of her spirit, was
merely going through the motions of an inherited domestic piety.
"Her life had been circumscribed," says Mr. Paine, "her experiences
of a simple sort"; but she did not hesitate to undertake "the work of
polishing and purifying her life companion. She had no wish to
destroy his personality, to make him over, but only to preserve his
best, and she set about it in the right way—gently, and with a tender
gratitude in each achievement." To preserve his best! "She sensed
his heresy toward the conventions and forms which had been her
gospel; his bantering, indifferent attitude toward life—to her always
so serious and sacred; she suspected that he even might have
unorthodox views on matters of religion." That was before they were
married: afterward, "concerning his religious observances her task in
the beginning was easy enough. Clemens had not at that time
formulated any particular doctrines of his own.... It took very little
persuasion on his wife's part to establish family prayers in their
home, grace before meals, and the morning reading of a Bible
chapter." Thus was reëstablished over him that old Calvinistic spell of
his mother's, against which he had so vainly revolted as a child:
preserving his "best," as we can see, meant preserving what fitted
into the scheme of a good husband, a kind father and a sagacious
man of business after the order of the Jervis Langdons of this world,
for Olivia Clemens had never known any other sort of hero. "In
time," says Mr. Paine, with a terrible unconscious irony, "she saw
more clearly with his vision, but this was long after, when she had
lived more with the world, had become more familiar with its larger
needs, and the proportions of created things." It was too late then;
the mischief had long been done. Mark Twain frightened his wife and
shocked her, and she prevailed over him by an almost deliberate
reliance upon that weakness to which he, the chivalrous Southerner
—the born cavalier, in reality—could not fail to respond. Why did she
habitually call him "Youth"? Was it not from an instinctive sense that
her power lay in keeping him a child, in asserting the maternal
attitude which he could never resist? He had indeed found a second
mother now, and he "not only accepted her rule implicitly," as Mr.
Howells says, "but he rejoiced, he gloried in it." He teased her, he
occasionally enjoyed "shivering" her "exquisite sense of decorum";
but he, who could not trust his own judgment and to whom,
consequently, one taboo was as reasonable as another, submitted to
all her taboos as a matter of course. "I would quit wearing socks,"
he said, "if she thought them immoral."
It was, this marriage, as we perceive, a case of the blind leading the
blind. Mark Twain had thrown himself into the hands of his wife;
she, in turn, was merely the echo of her environment. "She was very
sensitive about me," he wrote in his Autobiography. "It distressed
her to see me do heedless things which could bring me under
criticism." That was partly, of course, because she wished him to
succeed for his own sake, but it was also because she was not sure
of herself. We can see, between the lines of Mr. Paine's record, not
only what a shy little provincial body she was, how easily thrown out
of her element, how ill-at-ease in their journeyings about the world,
but how far from unambitious she was also. It was for her own sake,
therefore, that she trimmed him and tried to turn Caliban into a
gentleman. Timid and ambitious as she was, having annexed him to
herself she had to make him as presentable as possible in order to
satisfy her own vanity before the eyes of those upon whose approval
her happiness depended. Mark Twain told once of the torture of
embarrassment with which she had had to confess at a London
dinner-table that he, the great American author, had never read
Balzac, Thackeray, "and the others." But Boston, from the point of
view of Elmira, was almost as awe-inspiring as London. Mr. and Mrs.
Clemens were often the guests of Mr. and Mrs. Howells. Here is what
Mark Twain wrote to Howells after one of these visits: "I 'caught it'
for letting Mrs. Howells bother and bother about her coffee, when it
was 'a good deal better than we get at home.' I 'caught it' for
interrupting Mrs. C. at the last moment and losing her the
opportunity to urge you not to forget to send her that MS. when the
printers are done with it. I 'caught it' once more for personating that
drunken Colonel James. I 'caught it' for mentioning that Mr.
Longfellow's picture was slightly damaged; and when, after a lull in
the storm, I confessed, shamefacedly, that I had privately suggested
to you that we hadn't any frames, and that if you wouldn't mind
hinting to Mr. Houghton, etc., etc., etc., the madam was simply
speechless for the space of a minute. Then she said: 'How could
you, Youth! The idea of sending Mr. Howells, with his sensitive
nature,'" etc. She was on pins and needles, we see, and it must have
been intolerable to her that, at the Atlantic dinners, her husband, in
spite of his immense fame, sat below the salt: her whole innocent
mood was that of a woman to whom the values of that good society
which, as Goethe said, offers no material for poetry, are the
supreme, unquestionable values and who felt that she and her brood
must at all hazards learn the ropes. Mark Twain, after the enormous
break of his Whittier Birthday speech, wrote to Mr. Howells: "My
sense of disgrace does not abate. It grows. I see that it is going to
add itself to my list of permanencies, a list of humiliations that
extends back to when I was seven years old, and which keeps on
persecuting me regardless of my repentances." Imagine a European
man of genius having to qualify, not as an individual, but as a
member of a social order into which he had not been born! Charles
Dickens never felt grateful to society because it tolerated the man
who had once been a waif of the streets: Mark Twain, as Mr. Paine
presents him, was always the barefoot boy among the gods.
Only in the light of this general subjugation of Mark Twain's
character can we understand his literary subjugation. From the
moment of his marriage his artistic integrity, already compromised,
had, as a matter of fact, been irreparably destroyed: quite literally,
as a man of letters, his honor rooted in dishonor stood and faith
unfaithful kept him falsely true. He had accepted his father-in-law's
financial assistance; he had bought his post on the Buffalo Express;
in return, he had solemnly pledged the freedom of his mind. In
these words of his Salutatory he made his pledge public: "Being a
stranger it would be immodest for me to suddenly and violently
assume the associate editorship of the Buffalo Express without a
single word of comfort or encouragement to the unoffending patrons
of this paper, who are about to be exposed to constant attacks of my
wisdom and learning. But the word shall be as brief as possible. I
only want to assure parties having a friendly interest in the
prosperity of the journal that I am not going to hurt the paper
deliberately and intentionally at any time. I am not going to
introduce any startling reforms, nor in any way attempt to make
trouble.... Such is my platform. I do not see any use in it, but
custom is law and must be obeyed." Never, surely, was a creative
will more innocently, more painlessly surrendered than in those
words; marriage had been, for Mark Twain's artistic conscience, like
the final whiff of chloroform sealing a slumber that many a previous
whiff had already induced. With that promise to be "good," to refrain
from hurting "parties having a friendly interest in the prosperity" of
his journal, the artist in Mark Twain had fallen into a final trance:
anybody could manipulate him now. We have seen that his wife,
who had become his chief censor, having no more independence of
judgment than he, simply exposed him to the control of public
opinion. This, in all matters of culture, meant New England, and
especially Boston, and accordingly to please Boston—impossible,
terrifying task!—had become as obligatory upon Mark Twain as to
please Elmira.
We have already observed the intellectual posture of Boston during
the Gilded Age. Frigid and emasculate, it cast upon the presuming
outsider the cold and hostile eye of an elderly maiden aunt who is
not prepared to stand any nonsense. "To-morrow night," writes Mark
Twain, in one of his earlier letters, "I appear for the first time before
a Boston audience—4,000 critics"; he was lecturing with Petroleum
V. Nasby, and he tells how frightened Petroleum was before the
ordeal. Fortunately, in a sense, for Mark Twain, he had, in Mr.
Howells, a charitable sponsor, a charitable intermediary; but
unfortunately for his genius Mr. Howells was no more independent
than himself: Mr. Howells was almost as much the nervous and timid
alien in Boston society as Mrs. Clemens, and as the latter's natural
ally and supreme authority in the task of shaping her husband,
instead of dispelling Mark Twain's fears he simply redoubled them.
Together, like two tremulous maids dressing the plebeian daughter
of some newly-rich manufacturer in order to make her presentable
for a court ball, they worked over him, expurgated him, trimmed him
—to his own everlasting gratitude. To Mr. Howells he wrote: "I owe
as much to your training as the rude country job-printer owes to the
city-boss who takes him in hand and teaches him the right way to
handle his art"; and of his wife he said: "I was a mighty rough,
coarse, unpromising subject when Livy took charge of me ... and I
may still be to the rest of the world, but not to her. She has made a
very creditable job of me." And no doubt that refining process was
necessary. If Mark Twain had been enabled to stand on his own feet,
had been helped to discover himself as an artist, it would have
resulted naturally from the growth of his own self-consciousness, his
own critical sense. As it was, undertaken in behalf of a wholly false,
external ideal and by people who had no comprehension of his true
principle of growth, people who were themselves subservient to
public opinion, it destroyed the last vestiges of his moral
independence. There is a sorry tale about Mark Twain's neckties that
is really symbolic of the process he was going through. It seems that
long after his marriage he still continued to wear an old-fashioned
Western string-tie which was a cause of great embarrassment to his
family and his friends, an ever-present reminder that his
regeneration was still incomplete. No one quite knew what to do
about it till at last Howells and Aldrich boldly bought him two cravats
and humored him, to his wife's infinite comfort, into wearing them.
In this way the mysteries of a provincial gentility—provincial because
it was without a sense of proportion—were kept constantly before
his mind and he, the lovable victim of his own love, a Gulliver among
the Lilliputians, a sleeping Samson, surrendered his limbs to the
myriad threads of convention, yielded his locks to the shears of that
simple Delilah his wife.
For what sort of taste was it that Mark Twain had to satisfy? Hardly a
taste for the frank, the free, the animated, the expressive! The
criticism he received was purely negative. We are told that Mrs.
Clemens and her friends read Meredith "with reverential
appreciation," that they formed a circle of "devout listeners" when
Mark Twain himself used to read Browning aloud in Hartford. Profane
art, the mature expression of life, in short, was outside Mrs.
Clemens's circle of ideas; she could not breathe in that atmosphere
with any comfort; her instinctive notion of literature was of
something that is read at the fireside, out loud, under the lamp, a
family institution, vaguely associated with the Bible and a father
tempering the wind of King James's English to the sensitive ears and
blushing cheek of the youngest daughter. Her taste, in a word, was
quite infantile. "Mrs. Clemens says my version of the blindfold
novelette, 'A Murder and a Marriage,' is 'good.' Pretty strong
language for her," writes Mark Twain in 1876; and we know that
when he was at work on "Huckleberry Finn" and "The Prince and the
Pauper," she so greatly preferred the latter that Mark Twain really
felt it was rather discreditable of him to pay any attention to
"Huckleberry Finn" at all. "Imagine this fact," he wrote to Howells; "I
have even fascinated Mrs. Clemens with this yarn for youth. My stuff
generally gets considerable damning with faint praise out of her, but
this time it is all the other way. She is become the horse-leech's
daughter, and my mill doesn't grind fast enough to suit her. This is
no mean triumph, my dear sir." And shortly afterward he wrote to
his mother: "I have two stories, and by the verbal agreement they
are both going into the same book; but Livy says they're not, and by
George I she ought to know. She says they're going into separate
books, and that one of them is going to be elegantly gotten up, even
if the elegance of it eats up the publisher's profits and mine, too." It
was "The Prince and the Pauper," a book that anybody might have
written but whose romantic mediævalism was equally respectable in
its tendency and infantile in its appeal, that Mrs. Clemens felt so
proud of: "nobody," adds Mr. Paine, "appears to have been especially
concerned about Huck, except, possibly the publisher." Plainly it was
very little encouragement that Mark Twain's natural genius received
from these relentless critics to whom he stood in such subjection, to
whom he offered such devotion; for Mr. Howells, too, if we are to
accept Mr. Paine's record, seconded him as often as not in these
innocuous, infantile ventures, abetting him in the production of
"blindfold novelettes" and plays of an abysmal foolishness. As for
Mark Twain's unique masterpiece, "Huckleberry Finn," "I like it only
tolerably well, as far as I have got," he writes, "and may possibly
pigeonhole or burn the MS. when it is done"; to which Mr. Paine
adds: "It did not fascinate him as did the story of the wandering
prince. He persevered only as the story moved him.... Apparently, he
had not yet acquired confidence or pride enough in poor Huck to
exhibit him, even to friends." And quite naturally! His artistic self-
respect had been so little developed, had been, in fact, so baffled
and abashed by all this mauling and fumbling that he could take no
pride in a book which was, precisely, the mirror of the unregenerate
past he was doing his best to live down.
Behold Mrs. Clemens, then, in the rôle of critic and censor. A
memorandum Mark Twain made at the time when he and she were
going over the proofs of "Following the Equator" shows us how she
conceived of her task. It is in the form of a dialogue between them:

Page 1,020, 9th line from the top. I think some other word
would be better than "stench." You have used that pretty often.
But can't I get it in anywhere? You've knocked it out every time.
Out it goes again. And yet "stench" is a noble, good word.
Page 1,038. I hate to have your father pictured as lashing a
slave boy.
It's out, and my father is whitewashed.
Page 1,050, 2nd line from the bottom. Change "breech-clout."
It's a word that you love and I abominate. I would take that and
"offal" out of the language.
You are steadily weakening the English tongue, Livy.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like