How to use conditional stylesheets or javascript with JSF

Standard

A annoying part of JSF is that it will strip out all of your conditional statements. These conditional references are needed for IE bug fixes 99% of the time. The solution is a simple hack using the outputText component. This will treat the html entities as strings and convert them.

For example this outputText will render the html5shiv cdn.

<h:outputText
value="&lt;!--[if lte IE 8]&gt;
&lt;script src=&quot;//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js&quot;&gt;&lt;/script&gt;
&lt;![endif]--&gt;"
escape="false" />

Results

<!--[if lte IE 8]>
  <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<![endif]-->

Now once rendered the browser will be able to correctly interpret your conditional statements.

Primefaces bootstap styling loading modal

Standard

Building enterprise level application often requires loading large amount of data. This process can take some time. To provide a quality experience end users expect loading screens. This informs the user that they are interacting with the application.

Using Primefaces and Bootstrap 3 javascript you can easily alert end users when the server is working on processing data.

Consider the case of an end user is searching a database for collection of cars. The database may contain N amount of cars. Therefore, we must assume the process could take up to several hundred milliseconds. This is perfect situation for a loading bar.

The modal

The modal is a standard Bootstrap 3 Modal and has a simple progress bar. In the footer there is a reloading link in case the ajax call fails to return a response from the server.

<div class="modal fade" id="pleaseWaitDailog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Processing</h4>
      </div>
      <div class="modal-body">
        <div class="progress">
           <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="99" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
              <span class="sr-only">99% Complete</span>
           </div>
        </div>
      </div>
      <div class="modal-footer">
        Stuck? <a href="javascript: window.location.reload()">try reloading...</a>
      </div>
    </div>
  </div>
</div>

Primefaces events

The commandLink component of primefaces offers many great features. The most useful for this senario is the onstart and onsucess event. Onstart executes a javascript method when the ajax request begins to the server, the oncomplete executes a method when the response of returned from the server. There is no guarantee that the response will come back, this is why the modal has the reloading link.

<p:commandLink id="search" action"#{myBean.doSearch}" update="searchResults" styleClass="btn btn-primary" onstart="$('#pleaseWaitDailog').modal('show');" onsuccess="$('#pleaseWaitDailog').modal('hide');">
   <i class="fa fa-search"></i> Search
</p:commandLink>

Using this commandLink, it will call the bootstrap modal library to show, then hide the processing modal defined above. This will give the end user a better interaction with the server.

Bootstrap 3 + Primefaces 5 datatable styling

Standard

Using the default theme libraries supplied by Primefaces can make developing a custom look difficult. Having to override / make your own entire primefaces theme becomes painful; bootstrap 3 is the solution. Marrying Primefaces 5 component library and Bootstrap 3 renders a uniform design.

The following is a typical look of the Primefaces “boostrap” theme. Notice the headers on the columns as they have a background image. This design also lacks some functionality with different sized browsers.

Primefaces boostrap theme

Typical primefaces look

Utilizing the bootstrap 3 libraries the table can become responsive, have better design, and require little coding. Notice the difference in various design elements.

Disabled the default theme

Boostrap 3 with Primefaces 5 themes disabled

To marry primefaces and boostrap 3 it requires 3 steps; modifying the web.xml, setting class properties on the datatable, and overriding some default Primefaces css.

Web.xml

The Primefaces community supplies roughly 40 themes to choose from. We however, are not going to use any of them. Place the following code in your web.xml

<context-param>
   <param-name>primefaces.THEME</param-name>
   <param-value>none</param-value>
</context-param>

Setting the property above assures only the base styling will be rendered.

XHTML Page

On the desired page output a dataTable and attach the tableStyleClass attribute to it. The “table” and “table-striped” are Bootstrap css classes. Surround the entire dataTable with a div tag class “table-responsive”. The dataTabe is now responsive utilizing bootstrap css.

<div class="table-responsive">
   <p:dataTable tableStyleClass="table table-striped" value="#{myBean.itms}" var="itm">
      <p:column headerText="Column Name">
         <h:outputText value="#{itm.title}"/>
      </p:column>
   </p:dataTable>
</div>

Extra CSS

The default Primefaces css may still interact with the above dataTable rendering unwanted borders. The solution is to reset the css ui-datatable class generated by Primefaces like so:

.ui-datatable thead th, .ui-datatable tbody td, .ui-datatable tfoot td {
    border-style: none;
}

JAAS login module in Tomcat 7 example (Part 2)

Standard

Part 1 of this tutorial demonstrated how to implement a login module using JAAS + Tomcat 7. This next segment shows how to create a login form and call the login module.

Folder Structure:

/login.xhtml
/error.xhtml
/protected/index.html (protected via our web.xml file)

Simple JSF login page

The following is a simple form used to submit the username and password to a backing bean called loginBean. The form uses HTML5 passthrough elements, as well as built in JSF validators on the input fields. All errors are displayed using the h:messages output.

<h:form>
    <h3>Please sign in</h3>
    <h:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Please enter your username" p:placeholder="Username" p:autofocus="true">
        <f:validateLength maximum="50" minimum="3" />
    </h:inputText>

    <h:inputSecret id="password" value="#{loginBean.password}" required="true" requiredMessage="Enter your password" p:placeholder="Password">
        <f:validateLength maximum="20" minimum="3" />
    </h:inputSecret>

    <h:messages/>

    <h:commandButton type="submit" value="Sign in" id="submit" action="#{loginBean.login()}"/>
</h:form>

Calling the login module

Once the form passes validation the login() action is called. The login action uses the submitted username / password to request a login from the servlet container. This will call the login module created in part 1 of this tutorial. If the request.login() servlet request fails, it throws a LoginException which is caught in the form of a ServletException below. If the login succeeds then the user is redirected to the protected page.

@ManagedBean(name = "loginBean")
@ViewScoped
public class LoginBean implements Serializable {
    
    private static final long serialVersionUID = 1L;

    private String username;
    private String password;

    /**
     *
     * @return
     */
    public String login() {

        try {

            // Get the current servlet request from the facesContext
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) ctx.getExternalContext().getRequest();

            // Do login from the container (will call login module)
            request.login(username, password);

            return "/protected/index.xhtml?faces-redirect=true";

        } catch (ServletException ex) {

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An Error Occured: Login failed", null));
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "login.xhtml";
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

}

This concludes the configuration and implementation of JAAS container managed security. The original working copy of the complete project is available on Github.

Creating a simple JSF component: Google URL shortener

Standard

This article shows how to make a simple component in JSF. The component will utilize the google url shortener. The final result will have a custom taglib and can be passed any URL for shortening as follows:

<six:urlshortener id="googleURL" url="http://yoursite.com" />

The custom component will comprise of 4 files: API, Component, Renderer, and Taglib.xml.

The first file is the renderer which is responsible for the visual representation of the component. It extends the javax.faces.render.Renderer class. A responseWriter is used to open and close elements to be written to the DOM. A typical renderer may have both a encodeBegin / encodeEnd method, however for this example it is unnecessary as we only need render tags after encoding the URL from Google. The renderer can be identified by RENDERER_TYPE which corresponds to the Taglib.xml later in this article.

@FacesRenderer(componentFamily = UrlShortenerComponent.COMPONENT_FAMILY, rendererType = UrlShortenerRenderer.RENDERER_TYPE)
public class UrlShortenerRenderer extends Renderer {

    /**
     * * Renderer type of {@link UrlShortenerRenderer}.
     */
    public static final String RENDERER_TYPE = "com.sixthpoint.jsf.google.url.shortener.components.UrlShortenerRenderer";

    private static final Logger LOG = Logger.getLogger(UrlShortenerRenderer.class.getName());

    @Override
    public void encodeEnd(FacesContext context, UIComponent uicomponent) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        UrlShortenerComponent component = (UrlShortenerComponent) uicomponent;
        try {
            writer.startElement("a", component);
            writer.writeAttribute("id", component.getClientId(), "id");

            try {

                String url = component.getGoogleURL(component);
                writer.writeAttribute("href", url, "href");

                String style = (String) component.getAttributes().get("style");
                if (style != null) {
                    writer.writeAttribute("style", style, null);
                }

                writer.write(url);

            } catch (IOException ex) {
                writer.write(ex.getMessage());
                LOG.log(Level.SEVERE, "Could not generate Google short URL", ex);
            }

            writer.endElement("a");
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Error generating markup", ex);
        }
    }
}

The renderer calls the component getGoogleUrl method. This component is inserted into the component tree by the componentFamily attribute which has been annotated by @FacesRenderer. The two important methods defined by the UrLShortenerComponent below are: getFamily, and getGoogleURL.

Since the rendering has been delegated, the getFamily method is overrides the extended UI Component. This override returns the identifier, which is used to refer to the component that can be rendered by the renderer. A StateHelper is used to store the value of the url attribute between requests.

The getGoogleURL method is called by the renderer and is intended to represent the meaning / purpose of the component. The class is extended from the javax.faces.component.UIComponent and is bound by its component name to the renderer during the request-processing lifecycle.

@FacesComponent(UrlShortenerComponent.COMPONENT_TYPE)
public class UrlShortenerComponent extends UIComponentBase {

    /**
     * * Component family of {@link UrlShortenerComponent}.
     */
    public static final String COMPONENT_FAMILY = "UrlShortener";

    /**
     * * Component type of {@link UrlShortenerComponent}.
     */
    public static final String COMPONENT_TYPE = "UrlShortener";

    /**
     * Attribute name constant for url.
     */
    private static final String URL_TAG = "url";

    /**
     * Default value for the url attribute.
     */
    private static final String URL_DEFAULT = "http://www.sixthpoint.com/";

    /**
     * Set the component tree family name
     *
     * @return
     */
    @Override
    public String getFamily() {
        return UrlShortenerComponent.COMPONENT_FAMILY;
    }

    /**
     * Perform API call
     *
     * @param component
     * @return
     * @throws IOException
     */
    public String getGoogleURL(UIComponent component) throws IOException {

        UrlShortenerAPI api = new UrlShortenerAPI();
        return api.getGoogleURL(getUrl());
    }

    /**
     * Get the tag value from the state helper
     *
     * @return
     */
    public String getUrl() {
        return (String) getStateHelper().eval(URL_TAG, URL_DEFAULT);
    }

    /**
     * Set the tag value to the state helper
     *
     * @param url
     */
    public void setUrl(String url) {
        getStateHelper().put(URL_TAG, url);
    }

}

The final piece of the puzzle is the API. This file is where the call to Google’s API to encode the URL is made. The URLShortenerAPI is a POJO class intended to separate UiComponent logic from business logic.

public class UrlShortenerAPI {

    /**
     * URL to the REST service.
     */
    private static final String API_URL = "https://www.googleapis.com/urlshortener/v1/url";

    /**
     * Property in the JSON output to be extracted.
     */
    private static final String PROPERTY_CONTAINING_OUTPUT = "id";

    /**
     * Gets the shortened URL from Google.
     *
     * @param url
     * @return String
     * @throws IOException
     */
    public String getGoogleURL(String url) throws IOException {

        OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, API_URL);

        // Set header content
        oAuthRequest.addHeader("Content-Type", "application/json");

        // Payload
        oAuthRequest.addPayload("{\"longUrl\": \"" + url + "\"}");

        // Send the request
        Response r = oAuthRequest.send();

        // Determine generic map type
        Type typeOfMap = new TypeToken<Map<String, String>>() {
        }.getType();

        // Json -> Map
        Map<String, String> responseMap = new GsonBuilder().create().fromJson(r.getBody(), typeOfMap);

        return responseMap.get(PROPERTY_CONTAINING_OUTPUT);

    }
}

To use this component properly you need to configure a taglib. This taglib file is to be placed in the /WEB-INF/googleurlshortener.taglib.xml. I have created my own namespace as seen below. Notice that it defines the same component-type, renderer-type, and attributes needed to statisfy the component.

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
    version="2.0">
    <namespace>http://com.sixthpoint.google/urlshortener</namespace>
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.2</jsp-version>
    <short-name>googleurlshortener</short-name>
    <uri>http://www.sixthpoint.com/</uri>
    <tag>
        <tag-name>urlshortener</tag-name>
        <component>
            <component-type>UrlShortener</component-type>
            <renderer-type>com.sixthpoint.jsf.google.url.shortener.components.UrlShortenerRenderer</renderer-type>
        </component>
        <attribute>
            <name>url</name>
            <type>java.lang.String</type>
            <description>The url that is to be shortened.</description>
        </attribute>
    </tag>
</facelet-taglib>

To use add the namespace to your file with whatever prefix you define and call the urlshortener method.

The complete project project code can be found on GitHub.