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..

PHP is displaying questionmark (???) for unicode

One of the fun things in php-mysql is working with Unicode characters. It is so cooked that, we should almost eat those with a little bit adjustment.
I am not going to tutor on how to use php-mysql unicode stuff – there are a bunch of ’em out there.
Rather I would discuss an error that would be common while doing your stuff..
Once you configure everything and put your unicode to mysql, you might see the output of it being questionmark on the browser – but you see the correct unicode in the database through the phpmyadmin.. it is this single line of code you would ever need…
mysql_query(“SET NAMES ‘utf8′”, conn); where the conn is the result of your connection – mysql_connect();
You can modify it accordingly, for example I am using an object oriented one so I can issue the query from my object – you would need to do this only once.

Happy unicoding..

Cannot find .frm file – mysql error

Especially when you move mysql from Window [see related] to Linux using the data file copy, you might face such and error telling you one of your table’s .frm file is not found.
In this case either of the two can solve the problem.
1. be aware that the .frm, for that matter both MDI and MYI files are case sensitive to linux – as it is for all files. So, if on windows you have test.frm and your application access them as TesT.frm, you may not have problem, but it is a major one on Linux.
2. The other is group and ownership issue, make sure the files are under mysql on both ownership and group – unless you have other configuration for that.

TO change ownership use
sudo chmod -R mysql /path/to/data/files
and for group

sudo chgrp -R mysql /path/to/data/files

Hope it would help somebody.

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 –

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

A connection attempt failed error

It looks on windows php5.3 has some kind of confusion on localhost :)

I have been using the earlier version without any problem and the moment I update to the newer version.

I got error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

As a remedy, just change the localhost with 127.0.0.1 and it will work like a charm…

Prev –

mysql_connect('localhost', 'root', 'root'); 

To

mysql_connect('127.0.0.1', 'root', 'root'); 

Click here to See how you can upgrade mysql

While you are here, I would recommend for you:

Do you know how to add scroll bar to mysql terminal?

How I setup LAMP on AWS step by step

Learn nodeJs with AngularJS in a complete project step by step

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.

Fatal error: Using $this when not in object context in PHP

Whenever you got this error check the following:

1. Make sure the $this-> is used inside the object and referring to the class’s and inherited non-static members.

2. Make sure the called members of the object are properly addressed as static or member/function variables

Do you know the different different post types?

Here is an example for the second one.

Assume you have the following object


class Example
{
   function getExampleText()
   {
      return "Example Text";
   }
   static function getStaticExampleText()
   {
      return "Static Example Text";
   }
}

While accessing, if the code tries something like this one,

$example = new Example();
Example::getExampleText(); //Trying to access non-static as static

Then you would have the error

Hidden Frame Pattern / Pre-Ajax

This is one of the knows patterns in the web devs. The idea would be having two – or possibly more – frames and making one the front one for interaction while would be HIDDEN.
Why Hidden?
The visible frame would pass make a request to the hidden frame to make the server side interaction behalf of it. Doing so would make the visible frame to remain loaded. The hidden would play the rest of the game by consulting the server and grabbing all the required data. Of course, how do they talk? well, Mr. Javascript will be the ‘man in the middle’ – don’t wanna mention the security flaw known by this name 😉

Let’s see a quick example: the example will show how to interact with the server side script without page reload. For demo purpose, A page will accept first name and last name and will display the concatenated full name. Though the logic done is is too easy to accomplish, one has to bear in mind that any complex logic can be done in the same way.

First create a simple index file containing the frames

<html>
	<head><title>Lab01</title>
		<frameset rows="100%, 0" style="border: 0px">
			<frame name="visibleframe" src="enterName.html" noresize="noresize"></frame>
			<frame name="hiddenframe" src="about:blank" noresize="noresize"></frame>
		</frameset>
	</head>
</html>

Making the frameset row 100% will assure the full visibility.
Then have the page for first and last name.
enterName.html.


<script>
	//get full name by delegating the task to the php 
	function getFullName(){
		var firstName = document.getElementById("txtFirstName").value;
		var lastName = document.getElementById("txtLastName").value;
		top.frames["hiddenframe"].location = "concateName.php?firstName="+firstName+"&lastName="+lastName;
	}
	//display it on the front page 
	function showFullName(fullName){
		showdiv = document.getElementById("fullName");
		showdiv.innerHTML = fullName;
	}
</script>
Your First Name <input type="text" id = "txtFirstName" name="txtFirstName" /> <br>
YOur Last Name<input type="text" id="txtLastName" name="txtLastName" /> <br>

<input type="submit" name="subGetFullName" value = "concate" onClick="getFullName();" /> <br>
<textArea id="fullName" name="fullName"></textArea>

This file contains two javascripts: one for sending the form values to the hidden frame and the other to accept and display the result from the hidden frame.
Since the hidden frame had no source initially, the getFullName() function would be responsible for assigning the file to it.

Now lets build the server side script which will combine and return the full name
concateName.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head><title></title>
    <script>
    window.onload = function(){
       var fullNameDiv = document.getElementById("fullName");
       top.frames["visibleframe"].showFullName(fullNameDiv.innerHTML);
    };
    </script>
    <?php
        $firstName = $_GET['firstName'];
        $lastName = $_GET['lastName'];
        $fullName = $firstName . $lastName;
    ?>
    </head>
        <body><div id="fullName"><?php echo "FULL name is " . $fullName ?>
        </div></body>
</html>

Now we are done. :)
The concateName.php would get the parameters from the enterName.html through hiddenframe. Once it access the values, it will concatenate them and will deploy the result in the “fullName” div.
The defined window.onload would wait until things are in place and it will fire the result back to the “visibleframe” through javascript.
Now – the user has no what is going on behind he scene – as she will not see the page being reloaded on refreshed.

reference: Professional Ajax 2nd edition Wrox