Skip to content

Hello world!

Welcome to After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.

Apache Tutorial: Reverse Proxies

Apache Tutorial: Reverse Proxies

When designing my development environment, I needed to make sure that I could have access to it from almost any external environment. I’ve had to work on customer sites in the past that have all non standard ports locked down. This means that access into my VPN and remote desktop connections would be blocked in such instances, or even http access to services I have running from home on non standard ports (eg Confluence uses port 8090 out of the box). The way around this was to use reverse proxies.

A reverse proxy appears to the client just like an ordinary web server. The client makes requests for content, and then the reverse proxy decides where to send those requests, and returns the content as if it was the source. In essence, it is a load balancer that channels requests between the calling client, and the server and port dictated by the client call.

I decided on using Apache as my web server, and set virtual hosts to proxy the calls to the other servers. After installing Apache, I needed to enable two modules: proxy_http and rewrite:

sudo a2enmod proxy_http
sudo a2enmod rewrite

Proxy_http (or mod_proxy) enables the use of the reverse proxy capabilities, while rewrite allows URL rewriting. The rewrite module is not specifically needed for a reverse proxy, but I do use it to secure my traffic – more on this further down.

The proxy directives that are of interest are:

ProxyRequests – This allows or prevents Apache from functioning as a forward proxy server.
ProxyPreserveHost – This option will pass the Host: line from the incoming request to the proxied host, instead of the hostname specified in the ProxyPass line.
ProxyPass – Allows remote servers to be mapped into the space of the local server.
ProxyPassReverse – Lets Apache adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses. This is essential when Apache is used as a reverse proxy (or gateway) to avoid by-passing the reverse proxy because of HTTP redirects on the backend servers which stay behind the reverse proxy.

Because I am using standard ports to connect to my server from within other networks, I also wanted to make sure the traffic I was sending was encrypted. This is where the rewrite module comes in – it allows me to force a redirect of traffic from port 80 to 443.

So my final virtual host configuration became the following:

<VirtualHost *:80>
  RewriteEngine on
  ReWriteCond %{SERVER_PORT} !^443$
  RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
  ErrorLog /var/log/apache2/something.mysite.com_error.log
  CustomLog /var/log/apache2/something.mysite.com_access.log common

<VirtualHost *:443>
  SSLEngine on
  SSLCertificateFile /etc/apache2/ssl/apache.crt
  SSLCertificateKeyFile /etc/apache2/ssl/apache.key
  ProxyRequests Off
  ProxyPreserveHost On
  ProxyPass / http://123.456.789.012:1234/
  ProxyPassReverse / http://123.456.789.012:1234/
  ErrorLog /var/log/apache2/something.mysite.com_error.log
  CustomLog /var/log/apache2/something.mysite.com_access.log common

The first VirtualHost directive catches any traffic to on port 80, and uses the rewrite module to redirect it to port 443. The second VirtualHost catches any traffic to on port 443, uses my SSL certificate, and then forwards the traffic to the server of my choice (in this case my server at 123.456.789.012 on port 1234).

This way, I’m able to use standard web ports to access my severs in a secured way in an environment which may be otherwise restricted.

Useful Adobe AEM documentation Purging of Workflow Instances

Allow self-signed https certificate

private void ignoreSelfSignedCertificate() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                public void checkClientTrusted(
                        X509Certificate[] certs, String authType) {
                public void checkServerTrusted(
                        X509Certificate[] certs, String authType) {

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new;
    } catch (Exception e) {

Sample code to resize and crop image

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

public class ImageCropper {

    public static final int TARGET_WIDTH = 560;
    public static final int TARGET_HEIGHT = 168;

    public static void main(String[] args) {
        try {
            BufferedImage originalImage = File("C://exchange/mypic.jpg"));
            cropImageToGivenSize(originalImage, TARGET_WIDTH, TARGET_HEIGHT);
        } catch (IOException e) {

    private static void cropImageToGivenSize(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        System.out.println("Original Image Dimension: " + originalImage.getWidth() + "x" + originalImage.getHeight());

        float widthRatio = (float)originalImage.getWidth() / targetWidth;
        float heightRatio =(float)originalImage.getHeight() / targetHeight;

        BufferedImage resizedImage = originalImage;
        int resizedWidth = originalImage.getWidth();
        int resizedHeight = originalImage.getHeight();
        if(widthRatio > heightRatio){ //shrink to fixed height
            resizedWidth = Math.round(originalImage.getWidth() / heightRatio);
            resizedHeight = targetHeight;
        }else{ //shrink to fixed width
            resizedWidth = targetWidth;
            resizedHeight = Math.round(originalImage.getHeight() / widthRatio);
        resizedImage = resizeImage(originalImage, originalImage.getType(), resizedWidth, resizedHeight);

        int startX = resizedWidth/2 - targetWidth/2;
        int startY = resizedHeight/2 - targetHeight/2;
        BufferedImage SubImage = resizedImage.getSubimage(startX, startY, targetWidth, targetHeight);
        System.out.println("Cropped Image Dimension: " + SubImage.getWidth() + "x" + SubImage.getHeight());

        File outputfile = new File("C://exchange/test_after_crop_2.jpg");
        ImageIO.write(SubImage, "jpg", outputfile);

        System.out.println("Image cropped successfully: "+outputfile.getPath());

    private static BufferedImage resizeImage(BufferedImage originalImage, int type,
                                             Integer img_width, Integer img_height)
        BufferedImage resizedImage = new BufferedImage(img_width, img_height, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, img_width, img_height, null);

        return resizedImage;


For decades golf is declared to be “the hardest sport on the planet” and a lot of people skipped it simply because of that saying. Other lot tried to play once on a golf range and gave up because they couldn’t hit the ball easily. It is true that golf is not a sport that you can pick up and enjoy playing in a few hours or days, but on the other hand it is not as hard as it looks at first glance. I am a normal person who has played various sports (football, basketball, tennis, swimming, badminton, skiing, pool, bowling to name a few… and of course golf) in my life but like most people I’m not at professional level in any of them, yet it took me less than 2 years to really enjoy playing golf on the 18 hole course. Believe me – if I can do that most people can. And the more I play golf the more addicted I become to the sport:

* It is probably the only commonly played sport (I am not talking about those extreme sports like hill-climbing, diving or yachting for example) that you’re truly only against yourself out there. If you prefer you can completely ignore your golf buddy and only focus on yourself, in fact I prefer playing by myself from time to time so that I can focus on improving my skills.

* It is a sport that can be played by all genders within the widest possible age gap. Take a look at a professional golf game you’ll be amazed how much age difference it is between the oldest and youngest player on the field, and the different size/shape the players are! Yet they all have a fair chance to win the game. – This isn’t common at all in other athletic sports whereas certain size and shape are in advantage and normally younger people are in their prime.

* But that doesn’t mean golf is not a physically challenging game. On the contrary it is in fact a sport that can exercise your whole body – start from driving the ball at tee off, as your ball becomes nearer and nearer (hopefully) to the hole, you choose shorter golf clubs as you move along and change your body gesture and swing accordingly.. by the time your ball is inside the hole I bet you’ve exercised most of your body’s muscles. It is simply the best exercise you can do for a very long period of your life.

* It is also a mentally challenging game that requires extreme perseverance and consistency. Through the 18 holes’ play it teaches you a real-life lesson that bad things can happen at any time, that if that happens the best way to handle the bad is to forget about it quickly and concentrate on what’s happening next, and eventually if you’re brave enough to hold on until the end any miracle can happen at the last minute and you’ll be rewarded handsomely.

If you are itchy to pick up the hobby of your life time but have been put off by the seemingly steep learning curve, my book is here to help you get pass that painful process as quickly as possible (with my personal experience of picking up the game with zero experience – as a normal human-being :P). I hope we can achieve that in 8 weeks’ time together and let’s see if that’ll work out for you!

Easy way to figure out the location of a file in the JAVA classpath file = new"yourfileName"); 
String path = file.getAbsolutePath();

Inject and test JAVA method(or function) local variables with PowerMockito to make JUnit tests more

Ever had the situation when you really want to control the values of some of the local variables of the method you’re testing? Or want to assert the values of a JAVA method’s local variables that’s not returned (exposed) to the outside world? … Well, I just discovered this week that it’s all possible with the PowerMockito library.  Here attaches an example code snippet I wrote for my work. In the JUnit test( I forced the java “new Date()” call to always return day ‘0’ (1970-01-01) and verified the json object(also a local variable to the logUpdate method) has the eventTimestamp populated as expected – all thanks to the magic PowerMockito library 🙂

Date eventTimeStamp = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
JSONObject auditRow = new JSONObject();
auditRow.put("eventTimestamp", df.format(eventTimeStamp));
String input = auditRow.toString();

//Manipulate method's local variable values
Date mockDate = new Date(0); //Thu Jan 01 01:00:00 GMT 1970

//Hijack the method's local variable for testings
JSONObject injectedAuditObject = new JSONObject();