Thursday, December 8, 2011

Using a Singleton

Below is an example of a Singleton used to decrement a counter variable:

package singleton;
public class Counter {
   private static Counter instance;
   private int count;


   private Counter() {
   }


   public static synchronized Counter getInstance() {
      if (instance == null) {
          instance = new Counter();
      }
      return instance;
   }


   public synchronized void decrement() {
       count--;
       if( count<0 ) {
          count=0;
       }
   }


   public synchronized int getCount() {
       return count;
   }


   public synchronized void setCount(int countValue) {
       count = countValue;
   }
}

Test class for the singleton above:

package singleton;

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

public class CounterTest {
    private Counter counter1 = null, counter2 = null;

    @Before
    public void setUp() throws Exception {
       counter1 = Counter.getInstance();
       counter2 = Counter.getInstance();
    }

    /**
     * Test case to ensure that the getInstance Method
     * returns a non null object and to ensure
     * that getting 2 instances of Counter results in
     * the same object being returned.
     */
    @Test
    public void testGetInstance() {
       counter1 = Counter.getInstance();
       assertNotNull(counter1);
       counter2 = Counter.getInstance();
       assertNotNull(counter2);
       assert (counter1 == counter2);
    }

    /**
     * Test case that tests decrementing the count variable and
     * also ensures that both counter1 and counter2
     * returns the same count value.
     */
    @Test
    public void testDecrement() {
       counter1.setCount(20); 
       counter1.decrement();
       assert (counter1.getCount() == 19);
       assert (counter2.getCount() == 19);
    }

    /**
     * Tests that both instances of the Count returns
     * the same count value.
     */
    @Test
    public void testGetCount() {
       int count1 = counter1.getCount();
       int count2 = counter2.getCount();
       assert (count1 == count2);
       counter2.setCount(100);
       count1 = counter1.getCount();
       assert (count1 == 100);
       count2 = counter2.getCount();
       assert (count1 == count2);
    }

   /**
    * Tests that we are allowed to set the count variable
    * and that another instance reading that variable will
    * result in the correct value being returned. */
    @Test
    public void testSetCount() {
       counter2.setCount(100);
       int count1 = counter1.getCount();
       assert (count1 == 100);
    }
}

Thursday, October 20, 2011

java.rmi.MarshalException: Failed to serialize Error

This error occurs when trying to invoke a Remote object that is not Serializable. You can fix this by making the object in question (if possible) Serializable by implementing java.io.Serializable.

Thursday, September 22, 2011

Converting from java.util.Date to XMLGregorianCalendar

If you need to convert from java.util.date to an XMLGregorianCalendar format you can use the following code:

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import java.util.GregorianCalendar;

public class DateConversion {
   public XMLGregorianCalendar dateToXMLGregorianCalendar(
   final java.util.Date date)
   throws DatatypeConfigurationException {
      DatatypeFactory df = DatatypeFactory.newInstance();
      if (date == null) {
         return null;
      } else {
         GregorianCalendar gc = new GregorianCalendar();
         gc.setTimeInMillis(date.getTime());
         return df.newXMLGregorianCalendar(gc);
      }
   }
}

Touch all files within the current directory

If you need to update all files within the current directory with the latest timestamp you can use the following command:
find . -type f -exec touch {} \;

Friday, August 19, 2011

Unmarshal an object using JAXB

The code below can be used to Unmarshal XML that comes in as a String value to an Object (Assuming that JAXB was used to create your classes from the Schema).

String theXMLString = " ... your XML saved as a String value ... ";
MyObject myObject = null;
try {
     //"mypackage" is the package where JAXB created the schema classes
    final JAXBContext jaxbContext = JAXBContext.newInstance("mypackage");
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    final ByteArrayInputStream byteStream = new        ByteArrayInputStream(theXMLString.getBytes());
    myObject = (MyObject) unmarshaller.unmarshal(byteStream);
} catch (JAXBException e) {
    System.out.println("An error has occurred: "+e.getMessage(), e);
}

Monday, July 25, 2011

"No runnable methods" error when doing a Maven install

When doing a maven install I kept getting a Build Failed with this error being generated when attempting to run the test cases:


java.lang.Exception: No runnable methods at
org.junit.internal.runners.TestClassMethodsRunner.testAborted



To solve this problem I first ran a maven clean:

$ mvn clean

and then ran the maven install

$ mvn install

Starting up HSQLDB

java -classpath [lib_path]/hsqldb.jar org.hsqldb.Server

Ctrl-C to kill the the Session

Sunday, July 10, 2011

Changing your windows drive on the command prompt

To change your drive from say C:/ to D:/ just do the following:

C:/>d:
D:/>

So all that is required is for you to type in "d:" and press Enter.

Tuesday, June 7, 2011

Oracle escaping the single quote(') in a select

This query will fail when doing a select statement:

select * from table_name where field='it's friday today';



To escape the single quote (') you need to add in another single quote (''):

select * from table_name where field='it''s friday today';

Wednesday, June 1, 2011

": No such file or directory" Error on Linux

If you have ever encounter these errors on a Linux server: ": No such file or directory" or ": command not found" when attempting to run a script it may actually be a problem with the format of the file i.e. it may be a dos file. You can convert the file from dos to Unix using the following command:



$ dos2unix filename

N.B. On Solaris you may get a different error i.e. "^M: does not exist". You can use the same functionality to convert the file to Unix format.

Tuesday, April 19, 2011

Failed shutdown of Apache Portable Runtime on Tomcat 5.5.26

This "error" isn't really an error but a warning that the Apache Portable Runtime (APR) has failed to shutdown. This message can be ignored if APR isn't installed on your server.

Click here is more info on APR.

These forum links give more information:
http://www.coderanch.com/t/85960/Tomcat/Tomcat-Native-library-not-found
http://www.mail-archive.com/users@tomcat.apache.org/msg04625.html

And this link has information here is how to stop the error/warning from appearing:

http://issues.liferay.com/browse/LPS-3166?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel

Using curl to simulate a handset request

Previously I indicated on how one could use wget to simulate a handset request. You can also use curl to achieve something similar:

curl -v -A"Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 Nokia6110Navigator/" -H"x-up-calling-line-id: xxxxxxxxxxx" http://www.google.com

The 'xxxxxxxxxxx' should be replaced with the user's mobile number.

Thursday, February 17, 2011

java.lang.ClassFormatError: Truncated class file

Recently I kept getting this error when I copied over my .class files onto a remote server and attempted to run my java class on the server. I was using WinSCP to copy the files onto the server and the copy kept getting corrupted when I sent it across to the server. I shutdown WinSCP and started the process again which solved the problem.

Sunday, February 6, 2011

Programming NPV on Sharp EL-5250

Here is an example of how you can program your Sharp EL-5250 programmable calculator to calculate the NPV value when given yearly cash inflows.

Print"INITIAL CASH FLOW
Input C
Print "NO. OF YRS
Input N
Print"INTEREST
Rem IF I=12% NEED TO INPUT AS 0.12
Input I
Rem TIME COUNTER
T=1
Rem KEEPS THE CURRENT VALUE
X=0
Label CHECK
If T<=N Goto NPV
If T>N Goto THEEND
Label NPV
Print"NEXT CASH FLOW
Input F
X=X+(F/(1+I)^T)
T=T+1
Goto CHECK
Label THEEND
Rem NEED TO SUBTRACT INITIAL CASH FLOW
X=X-C
Rem X IS NOW THE NPV
Print X
End

Friday, February 4, 2011

Using ANT to create javadocs

Here is a very simple example to create javadocs using ANT. The fields should be replaced with your own parameters e.g. packagename should be replaced by the name of the package that contains the classes that you want to create javadocs for.

<target name="document">
  <javadoc destdir="doc" author="true" version="true" use="true" windowtitle="My JavaDocs">
    <fileset dir="src" defaultexcludes="yes">
      <include name="packagename/**">
      </include>

      <classpath>
        <fileset dir="lib">
          <include name="**/*.jar">           </include>
        </fileset>
        <doctitle><!--[CDATA[<h1>Mobile Text Adverts</h1>]]--></doctitle>
        <bottom><!--[CDATA[<i>Copyright &#169; 2011 Company Name. All Rights Reserved.</i>]]--></bottom>
      </classpath>

    </fileset>
  </javadoc>
</target>

Wednesday, January 26, 2011

Oracle escaping the % in like

Just figured out how to escape the % when using like in an Oracle SQL query e.g. if I want to get all rows from a table where the URL field contains "%20" which is the space in a URL.
select * from table_name where URL like '%!%20%' escape '!'

This indicates that '!' is the escape character and you would like to find all URLs that contain '%20'.