Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, January 10, 2013

"No runnable methods" when using Maven for a class that shouldn't be Tested

I recently ran into a problem doing a Maven build where I had a utility class to be used for my Test cases. Adding the @Ignore tag didn't seem to help. It turns out the solution was simply to add this plugin entry to my pom.xml file as my file had the suffix Util.java:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <configuration>
      <excludes>
         <exclude>**/*Util.java</exclude>
      </excludes>
   </configuration>
</plugin>

Tuesday, October 9, 2012

ClassNotFoundException: org.hibernate.hql.ast.HqlToken

When using Hibernate to read from a Database using Weblogic 10 and Springframework 2.5.6, I encountered the following error:

ClassNotFoundException: org.hibernate.hql.ast.HqlToken

The reason for this is that it by default will use Weblogic's default classloader to load the antlr jar file and doesn't use the version included within your .war file.

To solve this you need to wrap your .war in an ear file and within the META-INF/weblogic-application.xml file within you .ear file include the following:
 <prefer-application-packages>
    <package-name>antlr.*</package>
 </prefer-application-packages>
 

This should resolve this issue.


Monday, July 30, 2012

Java Pitfalls Book


This book "Java™ Puzzlers: Traps, Pitfalls, and Corner Cases" gives insight into some Java "fails" that one needs to watch out for when developing.

It explains what is wrong with this piece of code (It doesn't print out AB as one would expect):

public class PrintingSomeLetters {
  public static void main(String[] args) {
    System.out.println('A' + 'B');
  }
}

Tuesday, May 15, 2012

Java 5 autoboxing fail on equality check

  Double d1 = 25d;
  Double d2 = 25d;

  if (d1 == d2) {
            System.out.println("equal (==)");
  } else if (d1.equals(d2)) {
            System.out.println("equal (using equals() method)");
  }

The output is:
equal (using equals() method)

Thursday, March 8, 2012

Configuring maven to autogenerate Serializable JAXB classes

 First you need to create a bindings file:

<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<jxb:globalBindings>
  <jxb:serializable uid="1"/>
</jxb:globalBindings>

</jxb:bindings>
Save this file under "src/main/resources/" of your maven module. You can name it whatever you want e.g. jaxb-bindings.xjb.

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <executions>
    <execution>
      <id>Request</id>
      <goals>
      <goal>generate</goal>
      </goals>
      <configuration>
      <schemaDirectory>src/main/resources/xsd</schemaDirectory>
      <schemaIncludes>
      <include>*/*.xsd</include>
      </schemaIncludes>
      <generatePackage>mygeneratedfiles</generatePackage>
      <generateDirectory>src/main/java</generateDirectory>
      <bindingDirectory>src/main/resources</bindingDirectory>
      <bindingIncludes>
      <bindingInclude>jaxb-bindings.xjb</bindingInclude>
      </bindingIncludes>
      </configuration>
    </execution>
  </executions>
</plugin>

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);
      }
   }
}

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

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.

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 28, 2009

Going through a file line by line in java

BufferedReader inFile = new BufferedReader("filename");
String line = null;
try {
   while ((line=inFile.readLine())!=null) {
      //do something with the line here
   }
}
catch (IOException ioe) {
   ioe.printStackTrace();
}

Monday, January 26, 2009

Converting a java.util.Date object into a java.sql.Date object


public class ConvertDate {
   public java.sql.Date convertDate(java.util.Date date) {
      return new java.sql.Date(date. getTime() );
   }
}

Sunday, September 28, 2008

Getting a single DB connection in Java

Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@[ip_address]:[port]:[SID]", "[username]", "[password]");

Monday, September 22, 2008

Running Unix Commands from java

Runtime rtime = Runtime.getRuntime();
Process child = rtime.exec(new String[] {"/bin/sh","-c","sh myScript.sh"});
child.waitFor();
int return_code = child.exitValue();