Archives for category: Code

In a project that I’m working on we’re using linked sources and we have multiple sub-packages with JUnit tests. We ran into some issues with running the test. Thankfully, although the eclipse wizards wouldn’t help us create a test suite that would run all the tests it was trivial to write the suite by hand.

It can look like this:

    package tests;
 
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    import org.junit.runners.Suite.SuiteClasses;
 
    import tests.message.ATest;
    import tests.validator.BTest;
    import tests.validator.CTest;
    import tests.validator.DTest;
 
    @RunWith(Suite.class)
    @SuiteClasses({ ATest.class, 
    		BTest.class, 
    		CTest.class, 
    		DTest.class })
    public class AllTests {
 
    }

This will allow you to test any class that you import no matter what package it is in. To run this in eclipse you just right click the AllTests class and run it as JUnit test. It will then run all the tests you define in `@SuiteClasses`.

This will work with linked sources as well, I use it all the time.

So the other day I was struggling with sending a JSON object to a server. The JSON service would not accept this special object over HTTP so I had do dig into some Socket handling to send it. Of course, we could use Netcat to send the object like this:
echo '{"id":1, "method":"object.deleteAll", "params":["myParam"]}' | nc x.x.x.x 3994

But since the application I was working on needed to run some tests on creating and deleting stuff from the server we really needed a Java method to do this for us.

Here’s the code:

public boolean reset() {
	DataInputStream is;
	DataOutputStream os;
	boolean result = true;
	String noReset = "Could not reset.";
	String reset = "The server has been reset.";
 
	try {
		Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994);
		String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";
		is = new DataInputStream(socket.getInputStream());
		os = new DataOutputStream(socket.getOutputStream());
		PrintWriter pw = new PrintWriter(os);
		pw.println(string);
		pw.flush();
 
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		JSONObject json = new JSONObject(in.readLine());
		if(!json.has("result")) {
			System.out.println(noReset);
			result = false;
		}
		is.close();
		os.close();
 
	} catch (IOException e) {
		result = false;
		System.out.println(noReset);
		e.printStackTrace();			
	} catch (JSONException e) {
		result = false;
		System.out.println(noReset);
		e.printStackTrace();
	}
	System.out.println(reset);
	return result;
}

Creating the Socket is straight forward, the most noteworthy thing here the Writer that is being used. I tried with so many different Writers that I forgot what they all where called. Also note that the PrintWriter.println() method is used rather then the PrintWrite.print() method.

First let me state one thing: DO NOT USE THIS IN A PRODUCTION ENVIRONMENT… EVER!

There are cases though, when you are developing an application, debugging an application or just playing around, that you will need to deal with CertificateExceptions, SSLExceptions and other protection mechanisms that have been put in place for security. This most often occurs when some server admin has generated a self-signed certificate and sent you an IP-address to use for connecting. The certificate will most likely lack correct information such as subject alternative name, common name etc.

If these issues occur, of course you should contact the server admin and have him/her generate a proper certificate. Sometimes though, there is not enough time or good will from the admin side and you have to take extreme measures.

First thing you need to do is make sure you have the Apache HTTP Client library installed.

Then you can create the following class that will create a special SSLSocket that will accept any certificate:

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.http.conn.ssl.SSLSocketFactory;
 
/**
 * Creates an insecure SSL socket that trusts any certificate.
 * 
 * DO NOT USE IN PRODUCTION ENVIRONMENT!
 *
 */
public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");
 
    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);
 
        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
 
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
 
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
 
        sslContext.init(null, new TrustManager[] { tm }, null);
    }
 
    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }
 
    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

Then in your class that will be calling the HTTPS URL you can have the following method that will create a new “special” HTTP client:

/**
 * Sets up a client that will accept any certificate.
 * 
 * DO NOT USE IN PRODUCTION ENVIRONMENT!
 * 
 * @return the insecure client
 */
private HttpClient getNewHttpClient() {
	try {
		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		trustStore.load(null, null);
		MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
		sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
 
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", sf, 443));
 
		ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
		return new DefaultHttpClient(ccm, params);
	} catch (Exception e) {
		return new DefaultHttpClient();
	}
}

Now that you have an INSECURE HTTP client you can finally make a request. In this example a connection is made to “jsonURL” and fetches some JSON object:

/**
 * Reads JSON from the given URL
 * @param url
 * @return the JSON at the URL
 * @throws IOException
 * @throws JSONException
 */
private JSONObject readJsonFromUrl() throws IOException, JSONException {
	HttpClient httpClient = getNewHttpClient();
	String jsonText = getJson(httpClient);
	JSONObject json = new JSONObject(jsonText);
	return json;
}
 
/**
 * Creates an HTTP(S) request and writes the data to a String
 * of JSON.
 * @param httpClient the http client to use
 * @return a string of JSON
 */
private String getJson(HttpClient httpClient) {
	StringBuilder sb = new StringBuilder();
	try {
		HttpGet getRequest = new HttpGet(jsonURL);
		getRequest.addHeader("accept", "application/json");
 
		HttpResponse response = httpClient.execute(getRequest);
 
		String output;
		BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
		while ((output = br.readLine()) != null) {
			sb.append(output);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
 
	httpClient.getConnectionManager().shutdown();
	return sb.toString();
}

Heikki Hokkanen is the author behind the awesome tool GitStats. It is widely used all over the world to bring out some readable statistics from a git repository. Of course it is possible to get some nice command line output but there is nothing like a couple of bar charts and line charts.

The CSS-design of the tool is not the most updated to suit the modern day demands from bosses and customers so if you want to show off some stats you might want to try out my modified version of the tool. I take no credit on the tool what so ever, I’ve only spent a little time re-doing som CSS. I am not completely finished with the work yet since some of the styles are being set in the script that generates the html from the git repos.

I will post again once it’s finished until then you can at least give it a try and post some feedback over on GitHub!

 

If you don’t like graphics with more then 8-bit color space and you love the terminal, don’t worry. I have something for you as well. Add the following codes to your ~/.gitconfig file and you will be seing colors all over the place when running the commands git lg/lg2


[alias]
lg = log --graph --all --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(bold white)— %an%C(reset)' --abbrev-commit

lg2 = log --graph --all --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(bold white)— %an%C(reset)%C(bold yellow)%d%C(reset)' --abbrev-commit --date=relative

In my last project I was spending a lot of time looking at charting/graphing libraries for Android. I finally found the awesome AChartEngine but found it very hard to get a simple example working. So here is now a small PieChart example which hopefully can get you started! This example shows a pie chart with income, costs and the difference in a “sub total” sum.

Here’s a quick how to:

  • Extend GraphicalView (class in AChartEngine)
  • Create a getNewInstance method that returns the current class using a custom Renderer and DataSet
  • Create a custom Renderer (defines colors and labels for the chart)
  • Create a custom DataSet (the data maps to the colors you give in the renderer)
  • Profit!

To use this awesome PieChart you’ve now created you need to create a Layout in your xml which you can add the instance to.

Read the rest of this entry »

So when I was writing my Recept Keeper application i used a TabHost thinking it would have easy access animations and gestures for sliding. Turned out I was wrong and if targeting Android 4 or higher I could have used a PageView/Flipper.

I did however write a custom OnTabChangeListener that which has animations and gestures baked into it. Hope you can find some use of it in your TabHost!

Read the rest of this entry »

After lots of trouble and searching for Linux drivers to get the printserver in the Synology DS209 to work properly I had given up on wireless printing at home. Being bored tonight though, I got into my hea to give it another try since I had a Diskstation Manager update for my NAS.

After the update I figured what the heck, lets see if they’ve added some more options that I can tweak and what do you know, there was!

So, to get this working I:

  1. Plugged printer USB into the DS209
  2. Open the external devices in the Diskstation Manager
  3. Mark the printer in the list and click Usb printer manager -> setup printer
  4. Use Network MFP (this wasn’t here when I last tried!)
  5. I enabled AirPrint (Haven’t seen this before either!)
  6. Setup Brand to HP and Driver to HP Photosmart 7150
  7. Add printer and install any needed drivers on computer
  8. Done!

The 5280 still isn’t officially supported it seems but now I’m printing from both my Mac, Hack and Windows machines without problems. Next fight is scanning :)

Been getting into Java more and more lately and JavaDoc must be the most horrific leftover from the 90′s web with purple/black/times new roman styling. Not only is it unreadable due lack of margins, line-heights and smooth contrasts. It is also butt-ugly.

My favourite plugin for Chrome came to the rescue though. “Personalized Web” makes it so easy to add custom CSS to any site you want. So grab the plugin from Chrome app store and get the CSS from Sensemaya.

One of Swedens major newspaper websites got a redesign today and man, they have been working hard! They have managed to put aside all the web typography rules we all are started to take for granted. Things like vertical rhythm, 1.5em’s line-height for readability and lots of white space that allows the user to scan for content no longer exists. Instead it’s packed with what I’m sure is great print-design which makes the site unreadable and unusable, at least for me.

Lucky though that I found this Chrome plugin called “Personalized Web” that allows you to add custom CSS. I’ve used this before to get around Facebook’s silliness with the right sidebar.

Here’s the CSS for my dn.se and facebook.com that I’ve adjusted to my liking:

DN

body p, p, #main .teaser p {
line-height: 1.5em;
}
h2 a,
h3 a,
#article-content h1{
font-weight: normal;
font-size: 24px;
font-family: georgia;
line-height: 30px;
}
#main .teaser p {
font-size: 1.3em;
}
div#shortnews-wrap {
display:none;
}
body div#mid .teaser .teaser-container-inner h3 {
color: #666;
background: #DEDEDE;
}
#blogspace p, #mid .box-quote p, #mid .teaser .box-quote p {
font-family: arial;
font-size: 12px;
line-height: 18px;
}
#submenu-ad {
display: none;
}
 
#main .preamble p {
font-size: 1.4em;
line-height: 1.5em;
}
 
#main .content-paragraphs p {
font-size: 1.3em;
line-height: 1.5em;
}

Facebook

#pagelet_sidebar {display:none;}
#right {display:none;}
#siderbar-right {display:none}

After spending several hours the other day working on the endless adaption of Internet Explorer 6 for a Drupal project, and wondering why the styles in the conditional stylesheet I had added weren’t being applied, I stumbled on a small note that IE for some reason limits the number of linked stylesheets to 30 before it stops rendering. This causes the styles in any additional stylesheets to not be applied although the stylesheet is in the code. This seems like another stupid limitation in the painfully crappy (yes, it’s a pro term) IE series of browsers.

Read the rest of this entry »