Quick tutorial today!

If you’re experimenting on JSF and wanna check out the features that ajax can provide you but like me, you don’t like your business code on the client side, then this is for you 😀

First, of all, a super important note. Don’t mix your imports when dealing with ManagedBeans!! Make sure you’re either using CDI or JSF. For this example, i’ll be using javax.faces.bean package. Please make sure this is ok. It can give you really weird bugs…

So, what’s the idea. Let’s try and make a simple validator (which can be done in JSF ressorting to other methods but that will do as an example) which checks if a field is a INT and if not, then shows an error message.

We’ll need a .xhtml for the page and the managedBean.

In your .xhtml put something like this:

<h:form id=myForm>
<h:inputText value="#{bean.myvalue}" styleClass="someStyle">
<f:ajax event="change" render="error_sub" listener="#{bean.validateMyValue}"/>

<h:panelGroup id="error_sub">
<h:outputText value="Incorrect Format for Value!!" styleClass="someErrorStyle"  rendered="#{bean.show}" />

Two important/cool notes in this html.

First, ajax in JSF will only work if nested in a form.

Second, to make a ‘section/tag’ of your page disappear you cannot use rendered on that same tag with ajax! Ajax only sees rendered=true tags! So, to do that, apply the ajax to a ‘superior’ tag, like i’m doing with panelGroup. In your validation function however, you can use a boolean like ‘show’ which can be used to declare if outputText is to be display or not.

Got it? Ajax invokes validateMyBean which sets show to true or false… Renders error_sub again which this time, in case of an error, is display or not according to ‘show’. Got it? This is very important.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

public class MyBean {

private String myvalue;
private boolean show;

//Getters and Setters for myvalue!! Don't forget these!!

public boolean validateMyValue(){
catch(Exception e){
return false;
return true;

The above bean is used to place the variables, your getters and setters and your validation method.

Simple right? Well… now it is! 😀



Hi there!

If you’re developing a website with JSF v2 and are having issues with page jumping/direct access when credentials should be applied first, then this post is for you. 🙂

Normally, when applying such mechanisms one resorts to filters with servlet association. However, with JSF this can be tricky because (in my experience at least) the filter is initialized before your managed beans and FacesContext are. This is an issue for most examples out there, because the filter will give ‘null’ when accessing the sessionScoped bean (or in any other managedBean) where your credentials are supposed to be checked. So, how to achieve this? Using a PhaseListener.

A PhaseListener is a something that you can apply whenever a ‘request’ happens. So before the actual call to your ManagedBean happens, a routine can be called in your PhaseListener. With it, you can limit right there what will happen. So, first here is your listener:

public class AuthorizationListener implements PhaseListener {

public void afterPhase(PhaseEvent event) {

FacesContext facesContext = event.getFacesContext();
String currentPage = facesContext.getViewRoot().getViewId();

boolean isLoginPage = currentPage.lastIndexOf("index.xhtml");
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
Object currentUser = session.getAttribute("username");

if (!isLoginPage && (currentUser == null || currentUser == "")) {
NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
nh.handleNavigation(facesContext, null, "loginPage");

public void beforePhase(PhaseEvent event) {

public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;

What we are describing here is that whenever a call is made for a page, then first, the attribute ‘username’ must be checked. For this however we also need two more things. First, declare your faces-config.xml like so:

<faces-config version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">



And your login method (which will be in your ManagedBean):

public void login(){

boolean result = businessBean.checkCredentiais(username, password);

try {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", username);

} catch (IOException ex) {
Logger.getLogger(UserCredentiaisView.class.getName()).log(Level.SEVERE, null, ex);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", "");
errorMessageLogin = "Credentials not supported.";

And that’s it! Just don’t forget to clear your credentials in your logout method!! 😀

Stay cool! 🙂

Hi there!

If you need to store random passwords on your database and want to encrypt them for more safety, good for you! 😀

Here are some easy steps to help you on the way. First a Sha1Convertion Class:

public class Sha1Convertion {

public Sha1Convertion(){

public String makeSHA1Hash(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] buffer = input.getBytes();
byte[] digest = md.digest();

String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
return hexStr;

Second, a random generator for your passwords:

public class PassPhrase {
/** Length for password */
public static final int MIN_LENGTH = 10;

/** The random number generator. */
protected static java.util.Random r = new java.util.Random();

* Set of characters. This is limited to numbers and letters for error issues.
protected static char[] goodChar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'2', '3', '4', '5', '6', '7', '8', '9', };

/* Generate a Password object with a random password. */
public static String getNext() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < MIN_LENGTH; i++) {
return sb.toString();


Finally, your main (this is for 20 passwords):

Sha1Convertion shc = new Sha1Convertion();

for (int i = 0; i < 20; i++) {
String pass = PassPhrase.getNext();
System.out.println("Current - " + pass);
String result = shc.makeSHA1Hash(pass);
System.out.println("SHA1 - " + result);

And that’s it!! Stay cool! 🙂

Quick note today!

If you, like me, want to get rid of that pesky streaming server that you installed a long time ago for a now forgotten reason, here’s a quick tip 😉

1) Go to a Finder window.

2) On the tool bar, select ‘Go to‘ and input the following path “/etc/

3) Find the hostconfig file in there. Open it with an editor (any text editor).

4) Search for QTSSWEBADMIN, QTSSRUNSERVER and QTSSERVER. Put them all with –NO-.

5) Save the file. Restart.

6) Check in your browser to confirm or place a “ps aux” in your terminal and see if Quick Streaming Server will be there… I know it won’t 🙂


Simple note.

If you’re trying to place .eps figures into your .tex but errors continuously come up and you don’t want to use command line apps to resolve the issue, here’s a quick tip:

Simply import the epstopdf package in your .tex file 🙂


If you’re programming with J2EE and reach a place where you need to use more than one database, don’t dispair, it’s possible! 😀

So, what you need to do.

First, define your persistence.xml. Each database will have an entry. Here’s an example using Hibernate:

    <persistence-unit name="DatabasePU1" transaction-type="JTA">


This example shows the name of the persistence unit (DatabasePU1) which we’ll need to distinguish from the others. The jta-data-source is the JNDI name you gave to the descriptor (i’ll explain this next). Finally, the classes which depend on this specific database.

Each database on the persistence.xml need to look like the above, so for other databases just follow the pattern. (Note: there’s only one persistence.xml on each project with one to multiple entries)

The jta-data-source corresponds to another file (jboss-ds.xml) that you must add to the deploy folder on your JbossAS (if it isn’t there).
It’s responsible for connecting to the databases.

Here’s an example of a datasource based on MySql:


If you’re using a different database, switch the connection entry and the driver. (just google and you’ll find the ones required for your specific case)

Once again, you’ll have multiple entries if you need multiple databases (just like the pattern so nothing new). Just remember, one database, one datasource.

Now, the bases are set. All that remains is using it!

Imagine you have two databases set. DatabasePU1 and DatabasePU2.

When you’re setting your EntityManager annotation, depending on the classes defined on the persistence.xml, add the unitName according to which database the class belongs to.

Exemplifying: Class1 belongs to DatabasePU1.
So when adding an EntityManager to use it, do it like this:

EntityManager em;

Nothing more to it really so enjoy! 😀

P.s- If for some small percentage you’re gonna use multiple databases from the same machine (which means multiple schemas) and are getting some odd errors based on GenericJDBC Exceptions try adding to the JPA beans the following annotation:


Hi! 🙂

Quick reminder for me today. To create a popup window in Swing with an error message for instances when a form value entry is incorrect, use the following code:

JOptionPane.showMessageDialog(this,”Your error message…”, “Your error title”, JOptionPane.ERROR_MESSAGE);

This may be very usefull inside a try catch!! 😀
However this type of windows can be used for collecting a value (a login p.e.)…showing a slider bar…among others!! Just change the method ‘showMessageDialog’ to the appropriate ones!!
Cumps!! 😀