Welcome to The TEK Blog

September 16th, 2010

Welcome to The TEK Blog.

Here you’ll find information on all of my Android Apps and (hopefully!) useful blog posts!

Enjoy.

Posted in Interesting Stuff! | Comments Off


Java reverse String functions

May 19th, 2012

I was recently asked in an interview to write a method in Java to how to reverse a String.

At the time I came up with the following solution;

public String reverseString(String s) {
		if (s == null) return "";
 
		char[] chArray = s.toCharArray();
		StringBuffer b = new StringBuffer(); 
		for (int i = s.length(); i > 0; i--) {
			b.append(chArray[i - 1]);
		}
		return b.toString();
	}

I was then asked to do the same recursively…

public String recurReverseString(String s){
	    if (s.length() == 0) 
	         return s;
 
	    return reverseString(s.substring(1)) + s.charAt(0);
	}

What occurred to me as I was writing these methods is that the simplest way by far is to use the StringBuffer reverse method!

	public String reverseStringUsingBuffer(String s) {
		StringBuffer b = new StringBuffer(s); 
		return b.reverse().toString();
	}

Posted in Development, Java | No Comments »


Date utilities methods for determining next business day

October 17th, 2011

Here’s a useful couple of data utilities methods which determine if a given date is before or after a certain day/time.

 
    private static final int CLOSING_TIME = 17;
 
  /**
     * This method will check if the supplied date (String) is today and if the time
     * is after a closing time to return true, else it will return false,
     *
     * @param currentDate String representing the current date
     * @return boolean: true if the date is today and the time is after 3pm
     */
   public static boolean isNextBusinessDay(Date date) {
        if (date == null) {
            return false;
        }
        return new Date().equals(date) && afterClosing();
    }
 
   /**
     * This method will return the current system date, set at CLOSING_TIME
     *
     * @return Calendar object set to today
     */
    private static Calendar todayClosing() {
        Calendar closingTime = Calendar.getInstance();
        closingTime.set(Calendar.HOUR_OF_DAY, CLOSING_TIME);
        closingTime.set(Calendar.MINUTE, TIME_MIN);
        closingTime.set(Calendar.SECOND, TIME_MIN);
        return closingTime;
    }
 
    /**
     *
     * @return boolean: true if the system time is post 3pm, else false
     */
    public static boolean afterClosing() {
        return Calendar.getInstance().after(todayClosing());
    }

Posted in Development, Java | No Comments »


IE8 caching AJAX requests

October 11th, 2011

We use jsonp to make AJAX requests to various web services written in Java. This was working with no problems what-so-ever on FF and Chrome, but we found that when testing on Internet Explorer 8 the responses were being cached. Even clearing the browser cache did not refresh the page correctly!

So we had two options; Change the server side code to include cache control headers with the response. Or change the client code when making the request.

1) Change the server side code; In Java you could do something like this;

     protected void populateNonCachingHeader(HttpServletResponse response) {
        response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Expires", "0");
    }

This will make absolutely certain that no caching is taken place for the request.

2) Change the client code; We are using a JQuery add on called jsonp to make the AJAX call. We changed our code to have the cache property to false. As per below;

 
  var jsonHref = "/my/rest/service/url";
        jQuery.jsonp({
            url: jsonHref,
            timeout: 30000,
            cache: false,
            error: function(xOptions, textStatus) {
                //something bad happened
            },
            success: function(data) {
                  //good response
                }
            }
        });

Problem solved!

We went for the client side version as in the end as the change was simpler and had less impact on our systems.

Posted in Development, Java, JavaScript, JQuery, Web | No Comments »


Firefox and Firebug latest versions

October 4th, 2011

The current release version of Firefox (7.0.1) may not be compatible with the some plugins including Firebug due to plugins having to declare which version of firefox they are compatible with. To resolve this, you can either use the latest beta version of firebug from getfirebug.com or disable the compatibility checking. As Firefox 4+ are based on similar code, the plugins tend to work fine despite not having been tested, I’ve tested most plugins with Aurora which was version 8.

To disable the compatibility check, use the following steps.

1. Navigate to about:config
2. Add a new boolean property with the name extensions.checkCompatibility.xx where xx is the version eg extensions.checkCompatibility.7.0 for the latest firefox
3. Ensure the boolean value is set to false.
4. Restart firefox and all plugins should be running.

Thanks goes to Johnny Chiv for this.

Posted in Browser, Development | No Comments »


IE 8 – Class Doesn’t Support Automation error

July 6th, 2011

Getting a “Class Doesn’t Support Automation” in IE8?

Check out this post

Saved one of my testers today.

Posted in Browser, Development | No Comments »


JQuery text which contains html

July 6th, 2011

In order to make sure a peice of text does not contains any html elements (such as < >) you can use the following JQuery function;

var UTIL = {
 convertTextToHtmlSafe: function (arg) {
        var text = $(arg).text(arg);
        if(text.length== 0){
            return arg;
        } else {
           return $(text).html();
        }
    }
};

Posted in Development, JavaScript, JQuery | 1 Comment »


IE8 window.open()

July 5th, 2011

The following code was giving my a ‘invalid agrument’ JavaScript exception in IE8.

   $('a.new_window').live('click', function(event) {
 
        var url = $(this).attr("href");
        var windowName = $(this).attr("name");
        var h = 750;
        var w = 1000;
        var left = (window.innerWidth) ? (window.innerWidth - w) / 2 : 0;
        var top = (window.innerHeight) ? (window.innerHeight - h) / 2 : 0;
        var windowSize = 'height=' + h + ',width=' + w + ',top=' + top + ',left=' + left + ',scrollbars=yes,resizable=yes,location=no';
 
        var newwindow = window.open(url, windowName, windowSize);
        if (window.focus) {
            newwindow.focus();
        }
        //make sure the current page does not also go to the url.
        event.preventDefault();
    });

The problem here is that that windowName that i’m passing has spaces!
The window name should be either one of the following options;
_blank
_media
_parent
_search
_self
_top

OR has a form of a valid identifier in JavaScript. So no spaces!

So whereas a ‘new window’ will work in firefox. In IE8 it needs to be ‘newwindow’.

Posted in Development, JavaScript | No Comments »


Hibernate performance (and OpenSessionInView)

July 4th, 2011

I’m currently looking at performance of our application and our use of Hibernate.

We’re currently using Spring 3 and Hibernate 3 and AOP for transaction control.

We open our sessions and transactions at the DAO layer. Which causes a few problems; one of the worst of which is that we always have to set lazy loading to false to be able to access collection from our service and controller layers. This means we’re querying the database for information that we may never use!
The application mainly performs data reads which greatly reduces the complexity required by our transactional and session management.

Our current session management also means we’re making no use of session level cache. (There’s a good guide on this here)

So first things first;
I’m going to change our session management strategy. After a bit of investigation it became quite evident using the open session in view design pattern was the way to go. So I’m going to start using the Spring OpenSessionInViewFilter filter in order to start a Hibernate session for each HTTP request.

This approach has pros and cons.
Pros;

  • Take advantage of Hibernate session cache.
  • Able to use lazy loading which is currently set to false on most of our collections. This should give a decent performance gain

Cons;

  • If you are using an OpenSessionInViewFilter, then you must use transactions for all data access, even just for readonly access.
  • Problems if an exception is throw when commiting – how do you recover?
  • Applying to existing code base could cause problems.

Implementing the open session in view pattern in Spring is pretty easy. All you need to do (presuming you have the necessary Spring libs etc) is add the following filter to your web.xml file.

<filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
    </filter>

and then an associated filter mapping;

    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

I’ve made a few assumptions here; mainly that you already have a lot of set up already done. (configuring session factories etc..)

Testing problems;
So the change to implement OpenSessionInView was really easy. But alias, all my service level integration tests are broken! LazyInitializationException all over the place.

So the solution to this is to change our AbstractStandaloneIntegrationTest which all our service integration tests extend to open and close a hibernate session before each test. Like so;

public abstract class AbstractStandaloneIntegrationTest {
    protected SessionFactory sessionFactory = null;
 
    protected AbstractStandaloneIntegrationTest() {
        super();
    }
 
    protected void onSetUp() throws Exception {
        Session session = SessionFactoryUtils.getSession(cdbSessionFactory, true);
        TransactionSynchronizationManager.bindResource(cdbSessionFactory, new SessionHolder(session));
    }
 
    protected void onTearDown() throws Exception {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(cdbSessionFactory);
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
 
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

My integration tests can now just extend this class and Hibernate sessions are created for each test. Just how they would be created using Spring.

This post is fantastic for explaining OpenSessionInView.

Posted in Development, Hibernate, Spring | No Comments »


JQuery popup example

June 29th, 2011

I’m going to quickly take you though how to create a popup window using JQuery. Original I used inline javascript for this which was a bit horrible. Using JQuery is much cleaner.
I’m going to presume you have knowledge of JavaScript and JQuery.

Below is part of my original code with the inline JavaScript. This is just part of the code we care about and obviously not a full page.
This is what I started with in my anchor tag;

<a onclick="javascript: openfullwindow('www.google.com','window')">Google</a>

Here we’re using an inline Javascript on the onclick event which calls the JavaScript ‘openfullwindow’ method below;

<script type="text/javascript">
function openfullwindow(url, name) {
        var settings= 'scrollbars=yes,resizable=yes,location=no';
        newwindow = window.open(url, name, settings);
        if (window.focus) {
            newwindow.focus()
        }
}
</script>

We’re going to remove the inline JavaScript defined on the anchor tag. Instead we have define a class ‘new_window’ which is going to be our ‘hook’ to be used by JQuery. This not only make the code look a lot neater, but is also standard compliant.

<a href="www.google.com" class=" new_window">Google</a>

Now use JQuerys ‘live’ method to look for click events on the any anchor elements with a ‘new_window’ class as per below.

$('a.new_window').live('click', function(event) {
 
        var url = $(this).attr("href");
        var windowName = $(this).attr("name");
        var h = 750;
        var w = 1000;
        var left = (window.innerWidth) ? (window.innerWidth - w) / 2 : 0;
        var top = (window.innerHeight) ? (window.innerHeight - h) / 2 : 0;
        var windowSize = 'height=' + h + ',width=' + w + ',top=' + top + ',left=' + left + ',scrollbars=yes,resizable=yes,location=no';
 
        //make sure the windowName does not have spaces! IE does not like it.
        var newwindow = window.open(url, windowName, windowSize);
        if (window.focus) {
              //Note IE6 hack! Must check to see if newwindow has been populated.
              if (newwindow) {
                    newwindow.focus();
              }
        }
        //make sure the current page does not also go to the url.
        //NOTE IE 6 hack here to check for preventDefault. Otherwise return false.
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
});

If we remove the event.preventDefault(); method call then the page that contains the link we also redirect to it, as well as the popup opening.

EDIT: I’ve updated the code above because of a problem in IE6. IE6 does not support the event.preventDefault and I was also getting errors when calling newwindow.focus.

Posted in Development, JavaScript, JQuery | No Comments »


Selenium Selection by class with mulitple classes

June 24th, 2011

We had some broken Selenium tests this morning which were caused by a extra class being added to a div element.

The Selenium test broke because the XPath expression was explicitly looking for a class which it failed to find because of the extra class added.

To make our Selenium tests more durable, have think about whether you need to add ‘starts-with’ or ‘contains’ selectors into your xPath expressions.

So for example;

This expression would fail for mulitple classes on the div element. ;
//div[@class='content_row']

To stop this occurring we can use the following xPath expression;
“//div[@class and contains(concat(' ',normalize-space(@class),' '),'content_row')]“;

Or (a little bit less flexible)

(//div[starts-with( normalize-space( @class ), 'content_row ')])

There’s a good blog post here about this

Posted in Development | No Comments »