Česky   |  Deutsch   |  English   |  Español   |  Français   |  Indonesia   |  日本語   |  한글   |  Polski   |  Português (BR)   |  Türkçe   |  中文   |  正體中文   |  Your Language  
PlanetNetbeans
Planet NetBeans is an aggregation of NetBeans related musings from all over the Blogosphere.
Adam Bien - September 18, 2017 07:17 AM
WebStandards Igniter On-Demand Workshop

80+ episodes of continuous HTML 5, CSS 3, JavaScript (ES 6/7) coding workshop is available: webstandards.training. Only vanilla WebStandards, without any external frameworks or dependencies, were used.

Are you already building, or still migrating? Learn once, apply anywhere :-):

See you also at: WebStandards Igniter Workshop at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - September 14, 2017 04:51 AM
42nd airhacks.tv is available -- The Answer to all questions included

The airhacks.tv 42nd episode with "The Answer to all questions" is available:

Any questions left? Ask now or suggest a topic: https://gist.github.com/AdamBien/ec94900a3efd5d621bf4f00cc8a0dbac.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - September 11, 2017 05:54 AM
Early Autumn Java (EE) / Web Events

See you soon at:


Real World Java EE Workshops [Airport Munich]>

NetBeans – Michael's blog - September 10, 2017 08:19 PM
Using WebSockets with Java EE, part 2.3

Technical aspects of the WebSocket protocol WebSockets in a Java EE 7 application JSF 2.3 and WebSocket As mentioned before, I divided part two into a couple of sub parts. Today I’ll finish with WebSockets in a Java EE 7. If we want the user to choose a different chat room which is operated on […]

Adam Bien - September 10, 2017 10:03 AM
A Java EE 7+ Alternative To EJB Timers

In addition to EJB timers (Simplest Possible EJB 3.1 Timer), with Java EE 7+ you can directly inject ManagedScheduledExecutorService, a subclass of ScheduledExecutorService available in stock Java SE:

    
        import java.time.LocalTime;
        import java.util.concurrent.TimeUnit;
        import javax.annotation.PostConstruct;
        import javax.annotation.Resource;
        import javax.ejb.Singleton;
        import javax.ejb.Startup;
        import javax.enterprise.concurrent.ManagedScheduledExecutorService;
        
        @Startup
        @Singleton
        public class Scheduler {
        
            static final long INITIAL_DELAY = 0;
            static final long PERIOD = 2;
        
            @Resource
            ManagedScheduledExecutorService scheduler;
        
            @PostConstruct
            public void init() {
                this.scheduler.scheduleAtFixedRate(this::invokePeriodically, 
                        INITIAL_DELAY, PERIOD, 
                        TimeUnit.SECONDS);
            }
        
            public void invokePeriodically() {
                System.out.println("Don't use sout in prod " + LocalTime.now());
            }
        
        }
    
Immediately after deployment, you should find the following output (likely with different timestamp :-):
    
        Info:   Don't use sout in prod 11:31:39.093
        Info:   Don't use sout in prod 11:31:41.097
        Info:   Don't use sout in prod 11:31:43.096
    
(ManagedScheduledExecutorService replaced EJB 3.1 timers in a project as a workaround to appserver configuration issues in production) See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - September 07, 2017 03:58 PM
Microservices' Impact On App Design, Lightweight Java EE and Java EE-stic HTML 5 ...or my JavaOne 2017 sessions


Session ID: CON5252
Session Title: Microservices and Cloud-Driven Code Simplification
Room: Moscone West - Room 2003 Date: 10/03/17
Start Time: 09:30:00 AM
End Time: 10:15:00 AM

Session ID: CON5567
Session Title: The Java EE-stic (=No Dependencies) Way to Develop HTML5 Applications
Room: Moscone West - Room 2006 Date: 10/04/17
Start Time: 09:30:00 AM
End Time: 10:15:00 AM

Session ID: CON5578
Session Title: Java EE: Heavyweight or Lightweight—Mythbusters
Room: Moscone West - Room 2020 Date: 10/04/17
Start Time: 08:30:00 AM
End Time: 09:15:00 AM

I'm also invited to the panel:

Session Title: Powerful Lessons from Top Java EE Experts
Room: Moscone West - Room 2002: Java User Group Track 
Date: 10/01/17
Start Time: 04:00:00 PM
End Time: 04:45:00 PM

Thanks and see you soon at JavaOne 2017, airhacks.com or airhacks.io


Real World Java EE Workshops [Airport Munich]>

Adam Bien - September 04, 2017 10:14 AM
42- the answer, Fork Join, Pixel Perfect JSF, Building React and Angular, Scanning JAX-RS, Async CDI Events, Monolith or Topics For 42nd airhacks.tv

Topics for the 42nd airhacks.tv:

  1. 42 airhacks.tv - the answer to all questions
  2. ForkJoin support in Java EE 8
  3. Java FX in the browser
  4. Code coverage in system tests
  5. Opensource Java EE
  6. Auto-scanning JAX-RS resources
  7. Java and the job market
  8. @Stateless as an interceptor?
  9. Asynchronous CDI Events
  10. Empty POST or PUT
  11. @Stateful EJBs and usecases for the Gateway pattern
  12. Will CDI replace EJB in the future?
  13. Java EE 7 server recommendations
  14. GlassFish clustering / workshop
  15. JSF and pixel perfect applications
  16. Impact of react and angular on the delivery pipeline
  17. How to build JS frontends with Java EE backends
  18. Using multithreaded JAX RS 2.0 in Java SE
  19. Incrementally splitting a monolith: protocols, security processes

See full topics gist.

Ask questions during the show via twitter mentioning me: http://twitter.com/AdamBien (@AdamBien) or using the hashtag: #airhacks. You can join the Q&A session live each first Monday of month, 6 P.M at airhacks.tv or http://www.ustream.tv/channel/adambien


Real World Java EE Workshops [Airport Munich]>

Adam Bien - September 02, 2017 05:22 PM
Reactivity, Security, JSF Testing, AMQP, Encryption, Trends or 41st airhacks.tv is available

25+ questions ranging from Java 9 Logging, over Reactive Programming and differences to CompletableFuture, testing JSF, AMQP to using frameworks or not, were answered during the 41st airhacks.tv:

Any questions left? Ask now or wait a month.

Btw: all airhacks workshops at MUC airport are well booked. See you soon: Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


Real World Java EE Workshops [Airport Munich]>

Adam Bien - August 31, 2017 06:36 AM
How to establish JMX connection to JVM running in docker

For remote monitoring of JVM processes (running in a docker container) you will have to activate remote JMX monitoring with the following JVM parameters:


        -Dcom.sun.management.jmxremote 
        -Dcom.sun.management.jmxremote.port=[RMI_PORT] 
        -Dcom.sun.management.jmxremote.rmi.port=[RMI_PORT]
        -Djava.rmi.server.hostname=[EXTERNAL_IP_OF_THE_CONTAINER]    

Both RMI_PORTs could have the same value (e.g. 9090). The EXTERNAL_IP_OF_THE_CONTAINER has to be the IP address with which the JVM process is accessible. Localhost or 127.0.0.1 won't work.

The following two parameters completely disable transport encryption and access control. They increase convenience and disable security at the same time:


        -Dcom.sun.management.jmxremote.ssl=false 
        -Dcom.sun.management.jmxremote.authenticate=false 

Given the RMI_PORT=9090, you can launch the process with docker run -p 8080:8080 -p 9090:9090 --name jmx airhacks/tomee-jmx and connect with jvisualvm, jconsole, jmc with EXTERNAL_IP_OF_THE_CONTAINER:9090.

Checkout out the instrumented TomEE dockerfile: tomee-jmx from docklands

See you at Java EE Microservices. and Tuning and troubleshooting Java EE 7 Microservices Is Munich's airport too far? Learn from home: javaeemicro.services.

Real World Java EE Workshops [Airport Munich]>

APIDesign - Blogs - August 14, 2017 04:59 PM
Design for JDK9: Use PropertyChangeListener, get whole Swing with that!

Designing for JDK9 is going to be more and more important when JDK9 is finally about to be released. However the modular design of Jigsaw brings in new challenges. Hear my story where I tried to update a library to run on headless JDK9: because there is a hidden catch - once you try to use PropertyChangeListener you get whole AWT/Swing user interface with that!

Learn how to avoid that: DesignForJDK9!

--JaroslavTulach 16:59, 14 August 2017 (UTC)

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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.

EventDescription
beginThis is the start of the AJAX request.
completeThis is invoked right after AJAX response is returned.
successThis 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

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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.

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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


Java Evangelist John Yeary - August 07, 2017 04:21 PM
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.

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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


Java Evangelist John Yeary - August 07, 2017 04:21 PM
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


Java Evangelist John Yeary - August 07, 2017 04:21 PM
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.

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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

Java Evangelist John Yeary - August 07, 2017 04:21 PM
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

Java Evangelist John Yeary - August 07, 2017 12:34 PM
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.

Java Evangelist John Yeary - August 07, 2017 12:32 PM
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

Java Evangelist John Yeary - August 07, 2017 04:28 AM
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

Adam Bien - August 07, 2017 04:26 AM
React over Angular, Reactive Programming, Blocking @Asynchronous, To Framework Or Not, SSR with SPAs, Java 9 Logging or 41st airhacks.tv

Questions for the 41st airhacks.tv:

  1. React over Angular? ...and WebStandards
  2. JSR-375 and REST
  3. Reactive Programming vs. CompletableFuture
  4. Blocking @Asynchronous calls
  5. Interceptors with EntityManager
  6. AMQP and data masses
  7. To Framework Or Not To Framework
  8. Unit Testing Primefaces
  9. Multi-Threaded JAX-RS 2.0 Clients
  10. Java EE "vs." .NET
  11. Dynamic entities
  12. Data encryption
  13. Working offline with JPA
  14. Sample Projects
  15. Industry trends, Conferences and Co.
  16. Server Side Rendering with Java EE 7
  17. Naming CRUD in BCE
  18. Java 9 Logging interface
  19. Generic REST client
  20. React.js / Polymer examples
  21. Session replication challenges

Ask questions during the show via twitter mentioning me: http://twitter.com/AdamBien (@AdamBien) or using the hashtag: #airhacks. You can join the Q&A session live each first Monday of month, 6 P.M at airhacks.tv or http://www.ustream.tv/channel/adambien

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Java Evangelist John Yeary - August 07, 2017 04:19 AM
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.

Java Evangelist John Yeary - August 07, 2017 04:08 AM
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.

Java Evangelist John Yeary - August 07, 2017 12:50 AM
SourceServlet: Displaying the Source Code and Pages from a Project on your Blog

SourceServlet
I had been working on a way to create nice examples that include a way to display the page and source code for it. I created a servlet that will display the code as plain text that I would like to share with all of you.

SourceServlet.java


Adam Bien - August 04, 2017 03:51 AM
Build To Last From Frontend To Backend: Applying Thin WARs Ideas to HTML 5

During the Devoxx conference in Krakow I presented what happens, if you apply the Thin WAR Java EE ideas to build HTML 5 applications:

See you at Building HTML 5 Apps with WebStandards but Without Frameworks at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


Real World Java EE Workshops [Airport Munich]>