Showing posts with label frameworks. Show all posts
Showing posts with label frameworks. Show all posts

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.


Friday, July 21, 2017

autolink-java framework

I have been looking for a good and simple "Java library to extract links (URLs, email addresses) from plain text". I was searching on Github and found this little gem called autolink-java by Robin Stocker (robinst).

This library was used in a proof-of-concept (POC) I was working on at work. We needed to be able to extract all of the links from a page, and display them. This includes hyperlinks and email addresses. This little gem met the bill, and was quick to parse the text file I used.

The example requires the following maven dependencies:
This framework extracted a list of URLs from a file that looks like this:
As you can see, it generates a nice extraction of the URLs from the surrounding text. Give it a try and let me know what you think.

The project has been uploaded to Bitbucket and can be found here: autolink-java-extractor.

Sunday, March 20, 2016

Google Guava IP and Hostname Validation

I was trying to come up with a way to validate hostnames and IP addresses. I didn't want to spend time trying to do it myself. I figured that this should be a common situation, and likely someone had already written a tool to do just such a thing. I was right. Google Guava has a couple of interesting classes that do exactly what I was looking for.

For folks who may not be familiar with Guava, it is a framework of really helpful utilities that can be used for a variety of situations. Most folks who use Guava in my experience use the collections classes. However, there is a boon for anyone who digs a little deeper.

We will use two specific classes from the Guava framework to do our validations. The first is InternetDomainName which is used to validate the domain name. The other is InetAddresses to check our IP address for validity.

There are some caveats to the InternetDomainName class which are explained here: InternetDomainNameExplained.

In the code below, we see that it is very easy to use and it works very well.

Monday, March 30, 2015

Customizing Blogger

Introduction

I want to start by blaming Markus Eisele for my misadventures. I was looking at his blog and liked the makeover he gave it. I did find the template he was using, but decided that I would write my own. Well I thought this should be an easy thing to do. I severely underestimated the challenge of making a custom template for myself. It turns out that one of the easiest things turns out to be the hardest. Alright Markus you are off the hook... it may just be my bravado, and belief I can build a better mousetrap that led me down the long lonesome road.

Google is well known for having good and sometimes great APIs for their technology. Blogger is an exception to that rule. There is not one clear cut schema for their layout that I can find ironically using Google itself. You figure with all of the templates and bloggers that this would be covered ad nauseum.  It is not though.

Technologies

I was looking for a simple and elegant framework to make my blog sites look professional, and also make them portable. I had the following requirements:
  1. Mature framework
  2. Can be found on a CDN
  3. Easy to use
  4. Simple to implement
  5. Well Documented
  6. Lots of examples
  7. Flexible
  8. Customizable
  9. Response UI
  10. HTML5
  11. Portable
  12. JSF Compatible
  13. Works with NetBeans IDE for Tooling
I looked at a number of frameworks including Foundation, and Bootstrap. I ended up choosing Foundation since it seemed to be easier to use for me. Your milage my vary.

The first thing I wanted to know was what was the minimum required for a template on Blogger. I discovered that are a couple of versions of the template: an HTML 4.01 version (v.1) and an HTML 5 version (v.2) which are somewhat a hybrid mix of XML, and (X)HTML. I published the basic templates on Gist as shown below.

I have a couple of different blogs and found them to be different so I thought I would share my findings.

The next thing I needed to find out was what was the minimal template I would need for using with Foundation. The template below uses a CDN to deliver the required JS/CSS. The template below is the culmination of a lot of work to make it work with the visual tools on Blogger. Remember to backup your existing template before installing mine.

Conclusion

I finally have a working blog site using the new template, and will update all of my sites to use it. My personal non-technical blog site was the first to use the new template. It is still a work in progress, but it looks very nice. Take a peek for yourself at John Yeary Blogger site.

I have compiled a list of links that I found helpful in trying to figure out their layouts and tags in the references below.

References

Tags

Template References

Additional References

Saturday, January 18, 2014

HOWTO: Adding SyntaxHighlighter to Blogger

If you want to use SyntaxHighlighter in your blog, you can simply add the code below to the <head /> element in the template for your Blogger blog.

Saturday, November 30, 2013

How to use PowerMock and Mockito to test static and private methods

Introduction

This article is not another diatribe to tell you the importance of unit testing. I think we can all agree that it is important. This is about solving an issue that comes up frequently in unit testing. How do I test static methods, and how do you test private methods.

Until PowerMock, most developers were told you can't really test a static method per se. I will show how to do it below.

A common mechanism for testing private methods is to change them to protected. This is not a good solution for a number of reasons. So how do we test them? Again, PowerMock has come to the rescue.
I want solutions. I use Arquillian, but I am not such a zealot that I will chant the mantra that mocking is evil and should not be done. It is a means to an end. That being said, we use Mockito which in my professional experience is the best current mocking framework available. It is easy to setup and use.
However, Mockito has its limitations. Two are mentioned above. The fine developers of PowerMock have come up with an additional framework to use in conjunction with Mockito to get around the limitations.

Solution

The Apache Maven sample code for the project was developed using NetBeans and can be found on Bitbucket here: unit-testing-mockito-powermockito.

Since I am a Apache Maven user, I simply add the relevant frameworks to my pom.xml as shown below: Once the test frameworks are in place, I can use the PowerMockRunner to help me with my testing. The following are some simple classes to demonstrate how to test. The first is a class to generate UUID values for IDs.

IdentityUtilities.java


Next, I need a class to represent a person. I am interested in testing the private method generateId.

Person.java


Finally, we need our PersonTest class to test our Person object. The explanation follows the code.

PersonTest.java


The @RunWith(PowerMockRunner.class) annotation tells jUnit that we are using an extension to handle testing of this class. This tells jUnit to use this test runner instead of its own test runner.
The @PrepareForTest({IdentityUtilities.class, Person.class}) serves multiple purposes here. The first is to tell PowerMock that we need to do some preparation of the classes to instrument them for our testing. Classes defined using this annotation are typically those that needs to be byte-code manipulated. This includes final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation. IdentityUtilities.class is our class with a static method, and Person.class contains our private method.

The first test testInitialize() behaves like any other Mockito test with the exception that we mock it using PowerMockito.mockStatic(IdentityUtilities.class) to initialize it. This makes testing static methods as easy as any other Mockito test.

The second test requires a little more explanation. In this case, we spy on the object we are creating. This allows us to instrument it. Then using the "spied" instance we use PowerMockito.when(instance, "generateId").thenReturn("UNIT-1A") to tell the framework that when the private method "generateId" is called, we want to return a specific value. Then we initialize the instance, and check the value is what we expected. Finally, we can optionally check to make sure that the method was actually called by using verifyPrivate(instance).invoke("generateId").

Conclusion

Don't short change yourself, and don't modify your beautifully architected code just to satisfy a testing framework. Find a framework like PowerMock to help you test your code as written instead. You should only change the code because you want to do so, or because you discover flaws in it.

Saturday, January 07, 2012

Using Apache HTTPD (Web Server) mod_proxy with GlassFish and Mercurial

I wrote an article on how to use Secure Mercurial in GlassFish using SSL a few weeks ago. After the article was published, I was asked about URL rewriting. I had not really messed with it in the past except with PrettyFaces (which works like a champ for reference).

I tried a framework called Url Rewrite Filter which did a decent job of rewriting URLs. It is a simple library added to your project which uses a servlet filter to handle the URL re-writing. Add the filter to the web.xml, and a urlrewrite.xml which handles the rewrites. It works much in the same manner as PrettyFaces, but is targeted at JSP/Servlets.

In my case, I have an Apple G5 PPC which is the main server for my source repository for Mercurial. This presents some challenges since the Java version is limited to 1.5, and therefore GlassFish can't be upgraded to v3 from v2.1.1. I did manage to get GlassFish v3 to run with OpenJDK 1.7 (BSD Port), but the Zero VM is too slow to handle the load. Kurt Miller has a couple of the builds for Mac PPC There are a number of reasons for my interest, the primary one for URL rewriting is that GlassFish v3 supports AJP out of the box.

Enabling JK Listener (mod_jk)

Using GlassFish v3 would provide a more optimal solution as you can see from the administration console. I decided to try using the mod_jk articles I found for GlassFish v2 from Amy Roh: GlassFish supports configurable AJP Connector and Jean-Francois Arcand's Running GlassFish with Apache httpd.  I tried to combine these with mod_proxy and mod_proxy_ajp. The articles are focused on a specific build, and I was unsuccessful in using them. I am sure it has to framework versions, but I did not want spend too much time troubleshooting.

Finally, I tried using a simple mod_proxy arrangement along with mod_rewrite. This arrangement was surprisingly easy to configure, and worked the first time I tried it.

Here is the configuration I used:

httpd.conf



httpd-vhosts.conf


Those simple changes allowed me to rewrite the URL, and open only two ports on my firewall 80 and 443 which are a very good arrangement. As noted in Secure Mercurial in GlassFish using SSL, I am using GlassFish SSL and security to handle my authentication so this is truly a very good solution.
Mercurial Repositories

Wednesday, December 08, 2010

Apache HTTPClient 4.x Preemptive Authentication

I am using the Apache HttpClient for some work I am doing at the office. It is a really cool utility to perform web based work. A common requirement of such work is to use authentication.

The default behavior of the HttpClient is to try and connect to the resource and read the response. If the response is a 401 Unauthorized, the client sends the request again using the credentials that are set in the client. This results in an unnecessary double posting of the request. It is however compliant with RFC2616 Section 10.4.2 which describes this behavior.

In the previous version of the client (3.x), you could set the preemptive authentication with the code below:


httpClient.getParams().setAuthenticationPreemptive(true);

However, version 4.x does not support this convenient arrangement. There is a more flexible arrangement using interceptors. The client supports interceptors on both the request, and the response. The use of interceptors makes the code a little more complex, but the flexibility of using multiple interceptors, and ordering them makes up for the additional code required.

I can not provide an example of my code since it was something I created for work, but here are two examples. The first is complete, and the second is simply an example.



There is an additional post on stackoverflow which indicates you may be able to use a simple addition to the header. This may work for simple clients, but it is not as flexible as the interceptor form. I have not tested the code, but have included Adam Batkin's code snippet below.


String username = ...
String password = ...
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

HttpRequest request = ...
request.addHeader(new BasicScheme().authenticate(creds, request));

Apache Commons IO 2.0

Congrats to the Apache Commons IO Team on the release of the 2.0 framework. It has been a long time coming. The latest libraries require Java 1.5 which is a quantum jump in Apache terms. The old library required Java 1.3.

The IOUtils class provides a number of convenience methods to handle most IO operations. One of my favorite methods is IOUtils.copy(InputStream input, OutputStream output). A simple method, but so very useful since it is so common.

Have you ever needed to create unit tests on methods which require a closed InputStream, or OutputStream. I am sure you have, if not you just have not gotten there yet. Apache Commons IO offers you ClosedInputStream and ClosedOutputStream.

There are some other nice classes especially for debugging like CountingInputStream and CountingOutputStream which records the number of bytes read, or written. I can see another use for cloud computing models where you are charged for data transfers. This can help you keep track of those numbers for comparison with your charges.

If you have not taken the time to look at these great tools, take a couple of minutes to just look at the javadocs. I am sure you will be impressed like me.
Enhanced by Zemanta

Saturday, February 13, 2010

Book Review - JSF 1.2 Components

I was offered a chance to review a copy of the JSF 1.2 Components book by Ian Hlavats and published by Packt Publishing. The book covers a number of different JSF frameworks including 1.2 Reference Implementation (RI), Facelets, Apache Tomahawk and Trinidad, ICEfaces, and RichFaces. My overall impression of the book is a 2/5 stars.

Why?

When you are trying to teach someone to use a new technology, the source code must work, and the effort to get it to work should be minimal. This is not the case with the accompanying source code. There are a number of errors in the code that a modern IDE and technical reviewer should catch. This applies to the code examples in the book. The configuration and requirements to use Eclipse for the projects are a shame for anyone wanting to use another IDE. The projects should have been set up to use Apache Maven to make them IDE neutral.

I also do not like partial code examples. I believe that code should stand on its own. If you are going to provide code snippets, then the code provided must be complete and functional. This was not the case.

Chapter Summaries

The first chapter covers the very basics of JSF RI. This is a very shallow introduction to the RI.

Chapter 2 Covers Facelets. It is one of the best explanations I have seen on Facelets and is very easy to understand and follow. This chapter makes the book worth buying if you are interested in Facelets technology.

Chapter 3 on Apache Tomahawk does a good job of representing the framework. There are a lot of great components in Tomahawk (75+) which play nicely with other JSF frameworks.

Chapter 4 covers Apache Trinidad (A.K.A. Oracle ADF Faces). It does a reasonable job of demonstrating the framework, and has inspired me to look a little further into it. I found it very easy to use, and found myself trying other components which were not covered in the book. I do have some issues around the code examples and implementation which I will cover in the detailed section below.

Chapter 5 covers ICEfaces. It is a really good example of some of the things that ICEfaces can do, and the components are very eye catching. My chief complaint with ICEfaces compared with some of the other frameworks is that it is really messy to set up tables, and sorting.

The book fumbles at the finish line. The chapters of the book on Seam (Chapter 6) and Richfaces (Chapter 7) are totally blown. The authors decision to do Seam before RichFaces and not separate the code base was a bad decision. The chapters themselves are not too bad, but the code would not run. Since Chapter 7 depends on Chapter 6 code, the result is a quagmire.

I created a Maven POM for Chapter 6 and set to work on the dependency issues. I had done the same thing for the previous chapters by converting them into Maven projects. This time the project failed to run and there were a number of issues. In fact, too many issues to overcome. I resolved to use the code and instructions provided by the author and the code failed to run as well. I am convinced that the Seam and database portions of the code examples are not configured correctly. After spending a week trying to make it work in both Maven and Eclipse, I quit. It should not require me spending hours trying to make it work. The code is supposed to make it easy for me to get a handle on these technologies and not troubleshoot it.
I can not validate that the code works as the author has written it in the book since the code does not work in the provided examples.

Summary

My overall impression of the book is a 2/5 stars. I really liked some portions of the book, like chapter 2 on facelets, and chapters 3 & 4 on Apache MyFaces component frameworks.

Two chapters (6 & 7) appear to provide some really relevant data, but the sample code provided with the book on which this chapter depends falls short. As a result, I can not really assess Chapter 6. Chapter 7 depends on the successful function of Chapter 6 for the most part, and is really short changed by the failure of the Seam and database connectivity. Some of the sample code for Chapter 6 works so that you can get a glimpse into the power of RichFaces.

I noted that I made a number of the examples into Apache Maven projects. I would offer them out to the public, but the code has no licensing noted in the source, and was really meant for my consumption. If you are the author, publisher, or an interested party, I will provide it to you on request.

I would really like it if Packt would consider requiring all of their sample code be provided in Maven projects. This would make the them IDE neutral, and ensure the quality of the projects by providing exact dependencies.

Chapter Details and Errata

These are notes, errors, comments, and impressions from the chapters. I suggest that if you encounter any errors in the book, please check here to see if I have addressed them.

Chapter 1

(Pages 28-29)
The images on pages 28 and 29 should be swapped. The image on page 29 is for the code snippet on the top of page 28, and vice versa.

(Page 31)
This note should be added to page 31.

Note: Classes which are used as select options <f:selectitem> need to have equals() and hashCode() methods implemented. Otherwise you will get a strange validation error whose description is not indicative of the true root cause of the error.

(Page 32)
The author makes mention of a potential issue with <h:selectManyMenu> having issues on many browsers. I tried it on Firefox 3.5.+ on Mac OS X 10.6 and did not see the issues the author mentions. This may be applicable to earlier versions of Firefox using other operating systems.

Chapter 2

If you are trying the code examples from the book and the html is not formatted correctly, please check the xml namespace in the facelets html tag. It should have the following xmlns in bold added so that it displays html correctly.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:t="http://myfaces.apache.org/tomahawk">
...
</html>

I would also recommend adding the correct DOCTYPE to the header to make sure that the document is well formed. The Transitional XHTML example is shown below and will work in most applications.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

(Page 51)
The web.xml file has some of the more important information in bold, but really should include descriptions of what these parameters are in the actual web.xml. See the example below which includes descriptions.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
    <display-name>chapter2</display-name>

    <!-- Optional JSF-RI Parameters to Help Debug -->
    <context-param>
        <param-name>com.sun.faces.verifyObjects</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.validateXml</param-name>
        <param-value>true</param-value>
    </context-param>
    
    <!-- Use Documents Saved as *.xhtml -->
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>

    <!-- Special Debug Output for Development -->
    <context-param>
        <description>
            Setting this to true will cause the FaceletViewHandler to print out debug information in an easy to use screen
            when an error occurs during the rendering process.
        </description>
        <param-name>facelets.DEVELOPMENT</param-name>
        <param-value>true</param-value>
    </context-param>
    
    <context-param>
        <description>
            A boolean value that tells the compiler to skip comments (default is true).
            Even if you comment out code in your page, the tags will not be compiled but expressions (EL) will be
            treated as if they were inlined-- still compiled and evaluated for output in the document.
            Skipping comments will remove all comments completely from the document.
        </description>
        <param-name>facelets.SKIP_COMMENTS</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>
            When a page is requested, what interval in seconds should the compiler check for changes.
            If you don't want the compiler to check for changes once the page is compiled, then use a value of -1.
            Setting a low refresh period helps during development to be able to edit pages in a running application.
        </description>
        <param-name>facelets.REFRESH_PERIOD</param-name>
        <param-value>1</param-value>
    </context-param>
    <context-param>
        <description>
            A semicolon (;) delimitted list of resources that Facelets should use. If no resource paths are specified,
            Facelets will handle all requests (DEFAULT). If one or more paths are specified,
            Facelets will only use the ones specified, otherwise fall back on the parent or default ViewHandler (JSP).
            Note, this requires the FacesServlet in your web.xml to be mapped with a prefix for capturing multiple file types ex: /faces/*.
        </description>
        <param-name>facelets.VIEW_MAPPINGS</param-name>
        <param-value>*.xhtml</param-value>
    </context-param>
    <context-param>
        <description>
        The buffer size to set on the response when the ResponseWriter is generated.
        By default the value is -1, which will not assign a buffer size on the response.
        This should be increased if you are using development mode in order to guarantee that the response
        isn't partially rendered when an error is generated.
        </description>
        <param-name>facelets.BUFFER_SIZE</param-name>
        <param-value>8192</param-value>
    </context-param>
   
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>forward.jsp</welcome-file>
    </welcome-file-list>
</web-app> 

(Pages 56-57)
Note: The output from the debug does not work on facelets 1.1.14 because of a JavaScript error. You must use facelets version 1.1.11, or 1.1.15B1 for the debug to work properly. (See Facelets issue #292 on facelets.dev.java.net.)

(Page 66)
This code sample would not work for me. I needed to add <h:panelGroup> wrappers around the <ui:include> tags in the <h:panelGrid> components.

An alternative to would be to make the customerList a component and not a composition.

(Pages 77-78)
The templateClient02.jsf and templateClient02a.jsf code has a <ui:debug> components shown in the code. These will not work here. It must be in the template for it to work.

(Page 87)
The fourth paragraph has a typo which should be "Facelets and JSP..."

Chapter 3

(Page 97)
The <t:inputCalendar> component does not have a type attribute.

(Page 104)
There should be an explanation why the encoding type (enctype) is required on the <h:form> component. This is something that has been changed from the other examples and could easily be overlooked.

Note: The file:/// syntax will not work on Firefox, or Safari. It may not work on other browsers as well. This is a built-in security feature of those browsers. So this example will not work using those browsers. If you want to be able to actually click on the hyperlinks and have them work, I had to use Lynx. This is a command line browser which does not incorporate this security mechanism.

(Page 116)
The action on <t:commandNavigation> for products does not match the provided code. It should be <t:commandNavigation value="products" action="#{productBean.displayProducts}"/>

(Page 125)
The <t:jscookMenu> theme should be theme="ThemePanel" to match the provided code.

(Page 136)
Note: The <t:dataTable> component must be inside a <h:form> component for the table sorting to work.

Chapter 4


(Page 142)
Note: The installation and configuration section has an example of how to set up Apache Trinidad using facelets. This is contrary to the preferred method which is detailed on the Apache Trinidad Installation page. Below is a copy of my web.xml file which has the correct Apache Trinidad configuration.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">

    <!-- BEGIN Apache Trinidad BEGIN -->

    <context-param>
        <description>
            Note: TrinidadFaceletViewHander must be the alternate view handler if SessionChangeManager is used.
        </description>
        <param-name>org.apache.myfaces.trinidad.ALTERNATE_VIEW_HANDLER</param-name>
        <param-value>org.apache.myfaces.trinidadinternal.facelets.TrinidadFaceletViewHandler</param-value>
    </context-param>
    
    <context-param>
        <description>
            Unfortunately, Facelets provides no hook for plugging the PageResolver into the logic
            handling "facelets.VIEW_MAPPINGS". You should leave "facelets.VIEW_MAPPINGS"
            unset and use "org.apache.myfaces.trinidad.FACELETS_VIEW_MAPPINGS" instead.
        </description>
        <param-name>org.apache.myfaces.trinidad.FACELETS_VIEW_MAPPINGS</param-name>
        <param-value>*.xhtml</param-value>
    </context-param>

    <context-param>
        <description>
            Trinidad also supports an optimized strategy for caching some
            view state at an application level, which significantly improves
            scalability.  However, it makes it harder to develop (updates to
            pages will not be noticed until the server is restarted), and in
            some rare cases cannot be used for some pages (see Trinidad
            documentation for more information)
        </description>
        <param-name>org.apache.myfaces.trinidad.USE_APPLICATION_VIEW_CACHE</param-name>
        <param-value>false</param-value>
    </context-param>

    <context-param>
        <description>
            If this parameter is enabled, Trinidad will automatically
            check the modification date of your JSPs, and discard saved
            state when they change;  this makes development easier,
            but adds overhead that should be avoided when your application
            is deployed
        </description>
        <param-name>org.apache.myfaces.trinidad.CHECK_FILE_MODIFICATION</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <description>
            Enables Change Persistence at a session scope.  By default,
            Change Persistence is entirely disabled. The ChangeManager is
            an API, which can persist component modifications (like,
            is a showDetail or tree expanded or collapsed). For providing
            a custom Change Persistence implementation inherit from the
            Trinidad API's ChangeManager class. As the value you have
            to use the fullqualified class name.
        </description>
        <param-name>org.apache.myfaces.trinidad.CHANGE_PERSISTENCE</param-name>
        <param-value>session</param-value>
    </context-param>

    <context-param>
        <param-name>org.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION</param-name>
        <param-value>true</param-value>
    </context-param>

    <!-- Use client-side state saving.  In Trinidad, it is an
       optimized, token-based mechanism that is almost always a
       better choice than the standard JSF server-side state saving. -->
    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
        <!--param-value>server</param-value-->
    </context-param>

    <!-- Trinidad by default uses an optimized client-side state saving
       mechanism. To disable that, uncomment the following -->
  <!--context-param>
    <param-name>org.apache.myfaces.trinidad.CLIENT_STATE_METHOD</param-name>
    <param-value>all</param-value>
  </context-param-->

<!-- END Apache Trinidad END -->

    <filter>
        <filter-name>trinidad</filter-name>
        <filter-class>org.apache.myfaces.trinidad.webapp.TrinidadFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>trinidad</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

    <!-- Faces Servlet -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    </servlet>

    <!-- resource loader servlet -->
    <servlet>
        <servlet-name>resources</servlet-name>
        <servlet-class>org.apache.myfaces.trinidad.webapp.ResourceServlet</servlet-class>
    </servlet>

    <!-- Faces Servlet Mappings -->
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>resources</servlet-name>
        <url-pattern>/adf/*</url-pattern>
    </servlet-mapping>

    <!-- Welcome Files -->
    <welcome-file-list>
        <welcome-file>/forward.jsp</welcome-file>
    </welcome-file-list>

</web-app>


(Page 144)
Note: I also found that a number of examples use <h:form> instead of <tr:form> which is also preferred.

(Page 145)
The component <tr:chooseColor> has a closing tag before the id attribute, and will not work unless it is removed.

(Page 147)
The references to commandButton and outputText should use the tr prefix instead of the h prefix since it is supposed to be demonstrating the Apache Trinidad components and not the RI.

(Page 150)
The <tr:inputListOfValues> has columns="25" in the code.

The <tr:panelGroupLayout> rendered attribute has a coding error in it. It should have a space between ne and null like this rendered="#{productBean.selectedProduct ne null}".

Also this example is incomplete since it does not show, or discuss the pop-up dialog which is part of the component functionality.

(Page 153)
The last paragraph which discusses validating using client side alerting should be a note to stress its importance.

(Page 158)
The facets which are listed under the <tr:statusIndicator> tag have incorrect attributes. They should be name and not message.

(Page 159)
The <tr:poll> component should use the slowPollListener under the pollListener attribute.

(Page 160)
The backingBean component in the first example does not contain slowNumber field.
The second example on the page uses backingBean.pollListener which should actually be backingBean.progressListener.

(Page 165)
The provided code does not contain a styleClass attribute in the <tr:panelGroupLayout> component. Also the <tr:spacer> component has a height of 10 in the provided code.

(Page 166)
The image does match the actual output unless you remove the styleClass attribute from the code.

(Page 167 and 168)
The <tr:commandButton> actionListener does not exist. It should be actionListener="#{productBean.saveSelected}".

(Page 171)
The inlineStyle of the <tr:column> component should have a semi-colon at the end of the value.

(Page 173)
This section was a total failure. The provided code does not work.

(Pages 175 and 177)
This section did not work, nor did the sample code for using XMLMenuModel items.

(Page 191)
The image does not match the code example. The image is for another component dialog.
In addition, the color chooser dialog does not convert the color back correctly. I had to modify the Customer.getFavoriteColorHexValue() to get it to work.
public String getFavoriteColorHexValue() {
String value = null;
if (favoriteColor != null) {
int rgb = favoriteColor.getRGB();
value = Integer.toHexString((rgb & 0xffffff) | 0x1000000).substring(1);
}
return "#" + value;
}

Chapter 5

(Page 196)
The <ice:inputText> for name has an error in the backingBean syntax. It should be value="#{backingBean.name}".

(Page 200)
The components require <f:dateTimeConverter>s to display the values correctly.

(Page 205)
The Toco-Toucan.jpg image name is missing the "-" so the image would not display.

(Pages 212 and 213)
This example is poorly designed and impractical. It displays column numbers at the tops of each column. Who would do that? This should be more practical and show column names for the values in the columns.

(Page 214)
The <ice:commandSortHeader> for birth date should be removed since the code is duplicated.

(Page 215)
The data model UML is not correct. It should be SortableDatamodel <T extends Selectable>.

(Page 216)
The afterPhase method has an argument arg0. This should be phaseEvent which is more descriptive in keeping with a more modern coding style. The code will work, but it is considered bad form.

(Pages 218 and 219)
The <ice:commandSortHeader> for birth date should be removed since the code is duplicated.

(Page 225)
I must admit adding data set paging using ICEfaces is very easy.

(Pages 238-239)
The code here is irrelevant here and should be removed. It is duplicated in the next section on page 239 which actually covers this component.

Chapter 6

(Page 256)
The second paragraph has a typo. It should be "...specified in advance,...".

(Page 275)
The name of the bean should be ShippingCalculatorBean. The t in calculator is missing.

Tuesday, February 09, 2010

NetBeans 6.8 JSR-296 Database Application Example

Here is an example application development video.

Monday, January 18, 2010

Apache Commons Configuration Example

The other night at the Greenville Java Users Group meeting I asked the members of the JUG to join an open source project and make a difference. I told them that you do not need to necessarily contribute code, but providing documentation assistance would make a difference.

In the same meeting I asked how many people could tell me about any of the Apache Commons projects. I was surprised at how many people could only list a couple. No one had heard of the Apache Commons Configuration project. I use the project to load properties into some of my projects. I was surprised that so many people "roll their own" around properties files.

I decided to make an Apache Maven project which demonstrates the power and simplicity of the framework.

Here is the sample code: apache-commons-configuration-example.zip

/*
 * Copyright 2010 Blue Lotus Software, LLC.
 * Copyright 2010 John Yeary <[email protected]>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
/*
 * $Id: Application.java 168 2010-01-19 03:09:36Z jyeary $
 */
package com.bluelotussoftware.example.apache.commons;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * <p>Example application to demonstrate the Apache Commons
 * Configuration framework.</p>
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @version 1.0-SNAPSHOT
 */
public class Application {

    private static final String PROPERTIES_FILE_NAME = "configuration.properties";

    /**
     * <p>Default no-arg constructor.</p>
     */
    public Application() {
    }

    /**
     * <p>Main application entry point.</p>
     * @param args
     * @throws ConfigurationException
     */
    public static void main(String[] args) throws ConfigurationException {
        Application application = new Application();
        application.createProperties();
        application.setBackground("#c53478");
        String background = application.getBackground();
        System.out.println("background-color:" + background);
    }

    /**
     * <p>Creates a property file on the local system disk.</p>
     * @throws ConfigurationException if an <code>Exception</code> is encountered.
     */
    public void createProperties() throws ConfigurationException {
        // Create a new property and save it.
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.save(PROPERTIES_FILE_NAME);
    }

    /**
     * <p>Sets a property called <code>colors.background</code> to the value provided, or assigns a color
     * value{@literal #000000} if none is provided .</p>
     * @param backgroundColor
     * @throws ConfigurationException if an <code>Exception</code> is encountered. 
     */
    public void setBackground(String backgroundColor) throws ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.load(PROPERTIES_FILE_NAME);
        if (backgroundColor == null) {
            config.setProperty("colors.background", "#000000");
        } else {
            config.setProperty("colors.background", backgroundColor);
        }
        config.save(PROPERTIES_FILE_NAME);
    }

    /**
     * <p>Retrieves the background property from the properties file on
     * the system disk.</p>
     * @return the background color assigned in the properties file.
     * @throws ConfigurationException if an <code>Exception</code> is encountered.
     */
    public String getBackground() throws ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.load(PROPERTIES_FILE_NAME);
        String background = (String) config.getProperty("colors.background");
        return background;
    }
}

Friday, September 11, 2009

Using JTabbedPane on Swing Application Framework (JSR-296)

I was trying to figure out how to set the selected tab for a multi-tab JTabbedPane on my Swing Application Framework application. I thought that a quick Google search would have a simple answer. This was not the case. I found a post on a forum where a number of other people were wondering how to do it. So here is a summary of how I did it.

On the Frameview, I added a method as show below:

public void setSelectedTab (Integer tabIndex) {
tabPanel.setSelectedIndex(tabIndex);
}


The tabPanel in my case is the JTabbedPane instance.

In the SingleFrameApplication, I modified the startup() method to display the tab I want.

Note: You must set it after a call to show() the FrameView

@Override
protected void startup() {
FrameViewImpl frameView = new FrameViewImpl(this);
show(frameView);
//This must be done after the GUI is displayed
frameView.setSelectedTab(0);
}

Thursday, September 10, 2009

Beans Binding Part Deux

I have really enjoyed using the Beans Binding Framework (JSR-295) in the past. It was a really good start to making Swing a more usable platform doing client development. The project and JSR have been left abandoned by Sun. In large measure this was the result of development work done by Sun on JavaFX.

The really painful part of JavaFX currently is based on two items:
  1. No table (grid) component.
  2. No data providers to make binding to a database easy.
The result is a nearly useless framework for business developers who don't need shiny new baubles. I need Swing to work.

I am not the only person who feels this way. Fabrizio Giudici has created a project on Kenai.com to address the shortcomings: Better Beans Binding. He took the original JSR-295 code and forked it to create the new project. The package names have remained the same to allow a drop in replacement for the current beans binding framework without breaking anything. I am excited that Fabrizio has decided to do this project. I am hopeful that others wil join the project and make "better beans binding" a reality for the business users and others who need to make Swing just work.

Friday, February 06, 2009

Book Review: Pro Netbeans IDE 6 Rich Client Platform Edition

Disclaimer: Adam Myatt and I have been on the JavaOne 2008 and 2009 Tools and Languages Review Committee. I don't believe that there is any predjudice for/against the book, but in the interest of disclosure I thought it important to mention. Don't you wish politicians had that much honesty?

I had the pleasure of reading the Pro NetBeans IDE 6 Rich Client Platform Edition book by Adam Myatt. I had read it a while ago, but I did not have the time to do a review on it. The book is sixteen chapters long, and covers a variety of topics from download and installation to developing rich client applications. The book covers version 6/6.1 of NetBeans, but there is significant applicability to version 6.5 to make it worth purchasing.

The book has a primary target of new users to the NetBeans IDE. It is designed to take you from novice user to power user in a systematic organized way. The book is sufficiently modular that you can choose to read individual modules, or go from cover to cover. The chapters stand on their own so that you do not need to worry about missing something in a previous chapter if you decide to browse.

Based on the easy reading style and effectiveness of communicating complex topics, I would give the book (4/5) stars.

Chapter 1:
Downloading, Installing, and Customizing NetBeans

This chapter covers the basics of installation, and explains a number of options available for configuration.

Chapter 2:
The Source Editor

Here we cover the basics of the source code editor and its windows. It also covers some interesting features of the source editor like the error stripe and annotation glyphs. The error stripe allows the user to go directly to any errors which are in the code. The annotation glyph provides the user with suggestions. These may be as simple as reminding you to mark @Override on an overridden method.

One of the best discussions in the chapter has to do with built-in and custom macros you can create to simplify coding tasks. This was a great explanation of how it works.

Chapter 3:
Code Completion and Templates

Code completion is what makes an IDE so valuable. This chapter covers the NetBeans code completion technology in detail.

It also covers code templates which are a boon to any developer who learns to use them. Adam really explains this in a manner that makes them easy to learn and use.

Chapter 4:
Debugging

I thought I was fairly sophisticated in my use of debugging. This chapter made me feel inadequate. After reading it and implementing some of the ideas, I feel I am back to being an expert.

Note: I found one error on page 95. The third paragraph has Run --> Run File -->Run Debug Evaluate Expression. It should be Run --> Run File --> Run to Cursor.

I would buy the book for this chapter alone.


Chapter 5:
Profiling

This chapter covers profiling for performance. Sun and NetBeans has spent a lot of time creating this technology (like DTrace), instrumenting, and providing tools. It is a shame that they really have not promoted these capabilities to the developer community.

Adam has spent a lot of time detailing profiling and providing great examples to get you into it. His explanations may be enough to encourage developers to use these really great tools.

This chapter also includes how to profile remote JVMs and application servers. It is a really slick explanation and demo.

Chapter 6:
Managing Version Control

This chapter covers version control system implementations in NetBeans. It covers CVS and Subversion. Since the book was written, the Subversion implementaion has had numerous improvements. NetBeans 6.1 and 6.5 also include support for Mercurial.

Chapter 7:
Generating and Accessing Javadoc

This chapter covers Javadocs and tools in the IDE to make Javadocs easier to create. I must admit I thought they were already easy, but there are some features to make it even easier including code completion.

Chapter 8:
Managing Builds with Ant and Maven

This covers Apache Ant and Maven implementations in NetBeans. Adam covers some of the features of Ant with a high degree of skill. He covers the NetBeans implementation very well.

The section on Maven is a weak spot in the book. In fairness, the version of NetBeans which the book was based on had poor Maven capabilites. Version 6.5 of NetBeans has much better tools for handling Maven.

Chapter 9:
JUnit Testing

This chapter covers JUnit testing. This is another chapter that is a little to weak. NetBeans 6.0, 6.1, and 6.5 have some really great implementations for doing JUnit testing. This chapter does not do it justice.

Chapter 10:
Refactoring

This chapter covers refactoring. NetBeans has some really great refactoring tools.

JetBrains IntelliJ IDEA is the gold standard for refactoring, but each generation of NetBeans brings it one step closer.

There are some comprehensive explanations of how to use the refactoring tools in NetBeans. If you want to master the IDE, this chapter, and chapters 4, and 11 are a must.

Chapter 11:
Code Quality Tools

This chapter covers some of the really great plugins that are available for NetBeans including: Checkstyle, PMD, and SQE (FindBugs). If you are not using these static analysis tools in your code, you are doing yourself and customers a disservice. This chapter covers the tools in enough detail to get your interest. These plugins are in constant development, and you should check the latest versions and updates out.

These tools will make your code much better. You as a developer need to understand why. When Checkstyle marks code as a "Magic Number", you need to read the explanation. Understanding the why will help you to avoid these problems in your future code.

Chapter 12:
Developing JRuby/Ruby on Rails Applications

This chapter covers developing JRuby, and Ruby-on-Rails (RoR) applications using NetBeans. The chapter is not designed to teach you to program in Ruby, but to show you what features are available in the IDE. The NetBeans support for Ruby is fantastic. A number of other IDE developers are trying to emulate the functionality. I think that most Ruby developers will find that the support is a quantum leap in terms of ease and functionality over more traditional tools.

There is a note on page 297 which explains a really neat feature. If an existing application is deployed using Webrick, or Mongrel on port 3000, the IDE will increment the port number to prevent port in use errors.

Chapter 13:
Developing Web Applications

This is a long chapter covering web application development. The first part of the chapter covers the functionality of the IDE in terms of what features it provides. This includes items like the Javascript and CSS editors. Both of these tools are really useful.

The Javascript editor and debugger have been vastly improved in NetBeans 6.5.

The CSS editor with a change viewer make designing, or changing a CSS file a snap.

The chapter also covers the application server features and HTTP monitor. Specifically it covers Apache Tomcat and GlassFish. It explains how to add additional servers like JBoss, or Websphere to allow those server deployments.

The second half of the chapter covers web application development frameworks. The section covers Struts, Struts 2, Visual Java Server Faces (JSF) (Project Woodstock), and JMaki.

The Struts and Struts 2 section is relatively small. It provides the user with the basics of how to create and use Struts based projects.

The section on Visual JSF development is extensive and makes the book worth purchasing. The explanation on how to get started will set you on the right path. The section on visual data binding is elegant and simple. It also covers the Visual Database Query Editor. This functionality has been updated in NetBeans 6.5, but the explanation here still applies.

Note: Visual JavaServerFaces (JSF) development in NetBeans has been frozen. The promise of Project Woodstock in a version 4.3 release and beyond has been abandoned officially by Sun. The current supported version is 4.2. It will continued to be supported by the NetBeans team for the foreseeable future. The push by Sun is to provide support using third party providers of JSF components. The best of these providers is ICEFaces. They have a really great set of components, and have provided a transition plan for Project Woodstock developers.

The section on JMaki is too brief to really provide a great explanation of this great technology.

Chapter 14:
Developing Web Services: JAX-WS, SOA, BPEL, and RESTful

This chapter covers JAX-WS, SOA, BPEL, and RESTful services. These projects have undergone extensive updates which makes the information here slightly dated. The basic procedures are the same, but there are better tools in NetBeans 6.5.

Chapter 15:
Developing GUI Applications

This chapter covers GUI application development. It is the best aggregation on the subject I have seen. There are a number of tutorials on the NetBeans site, and some good explanations of the features, but this is the best explanation I have seen. There is a great tutorial example of how to use the various components of the IDE to do visual Swing development. I was impressed and learned some new things too.

There is a section on the Swing Application Framework (JSR-296) which is the best I have seen. This technology is supposed to make Swing development easier. I used the information in here to create an enterprise wide application in 1/4 of the time it normally takes. It was also less error prone since the framework handles threading and concurrency issues.

Note: On page 427 there is a code example that has the user add a showHelloWorld method. There is a missing variable that needs to be added. It should have:
private JDialog helloWorldBox;
There is another section on Beans Binding (JSR-296) which covers another ease of use technology for Swing. It allows the developer to bind data components to Swing components in an easy and consistent way. The explanation here of the technology combined with JSR-295 makes Swing development easy. It also covers the Database Table Editor to make modifying tables easy to use as part of the binding process.
Note: Page 431, last paragraph indicates that you can use the DOUGHNUTS table node to use the table editor, this is not correct. You must open the table, and select a column to open the table editor.

Note: Page 442, to use the validator you have created, you must compile the code first. Either by selecting the class itself and compiling it, or clean and building your project.

I personally found that the GUI project development section was crucial to me for using these great new technologies, and development of a successful enterprise Swing application.

Chapter 16:

Developing Rich Client Applications

This chapter covers the development of Rich Client Platform applications using the NetBeans platform as the base for your application. This section provides an introduction to the technology, and the basics of how to create your own branded rich client applications.

Summary:

I would recommend this book to anyone who wants to learn more about the NetBeans IDE.

Based on the easy reading style and effectiveness of communicating complex topics, I would give the book (4/5) stars.

Popular Posts