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

Invocation of init method failed – hibernate exception of caching

While working with hibernate you might come up with this error, as I do :(
Fortunately, here is how to make your java happy:

On your hibernate.xml [ or maybe you might named it other ], there is a part describing property:

<property name="hibernateProperties">
 <props>
 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
 <prop key="hibernate.show_sql">true</prop>
 <prop key="hibernate.c3p0.minPoolSize">5</prop>
 <prop key="hibernate.c3p0.maxPoolSize">200</prop>
 <prop key="hibernate.c3p0.timeout">1800</prop>
 <prop key="hibernate.c3p0.max_statement">50</prop>
 <prop key="hibernate.generate_statistics">true</prop>
 <prop key="hibernate.cache.use_second_level_cache">true</prop>
 <prop key="hibernate.cache.use_query_cache">true</prop>
 <prop key="hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>
 </props>
 </property>

The last two props are the ones we want to blame!!
One way to get rid of this problem would be by just making the values of those to false – hmm… would work but we would miss the capability of caching … Here is the next

Download the ehcache from this location and put it in your classpath.
Update the hibernate.xml file’s property section by adding the following:

<prop key="hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>

Now you+java+hibernate+me HAPPY..
hope would help someone..

by pass invalid/self signed certificate in java/glassfish – linux

The following would be handy if one wants to by pass the self signed certificate in java – for app server glassfish.
1. Go to browser and paste the url on it. Let’s assume we are using https://www.sometestcert.com/thispage.asmx
2. On the page double click the lock image [ on firefox you can get it on the right bottom corner ]. Make sure you have https not http to get that lock thing

3. Assuming you are on firefox, goto security -> view certificate -> details-> and Click Export and save it as certificate.pem – choosing x.509 certificate with chain is a good one.
4. then add the key to the glassfish’s keystore.. – say on local machine the default location for key store would be
/usr/local/glassfish/domains/domain1/config.
5. Once you go to the appropriate directory, being on terminalcd , type the following.
keytool -import -alias “sometestcert.com” -keystore cacerts.jks -file /location/to/certificate.pem
6. This time it might ask you a password, if you have specific password for the cacerts then insert it, if not the default would be changeit
7. type yes when asked if you trust the site – of course :)

enjoy certicating..

Donwloading file from website automatically in java.

Imagine you want to download a file from a website in a binary format, where you have account [username, password]. Here is a java snippet that would allow you to do that.
In this case the snippet would specifically allow you to download a file in binary not in a text format.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class WebDownloader {

public static void main(String[] arg){
try {
// Construct data
File file = new File(“file/path/for/the/file/to/be/downloaded”);
FileOutputStream fos = new FileOutputStream(file);
String data = URLEncoder.encode(“”, “UTF-8”) + “=” + URLEncoder.encode(“ur”, “UTF-8”);
data += “&” + URLEncoder.encode(“”, “UTF-8”) + “=” + URLEncoder.encode(“”, “UTF-8”);
// Send data
URL url = new URL(“your/url/goes/here”);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data); wr.flush();
BufferedInputStream rd = new BufferedInputStream(conn.getInputStream());
int count;
byte[] byt = new byte[256];
do{
count = rd.read(byt);
if(count != -1)
fos.write(byt, 0, count);
}while(true);
wr.close();
rd.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(“downloaded”);
}
}

The above snippet is a very slight touch of the code snippet from exampledepot –

Mockito – cool mocking tool for Java

In a day to day TDD, one would happy in incorporating anything which would facilitate testing. Especially, on Object world, testing the interaction of objects on the method has been somehow rigorous.
Mockito is a handy tool in this regard. As the name suffice, it will mock objects and make them available for testing.
I will try to create a very simple situation where Mockito would show its power.
Let’s say we have an object named CityTemp – which would contain city and citie’s temperature. And let’s have another class named Forecast that would take CityTemp and would return simple string like city has high temperature or city has midium temperature or city has low temperature.

Say we want to test the Forecast part with different temperatures. The usual way would be instantiating CityTemp and filling it up with values. Unlike the usual way, Mockito has another approach.
Steps,
1. First download Mockito from Mockito site
2. Create a simple Java project and name it as you want.
3. Add the mockito jars to the project
4. Create the following two classes:
CityTemp

package mocklist;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 * 
 */
public interface ICityTemp {
	public String getCity();
	public void setCity(String city);
	public Double getTemperature();
	public void setTemperature(Double temperature);
}

package mocktest;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 * 
 */
public class CityTemp implements ICityTemp{
	private String city;
	private Double temperature;
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Double getTemperature() {
		return temperature;
	}
	public void setTemperature(Double temperature) {
		this.temperature = temperature;
	}
}

and
ForeCast

package mocktest;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 *
 */
public class Forecast {
	private ICityTemp cityTemp;
	public Forecast(){
		
	}
	public Forecast(ICityTemp cityTemp){
		this.cityTemp=cityTemp;
	}
	public ICityTemp getCityTemp() {
		return cityTemp;
	}
	public void setCityTemp(ICityTemp cityTemp) {
		this.cityTemp = cityTemp;
	}
	
	/**
	 * Checks city's temperature and creates some verbiage
	 * @return String 
	 */
	public String weatherForcast(){
		String forecast=null;
		if (this.getCityTemp()!=null){
			if(this.getCityTemp().getTemperature() > 80){
				forecast=this.getCityTemp().getCity() + " has higher temp";
			}
			else if(this.getCityTemp().getTemperature() > 50){
				forecast=this.getCityTemp().getCity() + " has medium temp";
			}
			else{
				forecast=this.getCityTemp().getCity() + " has lower temp";
			}
		}
		return forecast;
	}
}

5. Now, we wanted to create a simple test to check forecast’s method
6. Create a test case file/class as follows:

import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import junit.framework.TestCase;
import mocktest.Forecast;
import mocktest.ICityTemp;
import static org.mockito.Mockito.when;

public class Another extends TestCase{
1	//mock the cityTemp object. with this simple annotation
2	@Mock private ICityTemp cityTemp;
3	public Another(){
4		MockitoAnnotations.initMocks(this);
5	}
6	@Test
7	public void testMidiumTemperature(){
8		Forecast forcast = new Forecast(cityTemp);
9		String expectedResult = "Addis Ababa has medium temp";
10		when(cityTemp.getTemperature()).thenReturn(65.0);
11		when(cityTemp.getCity()).thenReturn("Addis Ababa");
12		String actualResult = forcast.WeatherForcast();
13		assertEquals(expectedResult, actualResult);
	}
}

Let’s examine our lines of interest, in the test part.
Line two would be the one which starts the magic, it will create a mocked object of CityTemp. Look we don’t need to instantiate the object – it is mocked and we have it to manipulate as we want it.
That line can also be written as: private ICityTemp cityTemp = Mockito.mock(ICityTemp.class); In that case we might not need the statement at line 4.
At line 8, we passed the mocked object to the Forecast constructor. As you can see we haven’t needed the implementation of the interface when we pass it as argument – the mocked is enough by itself.
Then line 10 and 11 are the hearts of the mocking. Mockito would assign values as you wish! thats cool.
Line 10 says, whenever the CityTemp object is asked for temperature then return 65.0. Since the logic inside Forecast depends on temp value of CityTemp, we can vary as much as we want and get different values.
The same talk for line 12. The rest is, of course, history ….
Go thru http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html and enjoy..

Starting Tomcatv6.0 Server at localhost has encoutered a problem, Port 80 required by Tomcat v6.0 server at localhost already in use. the server may already running in another process, or a system process may be using the port,To start this server you will need to stop the other process or change the port number(s)

While working with tomcat, you might come across this glitch. Here is how to get rid of it easily.

1. Go to server tab in your eclipse. If you cant see it you can have it through window->show view->servers
2. double click on the tomcat server and you will be directed to page for tomcat configuration.
3. On the page you will see list of ports that the current server is using.
4. Change the HTTP/1.1 from 80 – or whatever it is complaining to new one like 9181.
5. what… you’re done… :)

Happy TomCatting.

Adding Java Project to new Java web application on Eclipse

I just wanted to add my existing Java project to the current java web project and here is the simple step actually [of course from Eclipse :) ]

1. Right click on the web project and select Properties
2. Select J2EE Module Dependencies
3. Here either you can select the project which resides in the eclipse workspace or you can import additional external jars.
4. Apply OK
5. Right click web project and select Build Path -> configure
6. On the projects tab, select the project tab
7. Click Add and select the project that you would like to add
8. OK.
You are done! It is advisable if you clean your project and build a new one

To to do this:

Go to project -> clean and select your project
Select start a build immediately
Select build only the selected projects

After this reboot your Application Server – and enjoy with your imported project.