Flex On Java 1st Edition Bernerd Allmon Jeremy Anderson pdf download
Flex On Java 1st Edition Bernerd Allmon Jeremy Anderson pdf download
Anderson download
https://ebookbell.com/product/flex-on-java-1st-edition-bernerd-
allmon-jeremy-anderson-34416118
https://ebookbell.com/product/pro-flex-on-spring-1st-edition-chris-
giametta-auth-4390884
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
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
https://ebookbell.com/product/with-god-on-our-side-steven-
flixjger-59377170
https://ebookbell.com/product/nuclear-engineering-handbook-hands-on-
with-python-nuclear-engineering-essentials-1st-edition-jamie-
flux-201892700
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
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.
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
1.4 Summary 11
www.it-ebooks.info
X CONTENTS
2.8 Summary 37
www.it-ebooks.info
CONTENTS vii
4.9 Summary 88
www.it-ebooks.info
viii CONTENTS
www.it-ebooks.info
X CONTENTS
www.it-ebooks.info
X CONTENTS
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
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.
xvii
www.it-ebooks.info
xviii ABOUT THIS BOOK
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.
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
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?
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
Figure 1.1 Comparing a Java applet DataGrid (left) to a Flex Advanced DataGrid
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.
www.it-ebooks.info
A whirlwind tour of Flex 5
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 ?
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.
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.
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.
www.it-ebooks.info
31 CHAPTER 1 Some Flex with yourJava ?
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.
<?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>
www.it-ebooks.info
Finding the right tools and patterns 9
Lo»n j
Shirty Saius
10:
Project [ i
De&Cfp
iDon: I
Sovony |
| Retrain US! |
Rftpor»3 By
Reported On: J3
Aasiflned To:
Efrbtiaiad HOLTS:
www.it-ebooks.info
10 CHAPTER 1 Some Flex with yourJava ?
www.it-ebooks.info
Summary 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
www.it-ebooks.info
14 CHAPTER 2 Beginning with Java
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
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
mvn archetype:create
-DgroupId=org.foj
-Dartifactld=flex-bugs
-DarchetypeArtifactld=maven-archetype-site-simple
mvn archetype:create
-DgroupId=[Java:the project's group id]
-Dartifactld=[Java:the project's artifact id]
-DarchetypeArtifactld=maven-archetype-site
<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
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
<modules>
<module>flex-bugs-web</module>
</modules>
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
[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
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>
AppFuse
Providino integration and style to open source Java.
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
www.it-ebooks.info
43 CHAPTER 2 Beginning with Java
import org. apache. commons . lang. builder. EqualsBuilder; <—Q Import declarations
J
Java persistence
©Entity framework
public class Issue extends BaseObject implements Serializable {
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
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;
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.
www.it-ebooks.info
22 CHAPTER 2 Beginning with Java
©Entity
public class Comment extends BaseObject implements Serializable { <1—
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long g e t l d O {
return id;
(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;
(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.
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.
www.it-ebooks.info
47 CHAPTER 2 Beginning with Java
public CommentDaoImpl() {
super(Comment.class);
}
(iOverride
(iSuppressWarnings ("unchecked")
public List<Comment> getCommentsBylssueld(Long issueld) {
return getHibernateTemplate().find
("from Comment where issue_id = ?", issueld);
}
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
www.it-ebooks.info
Build the services 25
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.
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 {
J
Default no arg
public IssueManagerlmpl!) { 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
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 {
1
public void deleteAHCommentsForlssueld(Long issueld) {
Delete all
commentDao.deleteAHCommentsForlssueld(issueld); comments
} for issue
www.it-ebooks.info
Wiring things together with Spring 27
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.
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
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
www.it-ebooks.info
Constructing the web tier 29
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;
if (delete != null) {
return delete();
}
boolean isNew = (issue.getld() == null);
issue = issueManager.save(issue);
if (!isNew) {
return INPUT;
} else {
return SUCCESS;
www.it-ebooks.info
30 CHAPTER 2 Beginning with Java
<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"/>
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
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.
ebookbell.com