Java Generics – conditionally instantiate a class

From Class to list of Enums

public static <T extends Enum> List<T> getList(Class<T> clazz) {
    return Arrays.asList(clazz.getEnumConstants());
}

So if I want to instantiate a class via some condition, I can do the following but still how do I know what type to use?

public class Foo {
	public String getName() {
		return "hi";
	}
}
public class Foo2013 extends Foo {
	public String getAge() {
		return "age";
	}
}
public class FooFactory {
	@SuppressWarnings("unchecked") // what do I need to do to not having to use this??
	public static <F extends Foo> F getFoo(int year) {
		try {
			if (year >= 2013) {
				return (F) Foo2013.class.newInstance();
			} else {
				return (F) Foo.class.newInstance();
			}
		} catch (InstantiationException e) {
			// TODO
		} catch (IllegalAccessException e) {
			// TODO
		}
		return null;
	}
}
public class FooFactoryTest {
	@Test
	public void testFooFactory() {
		Foo foo = FooFactory.getFoo(2011);
		Assert.assertEquals(Foo.class, foo.getClass());

		Foo foo2013 = FooFactory.getFoo(2013);  // <-- how can I do Foo2013 foo2013 without repeating the logic?
//		foo2013.getAge();
		Assert.assertEquals(Foo2013.class, foo2013.getClass());
	}
}

https://github.com/dodozhang21/JavaGenerics

Java concurrency – Multiple queue monitors

At work, I’ve implemented a queue monitor batch application. Due to business rule changes, it now needs to monitor two queues. Instead of creating another batch application, I really wanted to stick with the same application but just create two threads, each monitoring its own queue.

However, the twist I need is to have the main batch application thread die as soon as either queue monitoring thread dies.

I’ve been searching for a graceful way to handle such a concurrency need in Java. Thank you to Gary Myers, I’ve got a great start on it.

The basic idea is to pass a java blocking queue to both of the threads and if either thread fails, do blockingQueue.offer to indicate so. Then in the main thread, it will check for the blocking queue’s result. blockingQueue.take() blocks/waits for it to return and then continues the execution of the main thread.

Things I learned that made today AMAZING!

  • Put repositories in the pom.xml instead of settings.xml for maven to look through multiple repositories
  • Use SynchronousQueue to ensure only 1 element at a time may exist in the queue
  • Use daemon to make sure the JVM will die even if there is a thread running
  • You can EMBED ActiveMQ using spring so you don’t have install it at all

Below is a simple concurrency example that demonstrates the idea from Gary Myers.

Worker:

public class Worker implements Runnable {
   private BlockingQueue<String> finishedQueue;
   private String result;
   private long sleepTime;
   
   public Worker(BlockingQueue<String> finishedQueue, String result, long sleepTime) {
      this.finishedQueue=finishedQueue;
      this.result=result;
      this.sleepTime=sleepTime;
   }
   
   public void run() {
      try {
         TimeUnit.SECONDS.sleep(sleepTime);
         finishedQueue.offer(result); //you have to use offer to get this queue to work.  It will throw an exception if there is something in the queue.
      } catch(InterruptedException e) {
         e.printStackTrace();
      }
   }
}

DaemonThreadFactory:

public class DaemonThreadFactory implements ThreadFactory {
   private AtomicInteger counter;
   
   public DaemonThreadFactory() {
      this.counter=new AtomicInteger(0);
   }
   
   public Thread newThread(Runnable r) {
      Thread thread=new Thread(r);
      
      //if you wanted you can make this class generic by having the constructor take arguments that can be used to configure the following
      thread.setDaemon(true); //need it to be daemon so the JVM will die even if there is a thread running
      thread.setName("Daemon Thread: " + counter.incrementAndGet()); //you don't have to give it a name, but I always do.
      
      return thread;
   }
}

Test the threads in a simple example:

public class Main {
   public static void main(String[] args) throws InterruptedException {
      ExecutorService service=Executors.newFixedThreadPool(2, new DaemonThreadFactory());
      SynchronousQueue<String> queue=new SynchronousQueue<String>(); //this queue can hold 1 element at a time, so basically the first thread to finish will be the one to successfully put the element in the queue
      //create the runnables before hand so that extra time isn't spent instantiating the runnables at submission time.
      Runnable runnable1=new Worker(queue, "Runnable 1", 4);
      Runnable runnable2=new Worker(queue, "Runnable 2", 3);
      
      service.execute(runnable1);
      service.execute(runnable2);
      
      System.out.println("before queue");
      System.out.println(queue.take());
      System.out.println("after queue");
      
      service.shutdown(); 
   }
}

I will not go into the details of the code I added for queue monitoring as they are a lot more involved.

The coolest thing I learned about ActiveMQ is how you can embed it using the following spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       				http://www.springframework.org/schema/jms http://www.springframework.org/schema/context/spring-jms-3.0.xsd
					http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
 
    <!--  Embedded ActiveMQ Broker -->
    <amq:broker id="broker" useJmx="false" persistent="true">
        <amq:transportConnectors>
            <amq:transportConnector uri="tcp://localhost:0" />
        </amq:transportConnectors>
    </amq:broker>

    <!--  ActiveMQ Destination  -->
    <amq:queue id="destination" physicalName="com.threads.example.queue" />

    <!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->
    <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" />

    <!-- JMS Producer Configuration -->
    <bean id="jmsProducerConnectionFactory" 
          class="org.springframework.jms.connection.SingleConnectionFactory"
          depends-on="broker"
          p:targetConnectionFactory-ref="jmsFactory" />

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
          p:connectionFactory-ref="jmsProducerConnectionFactory"
          p:defaultDestination-ref="destination" />
</beans>

Once done, your application will run without your manual ActiveMQ installation. Above is from the example here.

If running in Eclipse…

  • Install m2eclipse plugin if you have not
  • Import -> Maven -> Existing Maven Projects
  • Select the MultipleQueueMonitors folder
  • Add src, resources, properties as source folders
  • Change the jre to whatever you want to use

The following error may occur in Eclipse

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c:
The matching wildcard is strict, but no declaration can be found for element 'amq:broker'. 

To fix it, you must associate the ActiveMQ XSD URL with the schema.

Go to XML->XML Catalog in Preferences, and add a User Specified Entry.

Location: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Namespace Name
Key: http://activemq.apache.org/schema/core

Then add a second one:

Location: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Schema Location
Key: http://activemq.apache.org/schema/core/activemq-core.xsd

Hit OK.

For more info, visit this stackoverflow thread.

>>>Check out or download the source from my github account if you are interested<<<

Grails: I will not use you

After the cijug presentation on Grails, I’ve decided I will not use it.

I know Grails is hot and cool but I don’t like it. It’s probably just a personal preference.

Why don’t I want to use Grails

  • It’s built on spring and hibernate, so why not just use them directly?
  • It’s just adding another layer of complexity. Now if something goes wrong, you need to know grails (groovy) plus all of the frameworks it uses underneath.
  • The generation bit is nice but personally I want control over all of the magic. You will need to modify them anyway. So why not just write them from scratch and LEARN YOUR HTML? This reminds me of the old Microsoft FrontPage HTML generation that always bit my ass when I first started creating web pages. But it probably wouldn’t be as bad since Microsoft was targeting their own browsers with the HTML generated.
  • The URL mapping is stupid. Spring’s innate annotation style mapping is so much easier.
  • I’m not a fan of the taglib. Why do I ever want to write HTML in Java? It makes me feel dirty. Plus it’s harder to debug. Personally the only “taglib” I like is facelets’ version. It felt more like writing HTML.

The only thing I really liked about Grails based on the presentation is the orm custom mapping. I prefer that over hibernate’s innate xml or annotation.

class Person {
  String firstName
  static mapping = {
      table 'people'
      firstName column:'First_Name'
  }
}

But that’s hardly worth a complete switch.

During the whole presentation I was thinking of a pyramid:

I remember not too long ago Spring and Hibernate are the newest and coolest kids on the block. Now we are just piling it on. What will we add next? I mean do you still need know Java any more to support applications? You really just need tons and tons of framework knowledge. Where do you get these knowledge from school? They are not going to teach them in college.

Dynamically invoke methods using spring config

A business rule at work requires some flexible configurations. I attempted to fulfill the need by create different spring batch steps/tasklets to execute each requirement based on a property value.

For example, step 1 will need to execute methodOne on the class Repository with the appropriate parameters. The method signature & parameters are determined by the tasklet1.chocie value in the env.properties.

I could write a bunch of if statements in each step. I wanted to see if there is a more dynamic way to do this.

I tried using Spring Framework and Java reflection.

My Git Repository for the example

Repository Class link
It has four methods: methodOne, methodOne(overloaded), methodTwo, methodThree.

TaskletExecution link
The POJO to hold the configuration needed to invoke the method using reflection.

  • String methodName
  • Object[] parameters
  • public Class[] getParameterClasses() {
    	List<Class> parameterClasses = new ArrayList<Class>();
    	for (Object parameter : parameters) {
    	    parameterClasses.add(parameter.getClass());
    	}
    	return parameterClasses.toArray(new Class[] {});
    }
    

AbstractTasklet Class link
The parent class for all of the tasklets. It has the execute method that uses reflection to invoke the method using the TaskletExecution.

public void execute() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
	log.info(String.format("in '%s' execute with choice '%s'", getTaskletName(), choice));
	Method method = Repository.class.getMethod(taskletExecution().getMethodName(), taskletExecution().getParameterClasses());
	Integer repositoryResult =(Integer)method.invoke(repository, taskletExecution().getParameters());
	log.info(String.format("repository result = '%s'", repositoryResult));
}

The TaskletExecution is determined by the value of the tasklet#.choice property in the env.properties. It uses the property to look up the taskletExecution value in the taskletExecutions map that’s autowired to each tasklet via spring.

Example of a TaskletExecutions Map link

<util:map id="tasklet5Executions" value-type="net.pureessence.example.TaskletExecution">
    <entry key-ref="choice1">
        <bean class="net.pureessence.example.TaskletExecution">
            <property name="methodName" value="methodThree"/>
            <property name="parameters">
                <list>
                    <bean class="java.lang.String">
                        <constructor-arg>
                            <value>51</value>
                        </constructor-arg>
                    </bean>
                    <bean class="java.lang.Integer">
                        <constructor-arg>
                            <value>52</value>
                        </constructor-arg>
                    </bean>
                    <bean class="java.lang.String">
                        <constructor-arg>
                            <value>tasklet5 arg3</value>
                        </constructor-arg>
                    </bean>
                    <bean class="net.pureessence.example.Type" factory-method="valueOf">
                        <constructor-arg>
                            <value>TYPE_3</value>
                        </constructor-arg>
                    </bean>
                </list>
            </property>
        </bean>
    </entry>
    <entry key-ref="choice2">
        <bean class="net.pureessence.example.TaskletExecution">
            <property name="methodName" value="methodOne"/>
            <property name="parameters">
                <list>
                    <bean class="java.lang.String">
                        <constructor-arg>
                            <value>tasklet5 arg1</value>
                        </constructor-arg>
                    </bean>
                    <bean class="java.lang.Integer">
                        <constructor-arg>
                            <value>123599</value>
                        </constructor-arg>
                    </bean>
                    <bean class="net.pureessence.example.Type" factory-method="valueOf">
                        <constructor-arg>
                            <value>TYPE_3</value>
                        </constructor-arg>
                    </bean>
                </list>
            </property>
        </bean>
    </entry>
</util:map>

Personally I’m not overly thrilled with how verbose the spring config is. It took me a long time to figure out how to make it syntactically correct. The spring in depth site is a very good resource. In general, it takes a lot of xml to create maps in spring. I think at this point, it maybe a better idea to create static maps in each tasklet in Java for configurations.

My Git Repository for the example

itext page number (page x of y)

I was looking for a complete example of how to dynamically generate the page numbers when you create the pdf using iText and I couldn’t find one. This is based on the example in the iText in Action book but I added my “refactoring” if you will.

I hope this helps someone. If not, it will definitely help myself in the future :)

public abstract class BaseReportBuilder extends PdfPageEventHelper {
	protected BaseFont baseFont;
	private PdfTemplate totalPages;
	private float footerTextSize = 8f;
	private int pageNumberAlignment = Element.ALIGN_CENTER;

	public BaseReportBuilder() {
		super();
		baseFont = load("fonts", "tahoma.ttf");
	}

	private BaseFont load(String location, String fontname) {
		try {
			InputStream is = getClass().getClassLoader().getResourceAsStream(location + System.getProperty("file.separator") + fontname);

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte buf[] = new byte[1024];

			while (true) {
				int size = is.read(buf);
				if (size < 0)
					break;
				out.write(buf, 0, size);
			}
			is.close();
			buf = out.toByteArray();
			return BaseFont.createFont(fontname, BaseFont.CP1252, true, true, buf, null);
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public void onOpenDocument(PdfWriter writer, Document document) {
		totalPages = writer.getDirectContent().createTemplate(100, 100);
		totalPages.setBoundingBox(new Rectangle(-20, -20, 100, 100));
	}

	@Override
	public void onEndPage(PdfWriter writer, Document document) {
		PdfContentByte cb = writer.getDirectContent();
		cb.saveState();
		String text = String.format("Page %s of ", writer.getPageNumber());

		float textBase = document.bottom() - 20;
		float textSize = baseFont.getWidthPoint(text, footerTextSize);
		
		cb.beginText();
		cb.setFontAndSize(baseFont, footerTextSize);
		if(Element.ALIGN_CENTER == pageNumberAlignment) {
			cb.setTextMatrix((document.right() / 2), textBase);
			cb.showText(text);
			cb.endText();
			cb.addTemplate(totalPages, (document.right() / 2) + textSize, textBase);
		} else if(Element.ALIGN_LEFT == pageNumberAlignment) {
			cb.setTextMatrix(document.left(), textBase);
			cb.showText(text);
			cb.endText();
			cb.addTemplate(totalPages, document.left() + textSize, textBase);
		} else {
			float adjust = baseFont.getWidthPoint("0", footerTextSize);
			cb.setTextMatrix(document.right() - textSize - adjust, textBase);
			cb.showText(text);
			cb.endText();
			cb.addTemplate(totalPages, document.right() - adjust, textBase);
		}
		cb.restoreState();
	}

	@Override
	public void onCloseDocument(PdfWriter writer, Document document) {
		totalPages.beginText();
		totalPages.setFontAndSize(baseFont, footerTextSize);
		totalPages.setTextMatrix(0, 0);
		totalPages.showText(String.valueOf(writer.getPageNumber() - 1));
		totalPages.endText();
	}

	public void setPageNumberAlignment(int pageNumberAlignment) {
		this.pageNumberAlignment = pageNumberAlignment;
	}
}

public class PageNumberReportBuilder extends BaseReportBuilder {
	public ByteArrayOutputStream buildPage() {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		Document document = new Document(PageSize.LETTER);
		
		try {
			PdfWriter writer = PdfWriter.getInstance(document, stream);
			writer.setPageEvent(this);
			document.open();
			// add your document stuff
		} catch(DocumentException e) {
			throw new RuntimeException(e);
		}
		
		document.close();
		return stream;
	}
}

Download the complete code example (eclipse project) along with jUnit tests where you can actually generate the PDF file.

Java instaniate an abstract class… sort of…

At work I had to create some test data for a junit test. The function I’m testing expects a super abstract class to be passed in and I need to test the same function for bunch of child classes. I wish I could just pass in the parent class but since it’s abstract I cannot instantiate it. I wonder if there is a way using reflection so I can instantiate the class?? Since I could not find a way, I used the following:

public void testSomeFunction() throws Exception {
	ParentData data1 = populate(ChildDataOne.class);
	//..test..

	ParentData data2 = populate(ChildDataTwo.class);
	//..test..
}

private static ParentData populate(Class clazz) throws Exception {
	ParentData data = clazz.newInstance();
	data.setProperty1("1");
	data.setProperty2("2");
	data.setProperty3("3");
	data.setProperty4("4");
	data.setProperty5("5");
	return data;
}

Setting private property without setter in Java

Not really a new trick but I had to look for the syntax today to use reflection to set a private property on an object to use it in a junit test.

Class clazz = someFooObject.getClass();
Field f = clazz.getDeclaredField("somePrivateField");
f.setAccessible(true);
f.set(someFooObject, new Integer(50));

Java: BETTER way to traverse a map

While reviewing the findbugs report (WMI_WRONG_MAP_ITERATOR) for a new project at work, I learned a better way to traverse a map in Java. In fact, since the first day I started coding in Java, I never thought twice about how to traverse a map. You always traverse the keys and use the key to get the value of the map.

for (Key key : map.keySet()) {
	Value value = map.get(key);
}

However, comes to think of it, it’s such a no-brainer. Every time you call map.get(key) you pay the price of the lookup. Since you need EVERY ELEMENT in the map, why look it up? Just get all of them like this:

for(Map.Entry mapEntry : map.entrySet()) {
	Key key = mapEntry.getKey();
	Value value = mapEntry.getValue();
}

That’s how jstl works. I just never paid attention. Better know it late than never :)

Java: static declaration of collection

I don’t know if this is a new feature in Java 5 that I did not know before or I just did not know this is possible in Java. But I learned today that you can do static declaration of collection types as below:

public static List supportedCopyPropertyTypes = new ArrayList() {
		private static final long serialVersionUID = 660145948432567403L;
		{
			add("String");
			add("BigDecimal");
			add("int");
		}
	};