JSF App slow with JPA connection

If you are working on Java Persistence API JPA on tomcat or any other web server this would be happening if you have multiple threads going off for connections.

The rule of thumb shall be to have one EntityManagerFactory and get EntityManagers out of it. Hence we would have one factory but multiple products that would take care of closing and managing them selves.

What are the signs:

1. Do you instantiate Persistence.createEntityManagerFactory(“name”) from multiple places?
2. What do you see on Process when you run

ps -aux | grep tomcat

Do you see multiple instances

If either or both of the above have yes, then here is the solution.

The first thing have single instance of ManagerFactory


package com.enderase.persistence;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
* Singlton implementation for EntityManagerFactory
*
* @author Kaleb Woldearegay<kaleb@gullele.com>
*/
public class HibernateUtil {
private static final EntityManagerFactory entityManagerFactory;

static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("jpa");
} catch (Throwable exception) {
//log your error here
throw new ExceptionInInitializerError(exception);
}
}

public static EntityManagerFactory getEntityManager() {
return entityManagerFactory;
}
}

Then make sure you are taking care of the instances of the EntityManagers that are created from the factory using

EntityManagerFactory entityManagerFactory = HibernateUtil.getEntityManager();
EntityManager em = entityManagerFactory.createEntityManager();

Make sure to close them appropriately after using them

This should pretty much take care of the problem

 

Check if there are three numbers a, b, c giving a total T from array A

I got this question while helping a friend on the course work. It is relatively simple question. But the way how it is approached can make a difference on efficiency.

The question is, given an array of numbers, you are to find if there are three numbers that would total the given number T.

If done in a very naive way, it can soar to o(n^3) like having three loops and checking the sum inside the third loop.. well.. this is a no no..

I have approached it in a log n ( for sorting) and n for (searching) approach..


package algorithm;

import java.util.Arrays;

/**
 * Given an array of integers, find if there are three numbers that would sum up to the 
 * number T
 * 
 * @author http://gullele.com
 *
 */
public class ThreeNumbersSummingT {
	public static void main(String[] args) {
		int[] test = new int[]{1,3,4,5,10,12, 18};
		ThreeNumbersSummingT summt = new ThreeNumbersSummingT();
		
		int[] response = summt.findThreeNumbers(test, 29);
		
		if (response.length > 1) {
			for(int num : response) {
				System.out.println(num);
			}
		} else {
			System.out.println(":( Couldn't find those three gems");
		}
				
	}
	
	public int[] findThreeNumbers(int[] nums, int t) {
		
		int[] indexes = new int[1];
		if (nums.length == 0 || nums.length <= 2) {
			return indexes;
		}
		
		//for primitive this would be quick sort so we have nlogn
		Arrays.sort(nums);
		
		int minIndex =0;
		int maxIndex = nums.length-1;
		int current = 1;
		while (minIndex != maxIndex) {
			if (nums[minIndex] + nums[maxIndex] + nums[current] == t) {
				int[] summingNumbers = new int[3];
				summingNumbers[0] = nums[minIndex];
				summingNumbers[1] = nums[current];
				summingNumbers[2] = nums[maxIndex];
				return summingNumbers;
			}
			
			int lookingFor = t-(nums[minIndex] + nums[maxIndex]);
			//if the number being sought is beyond the max, then jack up the min index
			if (lookingFor >= nums[maxIndex]) {
				minIndex++;
				current = minIndex + 1;
			} else if (nums[minIndex] + nums[maxIndex] + nums[current] < t) {
				current++;
			} else {
				maxIndex--;
				current = minIndex + 1;
			}
			
		}
		
		return indexes;
	}
}


Accessing one bean in another without using annotation

I would say we have to use annotations and Injection to get the bean inside another bean.
But in case you are interested to get it without using annotation you can use the following in the action/actionListener

TheBean theBean = (TheBean)FacesContext.getCurrentInstance() .getExternalContext().getRequestMap().get("theBean");

Where theBean is one we are interested to get it from being in the other bean.

That is it!

Adding session bean to to requested bean using annotation JSF

One major part on JSF would separation of concerns even for beans. As a rule of thumb beans related to model are session beans and those which have actions to be taken care of are requested one.

So, In this particular scenario we would have two beans. Basically we don’t want to include any logic inside the session bean, rather we would add session bean as a member variable to request bean.

Lets take a simple registration process.

The requested bean which will be responsible for actions would look like

package com.enderase.beans;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Serializable;

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

import com.enderase.model.Contractor;

@ManagedBean
@RequestScoped
public class ActionListeners implements Serializable{
	
	@ManagedProperty(value="#{contractorBean.contractor}")
	private Contractor contractor;
	
	public void setContractor(Contractor contractor){
		this.contractor = contractor;
	}
	
	public Contractor getContractor() {
		return this.contractor;
	}
	
	private static final long serialVersionUID = 1L;
	
	
	/**
	 * Action handler for Contractor save.
	 * @return String, next
	 */
	public String registerContractor() {
		Contractor contractor = this.contractor;
		if (contractor != null) {
			try {
				FileWriter fileWriter = new FileWriter("/tmp/name.note");
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("Name "+contractor.getName()+" Email "+contractor.getEmail()
						+contractor.getState());
				bufferedWriter.close();
			} catch (Exception ex) {
				//log the exception here
			}
		}
		return "navigated";
	}
}

So the key thing here would be the @ManagedProperty part.
That would inject the session bean into the request bean without creating any instance of it.

*Don’t for get to add getter and setter for the session bean you are adding otherwise you would get an error.

The session bean would be a simple holder of model

package com.enderase.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.enderase.model.Contractor;

@ManagedBean
@SessionScoped
public class ContractorBean {
	
	private Contractor contractor;
	
	public ContractorBean() {
		this.contractor = new Contractor();
	}
	public Contractor getContractor(){
		return this.contractor;
	}
	
	public void setContractor(Contractor contractor){
		this.contractor = contractor;
	}
}

Where the contractor would be a simple POJO file

asadmin-command-unknown-in-glassfish-ee-application

am a great user of tomcat when it comes to Java web application. I had fun with it. Being fast and allowing a bunch of things to be done by myself.. that being said, I am a regular user of glassfish as well. Specially the later version 3 looks awesome in a lot of ways..

I will try to use this blog to amend any hiccups whenever they appear and a bit of more tutorials as well.

The first one is the command line friend asadmin.

On the new version it will be found on

/glassfish-main-directory/glassfish3/glassfish/bin

Being on this directory if you issie

./asadmin

You will get the command line for it.
To add it to your path so that you can use it from any where in your terminal, just add it to your path

open your ~/.bash_profile or .bash_rc [create it if it doesnt exist and add the above directory at the end of it separated by appropriate directory separator.

That is it..

Mass/Multiple file upload in Java ServerFaces JSF

Without knowing if it is the best approach or not, I will post how I solved the multiple file upload problem in JSF as follows.
Here is the xhtml file that would take the files


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:t="http://myfaces.apache.org/tomahawk">
<h:head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:outputScript library="javascript" name="amharic.js"/>
<title>OH YEA, PUT your face HERE</title>
</h:head>
<h:body>

<h:form id="uploadForm" enctype="multipart/form-data">
<h:panelGrid columns="3">
<h:outputLabel for="file1" value="Select file" />
<t:inputFileUpload id="file1" value="#{myBean.uploadedFile}" required="true" />
<h:message for="file1" style="color: red;" />
<h:outputLabel for="file2" value="Select file" />
<t:inputFileUpload id="file2" value="#{myBean.uploadedFile}" required="false" />
<h:message for="file2" style="color: red;" />
<h:outputLabel for="file3" value="Select file" />
<t:inputFileUpload id="file3" value="#{myBean.uploadedFile}" required="false" />
<h:message for="file3" style="color: red;" />

<h:panelGroup />
<h:commandButton value="save" action="#{myBean.uploadFiles}" />
<h:message for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />
</h:panelGrid>
</h:form>
</h:body>
</html>

As you can see, the file would be dealing with a single backing bean property uploadedFile. You would tomahawk for the file upload one. There is also file upload in richfaces as well.

Now, let’s see what is the hood of MyBean.java. In the bean you would have to member variables for this purpose:

private List<UploadedFile> uploadedFiles;
private UploadedFile uploadedFile;

You can get the uploaded file from org.apache.myfaces.custom.fileupload.UploadedFile.
Then have a normal getter and setter for both.
The trick is in the setter of the uploadedFile:

public void setUploadedFile(UploadedFile uploadedFile){
this.uploadedFiles.add(uploadedFile);
}

When the file is requested, add it to the list of the uploadedFiles.
For the action which would would do the actual uploading of the file, I have used the snippet from http://balusc.blogspot.com/2008/02/uploading-files-with-jsf.html.

public String uploadFiles(){
for(UploadedFile uploadedFile : this.uploadedFiles){
if (uploadedFile !=null ){

// Prepare filename prefix and suffix for an unique filename in upload folder.
String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
String suffix = FilenameUtils.getExtension(uploadedFile.getName());

// Prepare file and outputstream.
File file = null;
OutputStream output = null;
try {
// Create file with unique name in upload folder and write to it.
file = File.createTempFile(prefix + "_", "." + suffix, new File("Your_Path"));
output = new FileOutputStream(file);
IOUtils.copy(uploadedFile.getInputStream(), output);

// Show succes message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
} catch (IOException e) {
// Cleanup.
if (file != null) file.delete();

// Show error message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));

// Always log stacktraces (with a real logger).
e.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
}
}
}
return "done";
}

 

webxml attribute is required error on maven build of war

This error appears mostly when Maven could not find the web.xml file. If you are following the default maven structure, make sure the webapp folder is named correctly – like not webapps or something like that.
Once you make sure, you can try by explicitly telling maven where the web.xml file is using

 
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
</configuration>
</plugin>

nosuchfielderror tokentypetoastclassmap Error in JPA

Did you come across this error while trying to access Hibernate query language like simple select?
The problem is mainly on the version of the antlr.jar
If you are not using Application server and putting all the jar by your self, check if you have added antlr-build.jar or some earlier version of that jar. Replace it and you should be fine.
Good luck.

An association from the table refers to an unmapped class Hibernate Exception

Got An association from the table

refers to an unmapped class exception while running hibernate on your app?
Here is a solution
Mostly it would be related to the hbm file of the table that it is complaining. On that hbm file, make sure if you have the class attribute on the option properly addressed like if you haven’t added the package on the top, make sure you provide the FQN of the class.

Also make sure if the hbm file is listed on the hibernate.cfg.xml/ where ever the list of the hbm files are listed.

Mostly this would solve the problem.

Using JSF form fields with jQuery – Can’t use jQuery with : (colon) problem

if you have a jsf page of the following

<h:body>
<h:form id="frmRegistration">
<h:panelGrid columns="2" rules="rows">
<h:outputLabel id="lblFirstName" value="First Name"  />
<h:inputText id="txtFirstName" value="#{memberRegisterBean.member.name}" label="First Name" required="true"/>
.
.
.

And say you want assign default value from javascript to the text box you would use:

    $("#frmRegistration:txtFirstName").val("this val");

Since that is how JSF would generate the id of the component
But, you wont see any effect as jQuery don’ like the generated colon (:).
use this instead> ‘escape it’

    $("#frmRegistration\:txtFirstName").val("this val");