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

Using SSH in Ubuntu

The idea behind using SSH (secure shell) falls when one is interested in sending files over the network in secure way. There are existing methods which will accomplish the task, but SSH is a cool one when one wants real security.
Here is the step to send files securely from your machine to the other.

1. install ssh client and ssh server using
sudo apt-get install openssh-client openssh-server

2. log into the server using the command
ssh username@server
where username is the user at the server. This can be checked on local machine as ssh user@localhost

3. Now we can share files using the tool scp
to upload file use:
scp path/to/file/to/upload user@server:/path/to/host/directory
Say, to upload the file test.txt from local machine to server named someserver.com into directory /home/remote, then
scp /home/user/test.txt user@someserver.com:/home/remote

And to download file from the same server to local machine
scp user@someserver.com:/home/remote/test.txt /home/user/downloads

This one required logging every time with subsequent request of password. To setup a secure file transfer without password the way to go would be using public private combination between server and client.
Logging to SSH Server without password
Generating and using public private key
1. Creating Public Private key can be done using:
ssh-keygen -t dsa – or if you want to make rsa: ssh-keygen -t rsa
2. it will prompt you to where to put the file and the passkey for the files. take default file path. This would allow the creation of id_dsa (private key) and id_dsa.pub (public key) into the ssh directory. -> The directory would be into /home/user/.ssh/. The private key would retain with the generating server while the public key would be uploaded to the server where you would create the connection.
3. Make sure the following are available and not commented in
/etc/ssh/ssh_config
IdentityFile ~/.ssh/identity
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_dsa
and from /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes

4. Make sure you have id_dsa, id_dsa.pub or rsa versions on .ssh folder
5. Copy the public key to the remote server using
scp /path/to/publickey user@server:/home/user/.ssh/ – where user is the authenticated user on the remote server
6. You will be asked for one last time your password for copying the file.
7. Log to remote server using your password
8. Navigate to /home/USER/.ssh
9. having the publicKey [it is the one you scp it, like id_rsa.pub or id_dsa.pub: cat publicKey >> authorized_keys
9. The file will now be added to the remote server’s authorized_keys. This will give you an access from your machine to the remote server without password – unless you want it to.

**
Make sure the file permission for authorized_keys is 600 and
for .ssh directory it is 700
**

reference:
http://www.techotopia.com/index.php/Configuring_Ubuntu_Linux_Remote_Access_using_SSH
http://outhereinthefield.wordpress.com/2007/10/31/passwordless-scp-authentication-for-unattendedbatch-process/
http://www.debuntu.org/ssh-key-based-authentication

403 Forbidden You don’t have permission to access .. on windows pc

You don’t have permission to access error

I was trying to access my PHP web project from my Vista on my Ubunut and end up running error 403 Forbidden You don’t have permission to access on this server …

Do you know how to find missing numbers from billing records – algorithm

Well this has a very easy remedy:

BTW – I am using Uniserver – http://www.uniformserver.com/ – [ Which is the coolest development environment on windows as you would get PHP, MySQL, and PhpMyAdmin residing all at one place.]

But it doesn’t matter if you are using other tool.

1. Go to where your www folder

2. open .htaccess file using your favorite text editor – note pad is more than enough for this.

3. Under Allow From 127.0.0.1 – or whatever it is allowed Add Allow From [your ip address of the computer from which you want to access the server]

Get started with nodejs and angularJS with this tutorial

How to configure php mysql and apache

Inserting data to table reading from another table in mysql

OK, we can use INSERT INTO statement to insert fresh data to mysql. But how about if the need lies on reading data from another table?
Here is how we do it in mysql.
Let us create the tables for illustration:
Log into your mysql and create the following queries
Creating database
CREATE database testdb;
USE testdb;

Creating tables

CREATE TABLE testtbl1 (id int(10) auto_increment, fname varchar(20), lname(20), primary key(id));
CREATE TABLE testtbl2 (id int(10) auto_increment, firstname varchar(20), lastname(20), age int, primary key(id));

Lets add some data to table 2 now
INSERT INTO testtbl2 (firstname, lastname, age)
VALUES
(‘ftest1’, ‘ftest1’, 35),
(‘ftest2, ‘ftest2’, 21),
(‘ftest3, ‘ftest3’, 25),
(‘ftest4’, ‘ftest4’, 38)

Now lets add data to the first table filtering persons with age less than 30

INSERT INTO testtbl1 (fname, lname) SELECT firstname, lastname FROM testtbl2 WHERE age <= 30;