What is a JSF component binding? How can I use it?

Standard

One of the more flexible features of Java Server Faces is the ability to use bindings within a view. Most developers omit the binding attribute and rely on a component libraries magic to display errors to the end user. Using the JSF binding component it is possible to specify the binding view component name for the UIComponent in the java backing bean. This binding refers to an instance of UIComponent in the EL scope allowing you to access certain properties #{mybinding.clientId}, #{mybinding.value},  #{mybinding.valid},  #{mybinding.submittedValue}

For example, lets assume you have a selectOneMenu with a list of items. These items are U.S states, then below you have a inputText area where the end user enters his/her city. We do not want to allow them to enter a city that is not in a state.

The problem can be solved using bindings. Consider this solution that binds the selected state value to the city entered. When submitted the validator will have access to both components.

The View

<h:selectOneMenu binding="#{state}" value="#{myBean.selectedState}">
    <f:selectItems value="#{myBean.states}" />
</h:selectOneMenu>
<h:inputText value="#{myBean.city}">
    <f:attribute name="state" value="#{state.value}" />
    <f:validator validatorId="locationValidator" />
</h:inputText>

Backing validator

@FacesValidator("locationValidator")
public class LocationValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) {
        Object item = component.getAttributes().get("state");
        // Object value holds city name
    }

}

Using bindings as described provides a solution for more complex validation requirements.

Using bindings with Bootstrap 3

Arguably the most popular css library out is Boostrap 3. It provides a sleek look to web pages. Using component bindings you can easily marry JSF with Bootstrap CSS. This is because components have a isValid EL expression attached to them.

For example lets assume you have a inputText that requires a min length of 4 and a max of 6. If outside of that requirement you want the field to be marked as invalid.

To highlight invalid fields use the binding component together with a form-group. The form-group has a has-error CSS class that will highlight the field inside. Once the inputText validation fails and refreshes the screen it will call the EL expression #{name.valid} and render the has-error class.

<div class="form-group  #{!name.valid ? 'has-error' : 'none'}">
   <label for="name" class="control-label">Enter name</label>
   <h:inputText value="#{myController.name}" binding="#{name}" id="name" styleClass="form-control">
      <f:validateLength minimum="4" maximum="6" />
   </h:inputText>
</div>

Whats the difference between #{mybinding.value} and  #{mybinding.submittedValue}?

This can be answered by understanding that the order of components matters. JSF will process your components in the order they appear in the view. The backing javascript for JSF does this. So for example if I was to swap the order of my state / city example so that the selectOneMenu came after the city inputText I would need to use the bindings submittedValue as ordering would cause the binding to be empty on the validator.

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.

Creating user accounts with grants in MYSQL

Standard

After you have installed a mysql database, setup root permissions, and added a few schemas it is time to start adding users. When adding users it is likely that different users call for different databases. This can be handled by using GRANTS in mysql.

To begin we will assume that there are two databases; PROD and DEVEL. We also have two users; Sarah, and Jessie. Sarah is assigned to the PROD database, while Jessie can only work on the DEVEL.

Create a new user

Start first by creating both users, the % signifies they can login from any location.

CREATE USER 'sarah'@'%' IDENTIFIED BY 'myPassword';
CREATE USER 'jessie'@'%' IDENTIFIED BY 'myPassword';

Grant permissions

Next they need to be granted permissions to access his/her working database.

# Sarah gets prod database
GRANT ALL PRIVILEGES ON PROD.* TO 'sarah'@'%' WITH GRANT OPTION;

# Jessie gets devel database
GRANT ALL PRIVILEGES ON DEVEL.* TO 'jessie'@'%' WITH GRANT OPTION;

At this point, if sarah logged in she would only see the PROD database. As expected if Jessie logged in he would only see the DEVEL database. They now only have permissions to there own separate databases.

Reset a password

Lets say you forget sarah’s assigned password. It can easily be reset with the following command.

SET PASSWORD FOR ‘sarah’@'%’ = PASSWORD(‘myNewPassword’);

Other useful commands

# Show all users; identification
select user,host from mysql.user;

# Show a users grants
SHOW GRANTS FOR 'sarah'@'%';

 

 

BackboneJS utilizing a event aggregator

Standard

When creating dynamic single page applications (SPA) a project can become rather large containing multiple views. These views may need to share or be alerted if the other view changes. BackboneJS can alert views if models data changes using the listenTo method.

this.listenTo(this.model, 'change', this.render);

However, lets assume you do not wish to pass a reference to a model in each of the views. It would be nice to have a way to pass data between the views another way; hence an event aggregator.

To demonstrate this consider this simple wine application. A user has the ability to modify the wine name or year. When the user data is submitted a dispatcher event is triggered alerting the wineView to rerender the set contents.

backbone-event-aggregator

Sample application

The Application

The first step is to create each view and pass in the event aggregator.

var aggregator = _.extend({}, Backbone.Events);

var formView = new FormView({ag: aggregator, model: new WineModel()});
var wineView = new WineView({ag: aggregator});

The formView binds to the click of the setData event which will update our wine model data. It then uses the event aggregators trigger method to alert all other views listening (the wineView) of the new data. The wine data model is passed in the trigger so a reference to the wine model is not needed in the wineView.

var FormView = Backbone.View.extend({
    el: '#input',
    aggregator: null,
    initialize: function (options) {
        this.aggregator = options.ag;
        this.render();
    },
    events: {
        "click #setData": "setData",
        "click .reset": "reset"
    },
    render: function () {
        this.$el.html(formTemplate);
        return this;
    },
    setData: function () {
        if ($("#name").val() !== "") {
            this.model.set({name: $("#name").val()});
        }
        if ($("#year").val() !== "") {
            this.model.set({year: $("#year").val()});
        }
        this.aggregator.trigger("aggregateEvent", this.model);

        return false;
    },
    reset: function () {
        this.model.clear().set(this.model.defaults);
        this.aggregator.trigger("aggregateEvent", this.model);

        return false;
    }
});

The wineView binds to the event “aggregateEvent” and when it is fired rerenders the view using the model data passed from the formView.

var WineView = Backbone.View.extend({
    el: '#output',
    initialize: function (options) {
        _.bindAll(this, "render");
        options.ag.bind("aggregateEvent", this.render);
    },
    render: function (model) {
        var compiledTemplate = _.template(WineTemplate)(model.toJSON());
        this.$el.html(compiledTemplate);
        return this;
    }
});

To see this event aggregator in action checkout my Github page and checkout a working example.

 

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 boostrap theme design

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

Bootstrap 3 with Primefaces 5 theme 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;
}

Using tmpwatch to free resources

Standard

Tmpwatch is a service that can recursively remove files that haven’t been accessed for a given period of time. In the case of CentOS it comes standard. If not enabled to run periodically, the tmp folder will expand until either the server is restarted, or it hits its disk resource limit. If the tmp folder does become to large, all programs that rely on temporary files will fail.

Ex: A apache webserver runs a php script which logs information for referencing. These log files are unwritable due to a lack of disk resources.

It will appear to be a permissions read / write error. However, a simple execution of the following tmpwatch command will free up space and delete all files older than 12 hours.

tmpwatch 12 /tmp

Note: Never delete all files in the tmp folder as they may be utilized for semaphore locking by various applications (mysql).

2 way encryption with MD5 DES

Standard

Data encryption standard (DES) is a old way of encrypting data. It effectively encrypts data to a unreadable string; however it should be noted that it is not secure. The following code is for demonstration purposes only and should not be implemented as a security protocol. DES is a breakable algorithm smaller key, and block size than a advanced encryption standard (AES) algorithm.

Use case

A user is prompted to enter some non sensitive data. For the sake of this example lets assume we have a requirement that the user telephone number must be encrypted. The user enters a phone number and the encode method secures the data for storage in the database. Upon rendering back to the end user the data is translated using the decode method.

public class MD5andDES {

    // A user chosen password used for the PEKeySpec. Once set do not change or all previously encoded data will be lost
    private static final char[] PBEKeyPassword = "nviowefjklaasdlkjweklnvq".toCharArray();

    // Private salt for PBE algorithm
    private static final byte[] PBESALT = {(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12};

    /**
     * Takes in a string which is then salted with a given password used for the
     * 2 way encryption
     *
     * @param data
     * @return
     * @throws GeneralSecurityException
     * @throws UnsupportedEncodingException
     */
    public static String encode(String data) throws GeneralSecurityException, UnsupportedEncodingException {

        // Get algorithm to use
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

        // Generates a secretKey object from the provided key specification
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PBEKeyPassword));

        // Returns a cipher object that implements the specified transformation
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initializes cipher with public key
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(PBESALT, 20));

        // Returns the cipher encoded to a 64bit string (aka base64 encoded). getBytes() forms a new byte array
        return DatatypeConverter.printBase64Binary(pbeCipher.doFinal(data.getBytes("UTF-8")));
    }

    /**
     * Takes in encrypted data and uses the salt to decrypt it to its original
     * state
     *
     * @param data
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public static String decode(String data) throws GeneralSecurityException, IOException {

        // Get algorithm to use
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

        // Generates a secretKey object from the provided key specification
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PBEKeyPassword));

        // Returns a cipher object that implements the specified transformation
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initializes cipher with public key
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(PBESALT, 20));

        // Returns a string of the orignally encrypted data
        return new String(pbeCipher.doFinal(DatatypeConverter.parseBase64Binary((data))), "UTF-8");
    }

}

A complete working copy with test cases is available for checkout on Github.

BufferedImage JPEG transparency using OpenJDK

Standard

When attempting to write a transparent JPEG to disk using OpenJDK 5,6,7 javax.imageio.IIOException error is thrown. This occurs because OpenJDK does not have a native JPEG encoder. There are two separate solutions.

Solution 1: Change the library

A alternative would be to switch from OpenJDK to Sun’s JDK which has a native JPEG encoder.

Solution 2: Buffered image write around

A programmatic way to solve the problem is to map or draw the existing BufferedImage onto a new BufferedImage with the type changed from TYPE_4BYTE_ABGR (default) to TYPE_3BYTE_BGR (new). The converted image will now be writable to disk.

// Read in the uploaded file
InputStream input = file.getInputstream();
BufferedImage originalImg = convertInputStreamToBufferedImage(input);

// Converts the buffered image to the required type then draws the original on top
BufferedImage convertedImg = new BufferedImage(originalImg.getWidth(), originalImg.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
convertedImg.getGraphics().drawImage(originalImg, 0, 0, null);
convertedImg.getGraphics().dispose();

// Write to disk
ImageIO.write(convertedImg, "jpeg", new File("/PATH/filename.jpg"));

 

PBKDF2 with HMAC-SHA1 encryption class

Standard

Sensitive user data must insure confidentiality and integrity. The following class is a example of how to use a password based key derivation function (PBKDF2) algorithm to encode / decode data. Using the createHash method a salt and hash byte array is generated from a instance of the PBKDF2WithHmacSHA1 from the secretKeyFactory. The byte arrays that are returned serve as your encrypted data. You must have both to be able to validate.

Use case

A user signs up for a account on your website. They enter a username / password. The password that is entered is ran against the createHash method. The result (salt, hash) are stored in a database. This is the users login data encrypted. Whenever a user attempts to login with that username, the salt and hash are retrieved from the database and the validatePassword method is called. If the test passes you are assured they are a legitimate user and may proceed.

What is slowEquals?

When a password is validated it requires that slowEquals be true. SlowEquals is a method designed to prevent against timing attacks. What this does is assure that the attacker cannot determine how long it took for the password to fail. It iterates through all values in the byte array regardless if they are equal or not. This prevents the attacker from having enough information compute a off line attack.

public class HmacSHA1 {

    // Used in encryption for how many cycles
    private static final int PBKDF2_ITERATIONS = 2000;
    private static final Integer checkLoops = 10;
    private static final String password = "changeit";

    /**
     * Typical test case to assure that Encoding / Decoding / Encryption work
     * properly
     *
     * @param args
     */
    public static void main(String[] args) {

        System.out.println("Encryption Test\n");
        
        for (int i = 0; i <= checkLoops; i++) {
            
             try {
                // Create has in the form of (salt:hash)
                String hash = createHash(password);
                String[] params = hash.split(":");
                byte[] salt = fromHex(params[0]);
                byte[] hash5 = fromHex(params[1]);

                // Compare our generated bytes to the orignal
                if (validatePassword(password, hash5, salt)) {
                    System.out.println("valid password!");
                }
            } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
                System.out.println("ERROR: " + ex);
            }
        }
    }

    /**
     * Validates a password using a hash.
     *
     * @param password the password to check
     * @param hash
     * @param salt
     * @return true if the password is correct, false if not
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.spec.InvalidKeySpecException
     */
    public static boolean validatePassword(char[] password, byte[] hash, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {

        // Compute the hash of the provided password, using the same salt, iteration count, and hash length
        byte[] testHash = pbkdf2(password, salt, PBKDF2_ITERATIONS, hash.length);

        // Compare the hashes in constant time. The password is correct if both hashes match.
        return slowEquals(hash, testHash);
    }

    /**
     * Validates a password using a hash.
     *
     * @param password the password to check
     * @param hash
     * @param salt
     * @return true if the password is correct, false if not
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.spec.InvalidKeySpecException
     */
    public static boolean validatePassword(String password, byte[] hash, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {

        return validatePassword(password.toCharArray(), hash, salt);
    }

    /**
     * Computes the PBKDF2 hash of a password.
     *
     * @param password the password to hash.
     * @param salt the salt
     * @param iterations the iteration count (slowness factor)
     * @param bytes the length of the hash to compute in bytes
     * @return the PBDKF2 hash of the password
     */
    private static byte[] pbkdf2(final char[] password, final byte[] salt, final int iterationCount, final int keyLength) {

        try {
            return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(new PBEKeySpec(password, salt, iterationCount, keyLength * 8)).getEncoded();
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns a salted PBKDF2 hash of the password.
     *
     * @param password the password to hash
     * @return a salted PBKDF2 hash of the password
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.spec.InvalidKeySpecException
     */
    public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
        return createHash(password.toCharArray());
    }

    /**
     * Returns a salted PBKDF2 hash of the password.
     *
     * @param password the password to hash
     * @return a salted PBKDF2 hash of the password in the form of SALT:HASH
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.spec.InvalidKeySpecException
     */
    public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {

        // Generate a random salt
        byte[] salt = getSalt().getBytes();

        // Hash the password
        byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, 24);

        // Format salt:hash
        return toHex(salt) + ":" + toHex(hash);
    }

    /**
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static String getSalt() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        return Arrays.toString(salt);
    }

    /**
     * Converts a byte array into a hexadecimal string.
     *
     * @param array the byte array to convert
     * @return a length*2 character string encoding the byte array
     */
    private static String toHex(byte[] array) {

        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        if (paddingLength > 0) {
            return String.format("%0" + paddingLength + "d", 0) + hex;
        } else {
            return hex;
        }
    }

    /**
     * Converts a string of hexadecimal characters into a byte array.
     *
     * @param hex the hex string
     * @return the hex string decoded into a byte array
     */
    public static byte[] fromHex(String hex) {

        byte[] binary = new byte[hex.length() / 2];
        for (int i = 0; i < binary.length; i++) {
            binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return binary;
    }

    /**
     * Compares two byte arrays in length-constant time. This comparison method
     * is used so that password hashes cannot be extracted from an on-line
     * system using a timing attack and then attacked off-line.
     *
     * @param a the first byte array
     * @param b the second byte array
     * @return true if both byte arrays are the same, false if not
     */
    private static boolean slowEquals(byte[] a, byte[] b) {

        int diff = a.length ^ b.length;
        for (int i = 0; i < a.length && i < b.length; i++) {
            diff |= a[i] ^ b[i];
        }
        return diff == 0;
    }

}

The complete project is available on Github.