Friday, December 26, 2014

ExecutorService Conundrum

I was asked by someone to solve a problem with threads that they were having. They wanted to cancel a Future that was sent to an ExecutorService. I told them to look at a previous posts I had done on the subject. However, they insisted that this was different. So I took a look at the code. Alas, it was slightly different, but like most folks including me, they were too close to the problem to see the answer. I looked at it, and at first glance I thought something was askew, but it was not.

The code for this project can be downloaded here: runnable-example
As you can see from the results of the run, the future is canceled, but still keeps running. Then it gets interrupted, and breaks. So the question is why is it still running after being canceled.

Here is the Runnable and the main class to execute it:

MyRunnable.java


Main.java


So the do you have an answer? The answer is at the bottom of the blog. Don't peek... think!

Reference

Answer

Simply because you have canceled it, and even interrupted it; it is still a running thread. It is not scheduled, so you are not canceling it before execution.

Sunday, December 21, 2014

JSF 2.x Dynamic Encoding

Encoding Examples
In an Internationalized world, we need to be able to change the encoding of a JSF page dynamically. In this case, we have some characters encoded in UTF-8, but we want to be able to change the encoding on the page, and have the framework handle the character conversions for our web page.

So how do we do it?

One of the simplest ways is to wrap our page in a <f:view /> tag. The tag wraps the <head/> and <body/> elements in our HTML page. In the example above this is accomplished as shown below: The code for the backing bean is shown below:

EncodingBean.java


The Netbeans Maven project can be found here: JSF Dynamic Encoding

Thursday, October 09, 2014

How do I check if a Class is an instanceof another Class without initializing it?

Illustration: Cathy Wilcox
We had a recent security audit and a question was posed about how to check a Class without doing an instanceof. This turned out to be a great learning experience. There were a couple of issues that needed to be resolved, first we were loading a Class by passing in its name using something similar to the line below: This will load the Class, but from here how do we check that it is an instanceof without instantiating it?
This can be solved by using isAssignableFrom(Class clazz) as shown below. In this case we are checking if SolientGreen is Green. Some of you will find the moral paradox of being "Green" with Soilent Green.
The second issue is a more potential security problem. How do we load the Class without initializing it. If the Class has a static initializer, the code is executed when the class is loaded. Alas, this is handled by using a variation of Class.forName(String name, boolean initialize, ClassLoader loader) which takes a boolean to determine if the class should be initialized, and a ClassLoader if you want to specify a specific loader.

Finally, we can check the Class like this: When this is run, you will not see the message. Very nice indeed!

So here is the remaining code for education and entertainment:
The code for the project can be downloaded from Bitbucket here: assignable

Friday, October 03, 2014

Cassandra Ruby Gem Issues on Mac OS X 10.9.5

I was trying to resolve some issues with building the cassandra gem on Mac OS X 10.9.5. The solution was a multipart solution. You first need to build thrift first which has a known issue, and then build cassandra. This technical tip is very simple. I didn't want to lose it, and I am sure that there are other people out there who will need it.
Note: Please make sure you have updated all the gems in your repository before executing these commands. This will build both required gems.

Tuesday, August 19, 2014

JSF 2.1 Tip of the Day: Clearing the @ViewScope

Introduction

I was trying to solve an issue in our code where the @ViewScope beans were not being garbage collected. I spoke a number of times with Manfred Riem at Oracle about the weirdness of this issue. The issue simply put was that we were facing a memory leak where the instances of @ViewScope objects were not being removed from the view map. As a result, the pages were being kept in memory. The view map is limited to 32 views which helped to hide the issue. In most cases, it would not appear to normal users of our application. The issue was suddenly evident when the view contained tens of thousands of objects. 32 x 10k is REALLY BIG! It really never made it to 32, the system would stall and crash at about 6 instances.

The Culprit

We had implemented our own custom NavigationHandler. This was working quite well on JSF 2.0.x, but a couple of things happened. The JSF implementation was changed to handle another view scope issue, and our implementation of the NavigationHandler was changed from my original code. The new handler did not handle cleaning up the @ViewScope object view map which is stored in the session. Oh, yeah, the view map in the session was the change to the API too.

The Solution

The solution turned out to be something simple, re-implement the same mechanism in the default NavigationHandler to clear the @ViewScope objects from the view map in the session.

Interesting Observations

I was trying to come up with a mechanism to clear the view map data from the session, and came up with a SystemEventListener to test out some ideas. I thought I would share the code for people to see how the map is cleared. This is an approach to the issue, but as I noted, it was actually something missed in our NavigationHandler. I thought I should post the code for anyone who was looking for ideas on how to manipulate the map, or clear data in it. So without further hesitation. Here is the code.

ViewMapSystemEventListener.java


To implement the listener, you need to add an entry to the faces-config.xml file as shown below.

faces-config.xml


Saturday, July 26, 2014

JSF 1.2: Project Woodstock Application using JPA

Woodstock Dataprovider Entity Example
Here is another example of using Project Woodstock along with JPA in an Enterprise Application. The project requires the sample database included in NetBeans.

The project was updated using NetBeans 6.5.1.


The code for the project can be found on Bitbucket here: WoodstockJPAApplication

Friday, July 25, 2014

JSF 1.2: Project Woodstock Multiple Selection Table Example

Multiple Selection Table

This is another example of a Project Woodstock project that was converted from Project Rave and Sun Studio Creator 2. This example details a multiple selection table, and was originally created by Winston Prakash.

I have updated the project using NetBeans 6.5.1 and tested on GlassFish 2.1.1.

The updated project can be found on BitBucket here: MultipleSelectionTable

Thursday, July 24, 2014

JSF 1.2: Project Rave Single Selection Table

Single Selection Table
Here is another example Project Rave/Woodstock project originally written by Winston Prakash for Sun Studio Creator 2. It has been updated using NetBeans 6.5.1 and tested on Glassfish 2.1.1.

The project can be found on BitBucket here: SingleSelectionTable

JSF 1.2: Woodstock Collapsible Group Table Example

Collapsible Group Table Example
Here is another example of a Project Rave data table converted to Project Woodstock. Project Woodstock was a great idea and the implementation with Visual JSF was the right path to go with JSF development. It is a shame that the project was canceled by Sun. I met a lot of great people who worked on the projects, and are still friends today. The code for this project was originally developed by Winston Prakash at Sun.

The code was developed using NetBeans 6.5.1 and can be downloaded from BitBucket here: CollapsibleGroupTable


Monday, July 14, 2014

JSF 1.2: Project Woodstock Button Facet Table

I was going through some old code examples. I found one created with Sun Studio Creator. Yes, it was very old.

The original example was developed by Winston Prakash.

I did some updates to Project Woodstock from the original Project Rave, and came up with a pretty new example page.

The project can be downloaded here: ButtonHeaderTable

Note: You will need to use NetBeans 6.5.1, or 6.7.1 to run it.

Sunday, July 13, 2014

JSF 1.2: Visual Web Pack (Project Woodstock) Java Persistence API Example

Master-Detail Example
This is some example code that I have for a Visual Web Pack (VWP) project that demonstrates some complex data table examples.

I often fantasize about being able to get the band back together and make Woodstock 2.0. Here is an example of why. This was complex for JSF 1.2.

The code can be downloaded from: vwpjpaexamples

I would strongly recommend using NetBeans 6.5.1 to build and run the example project.

Thursday, July 10, 2014

A simple practical "pragmatic" Formatter for java.util.logging.Logger

I have quite a trove of code examples I have collected over the years. Here is another example of a Formatter used with the java.util.logging.Logger to generate a standard output.

PragmaticFormatter.java


The next question is how do you use it? Easy enough... here is an example for you. The code for the project is located here: pragmatic-logging-formatter

JSF 2.x Tip of the Day: Encoding Text for XML

I have a simple method to encode text to display inside an XML page, or to use inside other XML/JS for example SyntaxHighlighter.

XMLEncode


Creating a BLOB Image Table

I am going through some old code while I wait for my Windows VM to update. I came across some code to create an image BLOB table on MySQL. I thought I would publish it before deleting it from my system. It might be helpful to someone.

CreateImagesTable.java


cat: How do I list the contents of a text file?

I was asked by a new developer how you would cat the contents of a file in Java. I thought for a second and here is what I came up with. I thought I would just share it. Note: This is my 30s answer, and probably could be cleaned up.

Cat.java


Monday, June 16, 2014

Clickjacking and Java EE: Some Practical Solutions

©Technology Personalized

Introduction

What is Clickjacking?

Clickjacking, also known as a "UI redress attack", is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. Thus, the attacker is "hijacking" clicks meant for their page and routing them to other another page, most likely owned by another application, domain, or both.
Using a similar technique, keystrokes can also be hijacked. With a carefully crafted combination of stylesheets, iframes, and text boxes, a user can be led to believe they are typing in the password to their email or bank account, but are instead typing into an invisible frame controlled by the attacker.

What does this mean for Java EE developers?
 
We don't operate inside of a vacuum. HTML/JS technologies are the backbone of most EE applications. This makes them subject to this kind of attack just like any other HTML/JS technologies. In fact, we often abstract away a lot of the underlying HTML/JS from the developer, this can make us more susceptible to this kind of attack unless we are cognizant and diligent in applying defenses.

Fortunately, there are a number of simple things that developers can do to add additional layers of security to their applications in an unobtrusive way. Those methods include adding X-Frame-Options, and frame busting.

X-Frame-Options

The first solution is to add a header to our pages to offer a browser a "suggestion" on how to handle pages that contain frames. The options include DENY, SAMEORIGIN, and ALLOWFROM. The latter is a new addition and may not be supported. The DENY option advises the browser not to allow any content to be displayed if it comes inside a frame. The SAMEORIGIN option advises the browser to only display framed content, if the content is coming from the same origin as the original request. The ALLOWFROM option takes a parameter (URI) that advises that content from a given URI can be framed. As previously noted, this may not be supported on all browsers. You will need to examine your target browser for compliance. Make no assumptions about your users though. They will use a browser of convenience. The implementation of adding the header is simple. The OWASP has come-up with a simple filter to handle the X-Frame-Options.

Frame Busting

The second solution is simple too. It involves using CSS/JS to do something called "frame busting". There are a number of examples on the web. I would recommend that you examine them carefully. I have found that the code I use is simple, elegant, and does not leave a lot of room for attack vectors. This does not imply that it is invulnerable, but does provide a good defense.

In the frame busting method I use, the CSS sets the style attribute body{display:none !important;} on the <body /> tag of the page as soon as the page is loaded. This is followed by a JS function that checks to see if the page is inside a <frame />, if it is then it attempts to set the body as the top location. Thus it breaks the frame. If it is successful, it removes the body{display:none !important;}styling. Otherwise, the <body /> of page will not display. Simple.

Examples

I have created a NetBeans Maven project on Bitbucketclickjacking-examples

The examples include comments and instructions to see the various issues, and possible solutions. Examples include HTML, JSF, and JSP pages. These examples were developed on GlassFish and tested on Apache Tomcat. The code for frame busting is included below for reference using JSF.

Frame Busting Code



References

Thursday, June 12, 2014

JSF 2.2 Tip of the Day: Hidden Field Validation

Hidden Mines

Introduction

How often do you have validators on your hidden fields? I recently performed a security audit of an application that did not have validators associated with the hidden fields on the page. I suspect that the out of sight, out of mind mentality prevailed. Admittedly, I have often short circuited some development and put hidden fields in a JSF page without a validator. My expectation is that the data in the field would be used to provide information that may be needed by the application. However, if these fields have setters... and the results are stored in a database... I think you get the picture.

Methodology

I decided to create a more complex than really necessary example to show how to validate a <h:inputHidden /> field. In the example, you can enter names into an <h:inputText /> which will use JavaScript to update the hidden field. The validation will be activated on form submission. Additionally, a value change listener will update the planet name, and update the planet to the new planet. The validation will prevent putting in planets that don't exist in the enum for current Planets. You can confirm this by entering a bogus name, or poor Pluto that was kicked out of the planetary club.

Code

The code for this example was developed using NetBeans 8.0 IDE on GlassFish 4+ and Apache Tomcat 8+ using JSF 2.2 (Mojarra).

The code for the project can be downloaded from Bitbuckethidden-field-validation


Planets.java



PlanetValidator.java



IndexBean.java



index.xhtml


Thursday, May 01, 2014

JSF 2.2 Tip of the Day: JavaScript Popup Window with Dynamic URL Link

Introduction

There are times when you need to have a JavaScript popup window that opens to another URL based on user input.  The JavaScript is usually added to the onclick event on the JSF component. The dynamic link in JSF is more difficult to accomplish since binding the onclick using Expression Language (EL) is determined at page rendering time. As a result, this means that the JavaScript is not dynamic. As a result, the link is not dynamic either.

A Solution

I have created a project that has three examples that demonstrate the different types of JSF links including the dynamic link. The last example includes <f:param /> elements that are appended to the dynamic URL that is generated.

The dynamic example still uses the onclick event, but the JSF action performs a redirect of the newly opened window. Additionally, and of the parameters that are added to the JSF component are converted to query parameters and appended to the redirect URL.

The Apache Maven project created with NetBeans is located on BitBucket here: jsf-link-examples

The project was tested on GlassFish 4 using Mojarra  JSF 2.2, but the technique should work on other application servers and JSF 2.x versions.

Index.xhtml



IndexBean.java


Cross-Site Scripting (XSS) and Playing with JSoup

Introduction

I have used Beautiful Soup with Python in the past for screen scraping. I was immediately excited at the possibilities. JSoup is a Java API for extracting data, and manipulating the DOM in HTML.
jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.
I did a quick proof of concept just to see what it would do with my "dirty" code.

It results in an interesting output that could be useful if used properly. If you put in garbage, you will get "less" garbage out. It is better than nothing.

I decided that this still could be really useful especially combined with Hibernate Validators and JSF.

Hibernate Validator - @SafeHtml

I was looking at the Hibernate Validators to see about cleaning up some input from users to prevent XSS issues. I noticed that there was a validator called @SafeHtml(whitelistType=, additionalTags=, additionalTagsWithAttributes=). It uses the JSoup HTML parser.

Alas, I am full of sorrow. I can not seem to get the <code>@SafeHtml</code> annotation to work. GlassFish vomits and complains it can not find it. I even tried to add it to every lib directory in GlassFish without success. Failing to succeed, I tried Tomcat 8 next. Again, nothing but bitterness and disappointment. It just will not get picked up.

I tried looking for a working example of the validator, and didn't find any that worked. I am not sure of the what is going on, but if I can't figure it out. I imagine I am not alone. I just blog about it. ;-)

Undeterred

Well I decided that I didn't need Hibernate anyway! I feel like I should be in Aesop's Fables. I mentioned my Proof of Concept (POC) earlier. I figured I would look at trying to remove some <script /> tags from my code and even encoded them too to see what it would do. The whole point here is to help prevent XSS.

Here is my Apache Maven project on BitBucket: jsoup-cleaner
 
Note: See the actual code for a more complete representation of the actual code I am trying to strip. The Syntaxhighlighter is having issues with the nested script tags. The same applies to the output.

I was surprised by the result actually. It stripped out the <script /> tags, but totally missed the encoded tags. That is a major issue.

Improvements

I was looking for some solutions for the encoded JavaScript issue when I discovered a blog post called Jersey Cross-Site Scripting XSS Filter for Java Web Apps.

This was not exactly what I needed, but it did contain a method which used JSoup and another framework called ESAPI. Enterprise Security API (ESAPI) was developed by OWASP to enhance the security of Enterprise applications. OWASP has a lot more than this framework.  ESAPI can strip out the encoded bits to help prevent XSS.
I shamelessly used the following method from the blog post.
This does effectively remove any encoded <script /> tags from the output. It does not however prevent errors in judgement on the part of the developer. For example taking the results of the output and using them directly in an HTML JavaScript attribute like onmouseover, or onclick.

I created an example project called XSS Scripter's Delight which I demonstrated at the Greenville Java Users Group. It demonstrates what happens when you don't validate inputs from users. The name is satirical, but does demonstrate in a non-malicious way what you can do if you are not careful.

The Apache Maven project developed with NetBeans can be found on Bitbucket here: xss-scripters-delight.

Monday, April 28, 2014

Arquillian Graphene 2: JavaScript Unit Testing Examples

I have been doing work with Arquillian for a while. If you need to do integration and unit testing on your JSF application. This is definitely the path to take. It makes testing so much easier to accomplish.

Recently, I have been trying to use Arquillian Graphene 2 to do JavaScript unit testing. I spent a lot of time trying to get the examples on the Graphene 2 - JavaScript Interface wiki to work. I discovered that they were slightly incorrect and the source of my grief. One of the great things about an Open Source world is that I updated the wiki with the correct information.

I have created a couple of Proof of Concept (POC) projects to demonstrate how to use Graphene to do JS testing. The first example uses Graphene in stand-alone mode. This mode allows you to test your JavaScript outside of a container, but using a browser implementation like: PhantomJS, Chrome, Firefox, or Safari.

The Apache Maven NetBeans 8.0 project can be downloaded from Bitbucket here: graphene-js-poc

You will need to execute this from the command line, or use the JS Unit Test custom goal in NetBeans.


The next project is simply a combination of the code from the Arquillian Graphene 2 wiki combined into a more complex project. This project is designed to run in a container. In my case, Glassfish is the container of choice. The slickness of this approach becomes quite apparent when you see the application server start-up, execute the tests, and shutdown gracefully.

The Apache Maven NetBeans 8.0 project can be downloaded from Bitbucket here: graphene-poc.

The project includes a JSF example along with testing JavaScript.

If you need to do unit testing of your JavaScript, this may be an option to consider. Please make sure you read the wiki and understand the limitations of the approach however. You can use my code as an example to help guide you along the path.

Friday, April 18, 2014

JSF 2.2 Tip of the Day: Naughty Expression Language (EL)

Unexpected Effects

Many of you may know this already, but I was reminded the other day how this can catch even some of the most brilliant JSF developers. When you comment out a component in your xhtml page that has EL bindings, you may not be REALLY disabling it.
Expression Language (EL) is parsed and evaluated as the page is being rendered. As a result, any exposed EL syntax will be processed including functions which could have deleterious effects. For example, take a look at the following code, and guess what it will do.

So what happens?

Scary things happen....
  1. It executes
  2. Parser exception. The parser will try to find a property called doSomething
  3. It will execute, please note that there is no <h:form/>. It is not required since we are evaluating the EL.
  4. Parser exception. The parser will try to find a property called doSomethingElse

Sensei what do I do?

You have a couple of options. The first option is the easiest, and it is likely what you want anyway with your JSF pages. You can disable the comments. No need to transmit your development comments to the end users anyway. The second option is to add a - between the # and the { like this #-{indexBean.doSomethingElse()}.
The first option is handled by adding a configuration parameter to the web.xmlfile as shown below. Here is a more complete example: The result of the code is as follows:

The complete code example was developed using NetBeans 8.0 and GlassFish 4.0 on JDK 8. The code can be found here: auto-execute-el

Wednesday, February 12, 2014

JSF 2.2 Tip of the Day: Using JSF AJAX Events

Please wait...

Introduction

The JSF framework provides an easy to use AJAX event handling mechanism. The jsf.js library is included in Mojarra and MyFaces. There are two particular methods of interest: jsf.ajax.addOnError(callback) and jsf.ajax.addOnEvent(callback). I will be covering the latter handler.

The JsDoc does not really explain the jsf.ajax.addOnEvent(callback) code very well. Since it is Javascript, you can read it, but I think a simple example of its flexibility with some comments might work better.

Using the addOnEvent is very simple. You register the callback, and it gets called during the lifecycle. The important thing here to remember is that the callback must be a function. Otherwise, it will throw an error. You can control what event processing occurs during the lifecycle.

Events

The callback is invoked during the AJAX request and response lifecycle. The status passed to the callback are listed below.

Event Description
begin This is the start of the AJAX request.
complete This is invoked right after AJAX response is returned.
success This is invoked right after successful processing of AJAX response and update of HTML DOM.


Based on the status, we can take appropriate action on the AJAX event. A great example to demonstrate AJAX event handling is to provide feedback to the user to indicate the status of their request. I will demonstrate how to create an AJAX based progress loader to demonstrate the events.

Code

The code for our AJAX loader is very simple, and could be moved into a composite component if necessary. The NetBeans developed Maven project can be downloaded from the references section below.

index.xhtml



This code controls our progress bar by making changes to the CSS in DOM. The CSS idea is not mine, but it is clever. Here is the CSS.

loader.css



A simple CSS layout, and our Javascript callback to jsf.ajax.addOnEvent(callback) is all it takes to make a cool progress loader.

References

Monday, January 20, 2014

RichFaces 4.3.x Tip of the Day: Complex RichFaces Data Tables

Introduction

I have been working on JSF tables for the various projects I have been involved with over the years. Starting in 2012, I began looking at RichFaces <rich:dataTable /> for some projects at my day job. The research into how to handle a number of complex situations has been enlightening to say the least.

The table is the most complex component in HTML. It is seemingly boundless in its extensibility. You can have multi-column headers that span multiple rows, you can multi-row cells, or multi-column cells. Tables can be displayed left-to-right, or right-to-left, top-to-bottom and vice-versa. As a result, when developing components for JSF, or any component framework, decisions must be made on how to generate them.

A couple of the component frameworks like PrimeFaces, and RichFaces allow developers to create more complex tables with more ease. However there are limitations with each of these frameworks. We trade flexibility for consistency, and this is fine in most cases.

The demonstration code in this post is about getting some of the flexibility back, or taking advantage of the flexibility that comes with a framework like RichFaces. We will gain the flexibility back, but it is a function of complexity. The examples will show you techniques for doing the "same thing" in multiple ways. For example, sorting can be done on the server, client, or a combination of both.

The question is where we put the complex bits. The answer to that question depends on you as a developer. You need to examine the problem domain, and understand the limits to the techniques presented.

Solutions

Please let me confess something. I like building HTML objects programmatically. There I said it. In this case I am trading the ease of development for flexibility. The solutions below will demonstrate the different techniques for accomplishing the same functionality. Please examine the code carefully before discounting it. I spent a lot of time playing with it to make it look simple.

The code for this project was developed using NetBeans and Apache Maven. The code was tested on GlassFish 3.1.2.2 and 4.0. It should work on other application servers, but I have not tested it on other servers. This project assumes you are using NetBeans which includes a sample database that these examples require. If you are not using NetBeans, you will need to create your own database with sample data to display some of the tables.

The code can be downloaded from Bitbucket at the link below, or in the references section at the end of the post.

richfaces-tables-poc

Dynamic Data Table with Sorting

Dynamic Table with Sorting
This example uses the binding attribute of the <rich:dataTable /> to bind our table to a CDI @ManagedBean. The bean is responsible for generating the table programmatically, and returning it back to the page. The data is sortable by column.
As you can see the page is very simple. In fact, most of the page is plumbing and navigation. The <rich:dataTable /> is the smallest part of the page. The code to generate the table is much more complex.
As you can see we have traded simplicity in the page for complexity in the @ManagedBean. If you are satisfied with this technique, lets take a look at another one.

Dynamic Data Table with Sorting Revisited

Dynamic Table
This table uses the same dynamic binding as the example above on the JSF page, but uses helper utilities to create JSF components dynamically from a library that I have written. It is a separate project that you can download (Please see references). This reduces the chances for errors creating common components, but it is still a lot of code. To check our sorting, I have made a "random" data generator for the table data for the code to sort.
The more simplified code in the @ManagedBean is shown below.
The code above was written before I added more functionality to my jsf-utils project. The new methods would shorten this considerably, but it would still be fairly complex.

Dynamic Table using JSP/JSTL Tags with JSF

JSF/JSTL Dynamic Table
Let me start this example with a warning. If you are using JSP/JSTL tags in your JSF pages, you may encounter very bad behavior. This technique should only be used as a last resort. I will not labor a point. If you don't understand why this is a bad idea, take a look at this post for links: JSF 2.x Tip of the Day: Great Blog Posts Explaining JSTL vs. JSF.
In this example, I will generate the rows and columns using <c:forEach />. This transfers a lot of the complexity to the page and away from the @ManagedBean. Since we are using <c:forEach />, our mechanism for sorting has to change. I used Query jquery.tablesorter.js to allow sorting of the headers.
As you can see we have much simpler code in the page bean. It looks like what you would expect for a normal JSF data table.

Complex Data Table Design

Complex Table Design
This table has a lot of really cool features, but the code is complex in the page, and the page bean is relatively simple.

Conclusion

RichFaces supports complex table designs, and produces nice results. The amount of work required to create dynamic data tables depends on the technique chosen, and limitations on the data being presented. There is no "one good way" to create data tables. Suffice to say that the easiest path should be chosen.

References

Popular Posts