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

 

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

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";
}

 

Component ID id:compid has already been found in the view JSF error

This error is quite explanatory in JSF.

I got once in a while when I work with dynamic generation of the components.

If you have this, the most common cause of this error would be you are trying to attach the an html component from your bean again.

Especially, if you have session scoped managed bean and you are attaching dynamically elements, may be one of your methods has already attached the component to the view (like the grid you are using for your component) and the other method is trying to attach it again.

If that is the case you might need to check the existence of the component in the grid (or any component you are using) before attaching it.

Also: see how to add session bean to request

re-structre

Change default source directory src/java in eclipse for java project

Prepare directory structure for maven by changing the default src

Probably you are using maven and wanted to change the directory structure.

Since maven recommends the standard src/main/java src/main/resource you might want to change it that way

Here is how to do it in eclipse.

First create the folder structure on the project in which ever way you would want to do it. I would use simple command like mkdir folderName to create it.

1. right click on the project, and hit refresh, make sure the folders you created are listed there.

2. Right click on the project, select properties and select java build path

3. Go to source tab

4. select and remove the current source folder, by default it would be src folder

5. Hit the Add newthen select your folder structure there.

maven directory structure

maven directory structure

This would change the original structure of the your java project from src to the one maven compatible.

See how to use maven to create starter boilerplate application
Get started with step by step j2ee and maven tutorial using eclipse

Can you solve these cool algorithm problems? See their solution as well

How do you find the maximum consecutive sum from the given array

You are given billion numbers and to look for a couple of missing numbers

From list of numbers in array, find those that are complementary to the given number

JSF navigation error because of invalid path in faces config

javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:216)     at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:544)

A continuous and erratic error you would see on the console of this title might come across your JSF development once in a while.

Also you may see the browser is taking long while this error happens.

It has to do with navigation in the faces-config.xml file. in my case, I had forgotten to add the forward slash in front of my file – that is

   <navigation-case>
     <from-outcome>hint</from-outcome>
     <to-view-id>/index.jsp</to-view-id>
   </navigation-case>

The above is snippet from the faces-config.xml file. As you can see, the index.jsp file is without the forward slash – That was the problem

Happy JSFing.

java.lang.NoClassDefFoundError – javax/servlet/jsp/jstl/core/Config

A kind of friendly error that would bade a visit while working on JSF and Tomcat would be: java.lang.NoClassDefFoundError – javax/servlet/jsp/jstl/core/Config.

Thankfully, this has a very simple remedy of adding JSTL jars of standard.jar and jstl.jar.

You can get those jars from http://jakarta.apache.org/site/downloads/downloads_taglibs.html