Home > Articles > Programming > Java

This chapter is from the book

3.4 PDF, Email, and Rich Text

So far, we have discussed the JSF enhancements provided by Facelets and the jboss-seam-ui.jar library. Those are important usability and integration features required by almost all Seam web applications. In this section, we discuss several additional UI features Seam provides. To use those features, you need to bundle more library JAR files in your application and provide extra configuration as described below. You can choose and mix the UI feature sets you want in the application while keeping its footprint and configuration complexity to a minimum.

3.4.1 Generate PDF Reports

The Facelets XHTML files generate HTML web pages by default. However, a real-world web application sometimes needs to generate PDF output for printer-ready documents such as reports, legal documents, tickets, receipts, etc. The Seam PDF library leverages the open source iText toolkit to generate PDF documents. Here is a simple Facelets file, hello.xhtml, which renders a PDF document:

<p:document xmlns:p="http://jboss.com/products/seam/pdf"
            title="Hello">
  <p:chapter number="1">
    <p:title>
      <p:paragraph>Hello</p:paragraph>
    </p:title>
    <p:paragraph>Hello #{user.name}!</p:paragraph>

    <p:paragraph>The time now is

      <p:text value="#{manager.nowDate}">
        <f:convertDateTime style="date" format="short"/>
      </p:text>

    </p:paragraph>
  </p:chapter>

  <p:chapter number="2">
    <p:title>
      <p:paragraph>Goodbye</p:paragraph>
    </p:title>
    <p:paragraph>Goodbye #{user.name}.</p:paragraph>
  </p:chapter>
</p:document>

While the hello.xhtml file has the xhtml suffix, it is really an XML file with Seam PDF UI tags. When the user loads the hello.seam URL, Seam generates the PDF document and redirects the browser to hello.pdf. The browser then displays the hello.pdf file in its PDF reader plugin or prompts the user to save the PDF file. By passing the pageSize HTTP parameter to the URL, you can specify the page size of the generated PDF document. For instance, the hello.seam?pageSize=LETTER URL produces a letter-sized hello.pdf document. Valid pageSize options also include A4, LEGAL, and others.

You can use any JSF EL expressions in the xhtml page; these EL expressions are resolved on the fly when the PDF document is rendered, just as are EL expressions on web pages. You can also use JSF converters to control text formatting, the <f:facet> tag to control table formatting, or the Facelets <ui:repeat> tag to render a list or table from dynamic data. See the Seam Reference Documentation (http://seamframework.org/Documentation) for more details on the tags.

To use the Seam PDF tags, you need to include the jboss-seam-pdf.jar and itext.jar files in the WEB-INF/lib directory of your WAR application archive.

mywebapp.ear
|+ app.war
   |+ web pages
   |+ WEB-INF
      |+ web.xml
      |+ faces-config.xml
      |+ other config files
      |+ lib
         |+ jsf-facelets.jar
         |+ jboss-seam-ui.jar
         |+ jboss-seam-debug.jar

         |+ jboss-seam-pdf.jar
  
         |+ itext.jar
|+ app.jar
|+ lib
   |+ jboss-el.jar
   |+ jboss-seam.jar
|+ META-INF
   |+ application.xml
   |+ jboss-app.xml

Then, you need to configure the PDF-related Seam component in the components.xml file. The useExtensions property indicates that the hello.seam URL should redirect to the hello.pdf URL. If the useExtensions property is set to false, the redirection would not happen and the web application would serve PDF data directly to the browser from a .seam URL, which could cause usability problems in some browsers.

<components xmlns:pdf="http://jboss.com/products/seam/pdf"
            xmlns:core="http://jboss.com/products/seam/core">
  <pdf:documentStore useExtensions="true"/>

  ... ...

</components>

Finally, you need to set up servlet filters for the .pdf files. Those filters are only needed when you have the useExtensions property set to true in the components.xml configuration we've just seen.

<web-app ...>

  ... ...

  <filter>
    <filter-name>Seam Servlet Filter</filter-name>
    <filter-class>
      org.jboss.seam.servlet.SeamServletFilter
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>Seam Servlet Filter</filter-name>
    <url-pattern>*.pdf</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>
      Document Store Servlet
    </servlet-name>
    <servlet-class>
      org.jboss.seam.pdf.DocumentStoreServlet
    </servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>
      Document Store Servlet
    </servlet-name>
    <url-pattern>*.pdf</url-pattern>
  </servlet-mapping>
</web-app>

The Seam PDF library supports generating digitally signed PDF documents. The public key configuration, however, is beyond the scope of this book. See the Seam Reference Documentation and iText documentation for more details.

3.4.2 Template-Based Email

Sending email from your web application is not hard—but it can be a messy task. The standard JavaMail API requires developers to embed the email messages as literal strings inside Java code. That makes it very difficult to write rich email (i.e., HTML email with elaborate text formatting and embedded images), and makes it nearly impossible for non-developers to design and compose the email messages. The lack of design and branding in email messages is a major weakness in many web applications.

In Seam, we provide a template-based approach to handling email. A business person or a page designer writes the email as a web page. Here is an example email template page hello.xhtml:

<m:message xmlns="http://www.w3.org/1999/xhtml"
           xmlns:m="http://jboss.com/products/seam/mail"
           xmlns:h="http://java.sun.com/jsf/html">
  <m:from name="Michael Yuan" address="myuan@redhat.com"/>
  <m:to name="#{person.firstname} #{person.lastname}">
    #{person.address}
  </m:to>
  <m:subject>Try out Seam!</m:subject>
  <m:body>
  <p>Dear #{person.firstname},</p>
  <p>You can try out Seam by visiting
  <a href="http://labs.jboss.com/jbossseam">
    http://labs.jboss.com/jbossseam
    </a>.</p>
  <p>Regards,</p>
  <p>Michael</p>
  </m:body>
</m:message>

When a web user needs to send out the hello.xhtml message, he or she clicks on a button or a link to invoke a Seam backing bean method to render the hello.xhtml page. Below is an example method to send the hello.xhtml email. The message recipient is dynamically determined at runtime via the #{person.address} EL expression. Similarly, you can dynamically determine the sender address or any content in the message via EL expressions.

public class ManagerAction implements Manager {

  @In(create=true)
  private Renderer renderer;

  public void send() {
    try {
      renderer.render("/hello.xhtml");
      facesMessages.add("Email sent successfully");
    } catch (Exception e) {
      facesMessages.add("Email sending failed: " + e.getMessage());
    }
  }
}

If a message has multiple recipients, you can insert multiple <m:to> tags using the Facelets <ui:repeat> tag. You can also use the Facelets <ui:insert> tag to compose messages from a template.

To use the Seam email support tags, you need to bundle the jboss-seam-mail.jar file in the WEB-INF/lib directory of your WAR archive.

mywebapp.ear
|+ app.war
   |+ web pages
   |+ WEB-INF
      |+ web.xml
      |+ faces-config.xml
      |+ other config files
      |+ lib
         |+ jsf-facelets.jar
         |+ jboss-seam-ui.jar
         |+ jboss-seam-debug.jar

         |+ jboss-seam-mail.jar
|+ app.jar
|+ lib
   |+ jboss-el.jar
   |+ jboss-seam.jar
|+ META-INF
   |+ application.xml
   |+ jboss-app.xml

Then, you need to configure an SMTP server to actually send the email. That is done via the Seam mailSession component in components.xml. You can specify the host name, port number, and login credentials for the SMTP server. Here is an example SMTP configuration:

<components xmlns="http://jboss.com/products/seam/components"
            xmlns:core="http://jboss.com/products/seam/core"
            xmlns:mail="http://jboss.com/products/seam/mail">

  <mail:mailSession host="smtp.example.com"
                    port="25"
                    username="myuan"
                    password="mypass" />
  ... ...

</components>

3.4.3 Display Rich Text

A community-oriented web application often needs to display user-contributed content (e.g., forum posts, comments etc.). Here, a big issue is how to allow rich text formatting in user-contributed content. Allowing the web user to submit arbitrary HTML-formatted text is out of the question, as raw HTML is insecure and prone to various cross-site scripting attacks.

One solution is to use a WYSIWYG rich text editor widget to capture user input. The widget transforms its content to sanitized HTML when the form is submitted to the server. Refer to Section 21.3.2 for more on this subject.

Another solution, which we cover here, is to provide the web users with a small set of non-HTML markup tags they can use to format the content. When the application displays the content, it automatically converts the markup to HTML tags. A popular non-HTML text markup language is Wikitext which is widely used on wiki community sites (e.g., the http://wikipedia.org site). The Seam <s:formattedText> UI component converts Wikitext to HTML formatted text. For instance, suppose that the #{user.post} Seam component contains the following text:

It's easy to make *bold text*, /italic text/,
|monospace|, -deleted text-, super^scripts^,
or _underlines_.

The UI element <s:formattedText value="#{user.post}"/> would produce the following HTML text on the web page:

<p>
It's easy to make <b>bold text</b>,
<i>italic text</i>, <tt>monospace</tt>
<del>deleted text</del>, super<sup>scripts</sup>,
or <u>underlines</u>.
</p>

Support for the <s:formattedText> tag is already included in the jboss-seam-ui.jar file. But it depends on the ANTLR (ANother Tool for Language Recognition, see www.antlr.org) parser to process the Wikitext grammar. In order to use the <s:formattedText> tag, you need to bundle the ANTLR JAR in your WAR archive:

mywebapp.ear
|+ app.war
   |+ web pages
   |+ WEB-INF
      |+ web.xml
      |+ faces-config.xml
      |+ other config files
      |+ lib
         |+ jsf-facelets.jar
         |+ jboss-seam-ui.jar
         |+ jboss-seam-debug.jar

         |+ antlr-x.y.z.jar
|+ app.jar
|+ lib
   |+ jboss-el.jar
   |+ jboss-seam.jar
|+ META-INF
   |+ application.xml
   |+ jboss-app.xml

With the ANTLR parser, Seam can potentially support other markup languages beyond the Wikitext. For instance, it might one day support sanitized HTML (i.e., HTML text with all potential security loopholes removed), BBCode (widely used in online forms), and others. Refer to Seam documentation for the latest updates on this subject.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020