Showing posts with label JavaEE. Show all posts
Showing posts with label JavaEE. Show all posts

Monday, October 09, 2017

JAX-RS 2.0 Tip of the Day: Using MOXy and Forms Example on GlassFish 5.0

Glass Fish
I have been tasked with doing some JAX-RS coding during my day job. I wanted to update my skills for JAX-RS which is one of my favorite technologies. I specifically use Jersey which I find very well done and easy to use. As a number of you may know... I am a GlassFish fan too (one just needs to look at my banner). I decided to use my trusty NetBeans 8.2 install to write a quick example.

MOXy is enabled by default if you add the dependency to your Maven project.


This is a great feature, and I wanted to give it a spin instead of using Jackson, or Jettison. The usage was as simple as adding a @XmlRootElement annotation to the model class. The rest was handled automagically.

The entire project including a war file are available on Github: jaxrs-form-data-parameters.

A simple platform independent file is used to setup the application.


We set up web resource (service) to handle our requests.


That's it! You now have a JAX-RS Web Service. The project runs successfully on GlassFish 5.0 (.war file on GitHub).

NOTE: MOXy has some issues running on GlassFish 4.1, 4.1.1, and 4.2.

Sunday, October 08, 2017

JSF HTML Whitespace, JS, and CSS Compression

This is the second approach to whitespace removal, JS, and CSS compression. In my article Whitespace Servlet Filter, I mentioned that I tried a number of approaches using htmlcompressor to accomplish this task.

This was my second approach which was to wrap the ResponseWriter in JSF to accomplish this task. The approach worked, but was abandoned before I finished writing some additional code to handle AJAX. This could be easily resolved with code that is similar to that found in Whitespace Servlet Filter.

This approach is very specific to JSF and relies on the project being pure JSF. The filter approach is more flexible in my judgement. I did think it was important to publish the code though on Github.

The code for the project can be found here: jsf-html-compressor.

Whitespace Servlet Filter

A few years ago I worked on a number of different techniques to strip the whitespace out of web pages. My goal was to come up with a solution for JSF pages. I tried a number of different solutions,  but they were all based on a framework called htmlcompressor which is a now abandoned project in the archives of Google Code. This framework used the Google Closure Compiler to handle the heavy lifting.

This solution worked flawlessly when we tested it on JSF pages, but there was a push to use pre-minified pages for static content, and leave JSF pages alone. I abandoned this project until I was using Google PageSpeed to check the speed of some pages to enhance their performance.  I remembered this approach I tried back in 2011, and tried it again with great success and only minor tweaking. I have decided to publish the code on Github.

The project can be found here: whitespace-filter.


Thursday, March 24, 2016

JSF 2.2 Tip of the Day: Using Hibernate Validators with JSF

Introduction

Hibernate validators offer a plethora of validators to make your development work much easier. Some of the common ones that are used are @NotNull, @NotBlank, and @NotEmpty. To take advantage of these validators, and avoid some misconceptions, a little information needs to be provided.

@NotNull

Everyone likes this particular annotation, and it can be a real life saver. However something that often catches developers using it on JSF is that JSF treats empty form fields as empty strings. This is not the same as null. So if you want JSF to capture these values and treat them as null values, you need to tell JSF to do so. This is accomplished by adding the following context parameter to the web.xml file.
    <context-param>
         <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
         <param-value>true</param-value>
    </context-param>
Once this is added to the context, all blanks will be treated as null values. Be mindful of any side effects created from this change.

@NotEmpty

This validator causes a lot of confusion. The value can not be null, but can be any character including whitespace, e.g. You can enter a space, and it will accept it.

@NotEmpty

This is the most useful annotation from my standpoint. This makes sure that the input is not null, and is not an empty string like white spaces. This is really what I think most developers are really after anyway. They want to make sure that users fill in form fields.

Code

The code for this project can be found on Github, and includes some additional bonus code such as using locales, and custom messages. The code can be found here: jsf-hibernate-validator.


Tuesday, March 22, 2016

JSF 2.2 Tip of the Day: Using ValueExpressions and VariableMapper to set EL using a PhaseListener

The title seems like a mouthful, and it is. I had some code which I used to demonstrate how to set EL values using a PhaseListener. I was going to delete the code when I decided that it was the second time someone in a short span of time asked me the same question, and I should post how to do it.

The use of a PhaseListener to set EL values seems to the casual observer like Voodoo magic. You will see the EL expressions on the page, and they magically seem to populate. In some ways it is like a classical interceptor which can make your code really seem magical, and lead to confusion. This approach though has its place, and if used correctly can solve a lot of issues. One example is determining if a <ui:include src="XXX" rendered="#{EL_VARIABLE_HERE}" /> should render.

It can also be used to set the src value on the fly. An always popular question on how to resolve.

The project can be found on GitHub here: jsf-ve-phaselistener

So the output looks like a nice set of name value pairs using the Greek alphabet as variable names.



Sunday, September 06, 2015

Book Review: Murach's Java Servlets and JSP

Cyndi Vasquez sent me this title a while back. I have been so bogged down that I finally got a chance to look at it. Thanks Murach... this is a good book.

The book is written in a style that many will either love, or hate. I personally am on the former. The pages on the left side are an explanation of the technical matter, and the right side are examples. The book is designed to guide you from front to back on an adventure into programming. Along the safari, I assure you will be pleased. The quarry is knowledge and this book is the tool to capture it.

The books is divided into five sections which will take you from absolute beginner to accomplished Servlet and JSP aficionado. It will even teach you a little about databases, and JSF along the way. There are two appendices that will show you how to set up your computer either Mac, or PC before you get started on your journey.

One of the thrills about this book is the use of NetBeans. I believe that NetBeans is the easiest tool for developing web based applications using Servlets and JSP. It also is my preferred tool for Java development in general. The book not only teaches you about the essentials of the title technologies, but helps you gain an in-depth knowledge of a valuable IDE that you can bank your career on.

Section one covers the basics of the technology and the MVC pattern. This is followed by a crash course on HTML, CSS, and web technologies based on Java.  The 8th chapter on EL is a great reference for how to use this important technology in your web applications.

Section three covers essential database skills to get you started with web development. These skills are the bare minimum to get started, but are complete for the purpose of this book. Keep in mind, these are the basics.

Section four is the meat of the book. This covers the advanced Servlet and JSP skills. It also covers some additional technologies like JSF. My favorite parts of this section are chapters 18, 19, and 20. The HTTP Request and Response skills are something every developer should strive to make sure they understand. Chapter 19 covers listeners which are truly your friends. Chapter 20 covers another often misused, abused, and otherwise fantastic technology. The filter can make your life as a web developer a great pleasure, or a rabbit hole in which you feel like Alice in Wonderland.

The final concluding section five puts all of the pieces together in a Music Store website. The Music Store website uses most of the technologies covered, and takes the learner to the next level with clear and concise directions.

Overall this is a great book for anyone interested in learning about Servlet and JSP technology. Please keep in mind that all Java web technologies are based on the Servlet foundation. JSF is nothing more than a veneer on top of this technology as an example.

Wednesday, April 01, 2015

JSF 2.2 Tip of the Day: p:passthrough and How to use it

I was asking my team to go through their JSF pages, and to update the XML namespaces to use the latest namespace from the JSF 2.2 specification. While I was looking at the code, I found a number of instances where developers were adding attributes like name to <h:commandButton /> and NetBeans correctly was identifying that there is an issue with that.

Fortunately, some of these attributes were passing through to the underlying page without needing p:passthrough. However, you should not rely on such functionality to work. If the VDL Document does not show it as an attribute, you shouldn't expect it to work.

Alright, so how do we do it correctly?

There is no magic here. It is simply a matter of adding the attribute with a prefix of p:, for example p:name="someName" for the name attribute. This will result in the attribute being passed through the rendered and added to the resulting output.

So I have an example, and the resulting output.

The resulting output will run the JavaScript associated with the passed through attributes, or set the CSS styling. Very simple and easy to implement.

Tuesday, February 17, 2015

JSF 2.x Tip of the Day: Implementing a ViewMapListener

A map of the lands where the Trobadors flourished. 
"France 1154-en" by Reigen - Own work
Licensed under CC BY-SA 4.0 via Wikimedia Commons.

Introduction

There are a number of SystemEvents supported by JSF 2.x. A question that comes up frequently is how to implement them. In a number of cases on stackoverflow, it is implemented using a PhaseListener. I was looking for a way to cleanup the view map, or just get values from it before it was destroyed. I decided that the simplest way to do so was to implement a ViewMapListener. I also noticed that there were very few posts on how to implement it using the faces-config.xml so I decided to use that approach since it was instructive and more clear to me.

Implementation

The basic implementation requires that you add our listener implementation to the faces-config.xml. The example I have here is designed to get called on a PreDestroyViewMapEvent which is called on a normal navigation. We can force it though by adding a @PreDestroy annotation to a method to invoke before being destroyed. Inside the method we would need to get the UIViewroot view map, and call clear(). This would cause our listener to be invoked too. It would be a good cleanup mechanism for cleaning up resources on session expiration too, but at the moment this does not work on JSF 2.1. The @PreDestroy is not called on session timeout on JSF 2.1. This is expected to be an enhancement in JSF 2.2+.

The code for the project can be downloaded from Bitbuket here: viewmaplistener-example

Conclusion

The example above is just one mechanism of using a SystemEvent listener. You may decide to read values from the map, and add them to the session, or manipulate it in some other way before the data is destroyed.

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

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

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


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, 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


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.

Popular Posts