Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, December 10, 2010

The Malaysian Java User Group can be more than just a mailing list

Is simply just a mailing list for years. Continue reading.

Recently, I received an email (with a few in the loop, not through the mailing list) from Loke to discuss about some aspects of MyJUG. I found it hard to respond to most posted questions (such as "Best Practices" and "Strengths and Opportunities" of this group), simply because - the cruelest fact - there's nothing much to describe.

I join the mailing list about 4 to 5 years ago, when I innocently thought getting to know more people there could get some new hires for my former employer. It doesn't work that way (or at least at the moment), so if you happen to have the same intention, you may want to readjust or quit.

Every now and then, I whine and whine to some people about the lack of substantive committee to move forward the group, the lack of activities, etc. Then, every now and then, we voted for topics and things go silent. Then, recur.

StackOverflowError not yet.

To run a successful technical/user group seems really hard in Malaysia. FOSS-SM used to have consistent monthly meetup when Aizat was active. Chee Seng runs the Flex UG (MyFlex) but the number of participants is really low (also given the fact that Flex is barely a killer). Umm, the PHP UG seems pretty successful though. Why?

I don't know.

The community can change it.

Monday, February 22, 2010

Some Groovy Class-Loading Notes

Was trying to load a resource (*.properties) from the class-path and as you know, class loading can be a PITA at different enviroments (IDEs, build tools, tests, containers).

Here's the snippet I used, ran with Maven and Eclipse IDE, target/test-classes is in the class-path.
String name = "aflexi.itest.properties"

// System CL
println ClassLoader.getSystemClassLoader()
// Uses system or bootstrap CL
println ClassLoader.getSystemResource(name)

// Caller CL
println ClassLoader.getCallerClassLoader()
println ClassLoader.getCallerClassLoader().getResource(name)

// Class's class loader. Perfectly fine in both places
println getClass().getClassLoader()
println getClass().getClassLoader().getResource("aflexi.itest.properties")

// Doesn't work anywhere, the CL is the one of previous, but the name will be resolved as "net/aflexi/cdn/test/itest/aflexi.itest.properties"
println getClass().getClassLoader0()
println getClass().getResource("aflexi.itest.properties")

// Doesn't work either. Using Groovy's calling class.
println ReflectionUtils.getCallingClass()
println ReflectionUtils.getCallingClass().getResource("aflexi.itest.properties")

And here's the result:

Expression / Class LoaderTest 1: InstanceTest 2: InstanceTest 1: Found Resource?Test 2: Found Resource?
ClassLoader.getSystemClassLoader().getResource()sun.misc.Launcher$AppClassLoader@19134f4sun.misc.Launcher$AppClassLoader@19134f410
ClassLoader.getCallerClassLoader().getResource()sun.misc.Launcher$AppClassLoader@19134f4org.codehaus.groovy.tools.RootLoader@8965fb11
getClass().getClassLoader().getResource()groovy.lang.GroovyClassLoader$InnerLoader@14177f3groovy.lang.GroovyClassLoader$InnerLoader@dc043511
getClass().getResource()groovy.lang.GroovyClassLoader$InnerLoader@14177f3groovy.lang.GroovyClassLoader$InnerLoader@dc043500
ReflectionUtils.getCallingClass().getResource()class cuke4duke.internal.groovy.GroovyLanguageclass groovy.ui.GroovyMain00

Take note that, getClass().getResource() uses the same CL instance (otherwise system CL) with getClass().getClassLoader().getResource(). The reason why it failed is that, it resolves the name of the properties file with package name, i.e. aflexi.itest.properties to net/aflexi/cdn/test/itest/aflexi.itest.properties.

Thursday, December 17, 2009

3 Spring Stuff Worth Sharing

Firstly, Spring 3.0.0 is released not more than 2 days ago. Juergen (if you have the habit of reading source code, you shall know him) blogged about the features at Spring Framework 3.0 goes GA. I am particularly interested to explore more (possibly make changes to my existing project) in the area of @Configuration, SpEL, REST, OXM and validation.

I also upgraded my project this morning, with less than 10 lines of code changes to switch the plug from 2.5.6 to 3.0.0 - the compilation errors were some casting issues of generics type - yes, Spring 3 is now compile-time type safe. If you use Maven, you may want to read about the pom and repository configurations here.

Second-and-thirdly, below are some notes I wrote down in company's intranet. :)

Spring Resolves Dependencies and Initializes Accordingly, Not You

Before that, I thought implementing the Ordered interface could impact the order of which beans shall first be loaded. Then I realized, it doesn't work. Ordered is used.. as far as I can tell right now, two on top of my head: during invocation of Bean and BeanFactory post processing and the order of Advices - just not Bean initialization!

So how does it really work (for which bean to be loaded before any other)? One thing that I found (or maybe really just one): dependencies - bean references and @DependsOn/depends-on. When the BeanFactory preinstantiates the beans, it resolves its dependencies (via BeanDefinitionValueResolver) and eventually the beans who are referenced/dependent by others will be initialized first.

Do take note that, you rarely use @DependsOn unless you have static (*ugh!!*) references. For my case, HibernateSessionFactoryBean depends on SubEntityManager and those enums in it are accessed via the static (*ugh!!*) method SubEntityManager.getInstance() by the SubEntityUserType.

Spring Shutdown Hook and Unit Testing

A Spring ApplicationContext has a close() method, things like HibernateSessionFactoryBean will only be destroyed when the context is destroyed via the close() method - which is triggered by shutdown hook. See AbstractApplicationContext.registerShutdownHook(). So what is important here to know is, if you are running unit tests, a series of them, destroy can only happen when the shutdown hook is called.

Here's an example, I was running two test fixtures but the first one didn't shutdown until the whole test execution exited.
[12-16 16:26:45] INFO  GenericApplicationContext [Thread-4]: Closing org.springframework.context.support.GenericApplicationContext@1923ca5: ...startup date [Wed Dec 16 16:26:42 MYT 2009]; root of context hierarchy
[12-16 16:26:45] INFO  GenericApplicationContext [Thread-3]: Closing org.springframework.context.support.GenericApplicationContext@19b5217: ...startup date [Wed Dec 16 16:26:34 MYT 2009]; root of context hierarchy
[12-16 16:26:45] INFO  HibernateSessionFactoryBean [Thread-4]: Closing Hibernate SessionFactory
[12-16 16:26:45] INFO  HibernateSessionFactoryBean [Thread-3]: Closing Hibernate SessionFactory

Friday, July 10, 2009

Hibernate session issue during Spring tests

I reckon this is something good to share as it took me a few hours to get the problem resolved.

We are using SpringJUnit4ClassRunner for our DAO tests, the tests passed when they were run in Eclipse, but not in Maven. One of the test classes failed with HibernateSystemException:

org.springframework.orm.hibernate3.HibernateSystemException: Illegal attempt to associate a collection with two open sessions; nested exception is org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

Google search gave me some clue about the problem had something to do with cascading style, transaction, and duplication but they didn't lead me anywhere. I broke at AbstractPersistentCollection.setCurrentSession to find out that the session/session factory (DAOs are instances of HibernateDaoSupport) assigned to one of the DAOs was different.

A second look at the test class which had:
@Autowired
BillingInvoiceDao $;
BillingOrderDao orderDao;
BillingItemDao itemDao;
MembershipDao membershipDao;

@Override
protected void setUpDataAccessObjects() {
membershipDao = DataAccessObjectHelper.getDataAccessObject(MembershipDao.class);
itemDao = DataAccessObjectHelper.getDataAccessObject(BillingItemDao.class);
orderDao = DataAccessObjectHelper.getDataAccessObject(BillingOrderDao.class);
}

I found out that BillingInvoiceDao was not a proxy instance but the other DAOs are. The log may explain something:
[07-11 09:19:30] DEBUG AutowiredAnnotationBeanPostProcessor [main]: Autowiring by type from bean name 'itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest' to bean named 'billingInvoiceDao'
[07-11 09:19:30] DEBUG DefaultListableBeanFactory [main]: Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
[07-11 09:19:30] DEBUG DefaultListableBeanFactory [main]: Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
[07-11 09:19:30] DEBUG AnnotationTransactionAttributeSource [main]: Adding transactional method [testCrud] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
[07-11 09:19:30] DEBUG AnnotationAwareAspectJAutoProxyCreator [main]: Creating implicit proxy for bean 'itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest' with 0 common interceptors and 1 specific interceptors
[07-11 09:19:30] DEBUG JdkDynamicAopProxy [main]: Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest@17afcff]
[07-11 09:19:30] DEBUG AnnotationTransactionAttributeSource [main]: Adding transactional method [testCrud] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
[07-11 09:19:30] DEBUG TransactionalTestExecutionListener [main]: Explicit transaction definition [PROPAGATION_REQUIRED,ISOLATION_DEFAULT] found for test context [[TestContext@134b58c testClass = HibernateBillingInvoiceDaoTest, locations = array['classpath:spring/dataAccessTestContext.xml', 'classpath:spring/dataAccessTestContext.billing.xml'], testInstance = itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest@17afcff, testMethod = testCrud@HibernateBillingInvoiceDaoTest, testException = [null]]]
[07-11 09:19:30] DEBUG TransactionalTestExecutionListener [main]: Retrieved @TransactionConfiguration [@org.springframework.test.context.transaction.TransactionConfiguration(defaultRollback=true, transactionManager=mainTxManager)] for test class [class itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest]
[07-11 09:19:30] DEBUG TransactionalTestExecutionListener [main]: Retrieved TransactionConfigurationAttributes [[TransactionConfigurationAttributes@ddc524 transactionManagerName = 'mainTxManager', defaultRollback = true]] for class [class itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest]
[07-11 09:19:30] DEBUG DefaultListableBeanFactory [main]: Returning cached instance of singleton bean 'mainTxManager'
[07-11 09:19:30] DEBUG TransactionalTestExecutionListener [main]: Executing @BeforeTransaction method [public void net.aflexi.cdn.core.test.AbstractDaoTest.setUpBeforeTransaction() throws java.lang.Exception] for test context [[TestContext@134b58c testClass = HibernateBillingInvoiceDaoTest, locations = array['classpath:spring/dataAccessTestContext.xml', 'classpath:spring/dataAccessTestContext.billing.xml'], testInstance = itest.net.aflexi.cdn.billing.HibernateBillingInvoiceDaoTest@17afcff, testMethod = testCrud@HibernateBillingInvoiceDaoTest, testException = [null]]]
[07-11 09:19:30] DEBUG DefaultListableBeanFactory [main]: Returning cached instance of singleton bean 'membershipDao'

That transaction propagation happened after autowiring of beans. The fix of my problem is to @Autowired all DAOs (so that they are consistent) or assign them via the DataAccessObjectHelper as shown in the snippet.

Hope this helps.

Saturday, April 11, 2009

"Autoboxing" Array is Illegal

Wrote some array methods today then I had a question about auto-converting an int[] to Integer[] (auto-boxing) while I was driving back home.

For instance, this works,
public static  V wrapper(V v, Class clazz){
return v;
}

int i = wrapper(1, Integer.class);

But this is not compilable,
public static  V[] wrapperArray(V[] v, Class clazz){
return v;
}

int[] i2 = wrapperArray(i2, int.class);

int.class will be auto-converted to Integer.class but int[] will not. I can't find the exact line in JLS describing this, do leave a comment if you could.

Friday, April 10, 2009

Strange Maven Plugin Metadata Problem

Not too sure when, my Maven Eclipse plugin has been upgraded to 2.6 and probably due to some metadata "corruption", its dependencies were not downloaded, running it caused ClassNotFoundException:

[INFO] ------------------------------------------------------------------------
[INFO] Building Whatever
[INFO] task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
...
-----------------------------------------------------
this realm = app0.child-container[org.apache.maven.plugins:maven-eclipse-plugin:2.6]
urls[0] = file:/home/yclian/.m2/repository/org/apache/maven/plugins/maven-eclipse-plugin/2.6/maven-eclipse-plugin-2.6.jar
urls[1] = file:/home/yclian/.m2/repository/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
Number of imports: 10
import: org.codehaus.classworlds.Entry@a6c57a42
import: org.codehaus.classworlds.Entry@12f43f3b
import: org.codehaus.classworlds.Entry@20025374
import: org.codehaus.classworlds.Entry@f8e44ca4
import: org.codehaus.classworlds.Entry@92758522
import: org.codehaus.classworlds.Entry@ebf2705b
import: org.codehaus.classworlds.Entry@bb25e54
import: org.codehaus.classworlds.Entry@bece5185
import: org.codehaus.classworlds.Entry@3fee8e37
import: org.codehaus.classworlds.Entry@3fee19d8


this realm = plexus.core
urls[0] = file:/opt/maven-2/lib/maven-2.1.0-uber.jar
Number of imports: 10
import: org.codehaus.classworlds.Entry@a6c57a42
import: org.codehaus.classworlds.Entry@12f43f3b
import: org.codehaus.classworlds.Entry@20025374
import: org.codehaus.classworlds.Entry@f8e44ca4
import: org.codehaus.classworlds.Entry@92758522
import: org.codehaus.classworlds.Entry@ebf2705b
import: org.codehaus.classworlds.Entry@bb25e54
import: org.codehaus.classworlds.Entry@bece5185
import: org.codehaus.classworlds.Entry@3fee8e37
import: org.codehaus.classworlds.Entry@3fee19d8
-----------------------------------------------------
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Internal error in the plugin manager executing goal 'org.apache.maven.plugins:maven-eclipse-plugin:2.6:eclipse': Unable to load the mojo 'org.apache.maven.plugins:maven-eclipse-plugin:2.6:eclipse' in the plugin 'org.apache.maven.plugins:maven-eclipse-plugin'. A required class is missing: org/codehaus/plexus/resource/loader/ResourceNotFoundException
org.codehaus.plexus.resource.loader.ResourceNotFoundException

Tried running Maven with the -cpu argument but it didn't help. maven-metadata-central.xml showed the latest as 2.5.1 and others got 2.6. Fixed by deleting metadata files then re-run Maven.

Bah.

Thursday, March 5, 2009

404 on Nexus

Was stuck for a few minutes as Sonatype Nexus was reporting 404 while I tried to access a POM file. Expiring the cache (right clicking on the troubled repository) is the fix of it.

Sunday, February 15, 2009

InflaterIjputStream.class

Exception in thread "main" java.lang.NoClassDefFoundError:
java/util/zip/InflaterInputStream
at java.util.zip.ZipFile.getInputStream(ZipFile.java:212)
at java.util.zip.ZipFile.getInputStream(ZipFile.java:180)
at java.util.jar.JarFile.hasClassPathAttribute(JarFile.java:463)
...

In the rt.jar, InflaterInputStream.class was named InflaterIjputStream.class. How could this happen? Fixed the issue by repackaging the zip.

yc

Tuesday, February 10, 2009

JVM failed with Segmentation Fault

This happened completely out of a sudden and truly random. The JVM that runs our business logic app died last night and could never be brought up anymore due to segmentation fault. (It suicided quietly)

The last few lines via strace:

DEBUG DefaultListableBeanFactory [main]: Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
[02-10 10:22:30] DEBUG AnnotationTransactionAttributeSource [main]: Adding transactional method [createUser] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT]
) = ? ERESTARTSYS (To be restarted)
+++ killed by SIGSEGV +++

It could just be a JVM bug (not exactly sure which, but suggested by John Raymond Wold, W_work in #[email protected]) and upgrading to the newest version fixed the problem.

- yc

Monday, December 1, 2008

Hudson SVN Revisions/Changes Went Out of Sync

A project in our Hudson had been stalled for 3 weeks, for its svn revisions/changes, and I had to do a manual svn update in its workspace directory to make sure the build runs correctly. What exactly happened is that, Hudson was not checking out the HEAD revisions of these modules but the old revisions before it ran into this problem, besides, the "Changes" page showed no information other than those builds that happened 3 weeks ago.

So I thought there could be some state being held by it and I tried:
  • To turn off using SVN update but SVN checkout for every build.
  • To change the revision values in the svnexternals.txt.
  • etc.
None of these helped 'til I changed the synchronousPolling in hudson.triggers.SCMTrigger.xml from false to true and Hudson finally polled the latest revisions and updated the "Changes" page for the newly triggered build. This reset the state and behaviour (of polling all in one go) and therefore resolved my problem.

Just a tip if any of you ever hit into this.

yc

Sunday, November 23, 2008

Where is the log file of Eclipse TPTP Agent Controller?

I have a problem to use the integrated agent controller, which RAServer.sh reported that it has actually been running. Still finding and just learned that the logs are available at:

$TPTP_AC_HOME/config/servicelog.log

yc

Thursday, November 6, 2008

Profiling a Remote Application in Eclipse

I came across this guide which mentioned about attaching the Eclipse profiler to a remote Java application. I was stuck for some hours, asked my question in #java and #eclipse but got no response.. then, realized that, the instructions are old!

Instead, I visited the TPTP site, downloaded the Agent Controller and followed the instructions in this page to get things up and running. Basically,
  • Add $TPTP_AC_HOME/lib:$TPTP_AC_HOME/bin:$TPTP_AC_HOME/plugins/org.eclipse.tptp.javaprofiler to $LD_LIBRARY_PATH
  • Add $TPTP_AC_HOME/bin to $PATH
  • Run SetConfig.sh to configure the AC
  • Run ACStart.sh to start AC
  • Add '-agentlib:JPIBootLoader=JPIAgent:server=enabled;CGProf' to your JAVA_OPTS (ldd and nm are good commands)
  • Start your Java application
  • Profile and hook into the application by selecting "Attach to Agent" in the Eclipse's dialog
- yc

Friday, October 31, 2008

XML-RPC vs. SOAP vs. REST thoughts and Spring Beans

Recently I am working on the remote API side of my project, and the protocol that we chose is XML-RPC. Somewhere in two blogs returned by Google search suggested that REST > XML-RPC > SOAP. SOAP can only be considered for its wide enterprise adoption and protocol stack (with security management, transaction control, etc.) and therefore it is complicated. Yes, the person created XML-RPC wasn't an expert in XML but it's neat.

Why not REST then? I used to work on design and technical issues of Mule ESB and I was exposed to REST of its sweetness (the simplicity, the CRUD stuff) before more people started to talk about it (now they talk about Cloud). I learned that SOAP is for SOA (Service Oriented Architecture) and REST is for ROA (Resource Oriented Architecture). They are two different paradigms, and the purpose and design of these layers are therefore different, e.g. you don't carry a service/RPC mindset when you create a REST API.

So, no REST for now as IMO it requires more effort to design a proper API. Never I'll create SOAP due to its complexity.

What about JSON-RPC? I had a short discussion regarding this with @ditesh at #[email protected]. I love JSON for its interoperability and speed (vs. XML parsing). But the available implementations turned me off pretty quickly, most of them stuck in year 2005~2007. For a publicly available remote API, a well-adopted and "mature" protocol is a much better choice.

What about the Spring beans stuff mentioned in the topic? I found the Apache XML-RPC server can't be integrated with Spring naturally (it has but not enough of bean property methods) and the API is quite ugly, e.g. XmlRpcSystemImpl.addSystemHandler() takes a PropertyHandlerMapping, why not XmlRpcListableHandlerMapping?

I took a similar approach suggested by Tomas Salfischberger in his blog and here they are:
  • An implementation of Spring's AbstractController.
  • An extension of PropertyHandlerMapping, this bean is used by the previous.

public class MyXmlRpcController extends AbstractController {
private XmlRpcServletServer server = new XmlRpcServletServer();
private boolean introspectionEnabled = false;

@Override
protected void initServletContext(ServletContext servletContext) {
super.initServletContext(servletContext);
if (this.introspectionEnabled) {
try {
XmlRpcSystemImpl.addSystemHandler((PropertyHandlerMapping) this.server.getHandlerMapping());
} catch (Exception e) {
}
}
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
this.server.execute(request, response);
return null;
}
@Required
public void setHandlerMapping(XmlRpcHandlerMapping serverHandlerMapping) {
this.server.setHandlerMapping(serverHandlerMapping);
}
public void setIntrospectionEnabled(boolean introspectionEnabled) {
this.introspectionEnabled = introspectionEnabled;
}
}

public class MyXmlRpcHandlerMapping extends PropertyHandlerMapping {
private Map serviceMap;

public void init() throws XmlRpcException {
this.load(Thread.currentThread().getContextClassLoader(), serviceMap);
}
@Required
public void setServicesMapping(Map serviceMap) {
this.serviceMap = serviceMap;
}
}


<bean id="xmlRpcHandlerMapping" class="my.MyXmlRpcHandlerMapping" init-method="init">
<property name="servicesMapping">
<map>
<entry key="membershipService" value="my.service.XmlRpcMembershipService"></entry>
</map>
</property>
</bean>
<bean id="urlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>/xmlrpc=xmlRpcController</value>
</property>
</bean>
<bean id="xmlRpcController" class="my.MyXmlRpcController">
<property name="handlerMapping" ref="xmlRpcHandlerMapping"></property>
<property name="introspectionEnabled" value="true"></property>
</bean>


- yc

Friday, October 17, 2008

The guys behind the new Maybank2U, please read

Epic fail! For the past few days, I had been hearing people ranting about the new site in Twitter, Facebook and my IM.

I haven't been using my Maybank account (basically abandoning it unless there's a need to M2U to some friends for convenience sake, oh.. and, it has more ATM machines than HSBC that is true) for the past 2 months ever since I changed my job.

As I am NOW doing some book keeping, as well as to experience the pain others are suffering, I convinced myself to log into the site. Clicking on "Transaction History", the cool Ajaxy waiting icon appeared and.. woohoo, a few 10 seconds later:

ImageAh, ArrayIndexOutOfBoundsException, caused by a JSP tag. I don't want to know what else they're doing with Struts and in the JSP, but surely, these guys wrote some shit to make almost every customer suffers.

- yc

Monday, October 13, 2008

I love Java

Love? Love comes with struggles, frustrations, hate; it's unconditional. There's this "I Love *" meme initiated by the folks at foss.my and in supporting of it and to show my love to the programming language and its community:

Image

I love Java for how advanced it is, for the standards (see JCP and JSRs) that have been defined, for the other languages that you can run on top of it, for its rich frameworks and libraries, ...

I hate Java, for the same reasons too. :)

Note: The Sun's Java Virtual Machine (runtime) is called HotSpot. It is released under GPL, it wasn't.. before November 2006. Here is a list of JVM implementations.

- yc

Friday, July 25, 2008

Things do Go Wrong Sometimes

Chuk Munn is a Sun Evangelist who I met last week, a comment from him in the Malaysian Java User Group lately, however, went very wrong and was found in strong disagreement by a number of us.

It's a topic on class-loading which he shared based on his past experience that "(you shall) never use a functionality from an open source project if it is available unless you absolutely have to."

I'm not sure what he was trying to sell, maybe the Java Logging API provided by the SDK versus Log4J. But certainly from me, I would rather put the blame on the container of not doing a good isolation work instead of blaming open source.

- yc

Tuesday, July 22, 2008

"Shutting down" the RMI Registry

This blog is a quick tip to shut down the RMI registry. Something I encountered just now while writing the tearDown() method for a test case.

When a RMI registry has already been created (via LocateRegistry.createRegistry()), re-creating it will give you an ExportException:
java.rmi.server.ExportException: internal error: ObjID already in use
at sun.rmi.transport.ObjectTable.putTarget(ObjectTable.java:169)
at sun.rmi.transport.Transport.exportObject(Transport.java:74)
at sun.rmi.transport.tcp.TCPTransport.exportObject(TCPTransport.java:229)
at sun.rmi.transport.tcp.TCPEndpoint.exportObject(TCPEndpoint.java:393)
at sun.rmi.transport.LiveRef.exportObject(LiveRef.java:129)
at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:190)
at sun.rmi.registry.RegistryImpl.setup(RegistryImpl.java:92)
at sun.rmi.registry.RegistryImpl.<init>(RegistryImpl.java:78)
at java.rmi.registry.LocateRegistry.createRegistry(LocateRegistry.java:186)
at org.mule.transport.rmi.RmiMessageReceiverTestCase.registerRmi(RmiMessageReceiverTestCase.java:126)

Yes, you can't create the same registry twice, therefore you may want to dispose the previous one after every test (not actually necessary, as you could just share the same instance for all tests). An RMI registry can be disposed with the UnicastRemoteObject.unexportObject() method, by passing the Registry object to the method argument. Take note that LocateRegistry.createRegistry() and LocateRegistry.getRegistry() give you a stub to the remote object as a different object, so please use the same reference returned from the createRegistry() method.

- yc

Monday, July 21, 2008

A Networking Session with Sun / Java Evangelists

There was an invitation sent to MyJUG, to a networking session with the Sun / Java Evangelists last Wednesday at Monash University. The turn-up wasn't that high and I reached there pretty late too, I guess everyone was pretty stuck at work or in the jam. Thanks Chee Seng for the ride, otherwise I would have stuck 'til the event had ended.

Good to see familiar face like Colin Charles (the MySQL guy) and Loke there, and finally met up with Monica Ng (the Marketing Communication Consultant of Sun). The evangelists in list anyway, were, Matt Thompson, Reginald Hutcherson, Lee Chuk Munn, Peter Karlsson, Colin and Naveen Asrani.

Sitting alongside with the evangelists was fun. We started our technical conversation when Chee Seng introduced himself as a Flex guy. Chuk Munn and other folks started to bash Flex to promote JavaFx, something that I did not show much interest on which I might give a try now after being told that the beta release will be a very fine product.

We also touched on the performance enhancement of Java 6 SE Update 10 as well as the new Open Solaris. We all left after some folks distributed the live CD of the OS.

It would have been a greater event without the nearly 2-hour jam. Hopefully Sun will make it a weekend next time.

- yc

Monday, July 14, 2008

PropertyPlaceholderConfigurer.ignoreUnresolvablePlaceholders and my precious one hour

To speed up my prototyping process, I decided to use Mule to takecare of the integration of my core code with the persistence layer for me. Yes, basically I am lazy to write all the polling, updating, etc. This did not turn out good as I was stupidly assuming a startup problem a Mule issue and tried to fix it in the past 1 hour.

So what was it about?

I have a Mule configuration and also a Spring beans configuration which is used to configure datasource. PropertyPlaceholderConfigurer is also defined in the Spring configuration to read a jdbc.properties file and those properties will be filled into the datasource settings, e.g.

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>

Great, unit test goes easier now. Not yet.

I have this JDBC query settings in my Mule configuration:

<jdbc:connector name="jdbcConnector" dataSource-ref="dataSource" pollingFrequency="5000">
<jdbc:query key="getSurrogateById" value="SELECT * FROM surrogate WHERE surrogateId=${header:test}" />
</jdbc:connector>

Tried to start Mule, but it failed with this error:

[07-15 00:47:34] ERROR AbstractConfigurationBuilder [main]: Configuration with "org.mule.config.spring.SpringXmlConfigurationBuilder" failed.
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'jdbcConnector' defined in null: Could not resolve placeholder 'header:test'
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:268)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:75)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:554)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:528)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:363)
at org.mule.config.spring.MuleApplicationContext.<init>(MuleApplicationContext.java:102)</init>

Changing the Mule version didn't help (something stupid that I did), until I uncommented PropertyPlaceholderConfigurer, Mule was able to start. That gave me the clue to look into the class (which I didn't have to as the stacktrace was obvious enough) to find out the ignoreUnresolvablePlaceholders property.

Bah.

- yc, finished ranting

Monday, July 7, 2008

How Generic Shall it Be?

I have been writing the protocol API using Java 1.5 these days. There are some tempting features to use, but I'm not sure how evil they will be.

For instance, I use annotations to reflect clauses mentioned in the technical specifications:
@TechnicalRecommendations("1.2.1.3")
@PublishEvent(events={"UserNotification.EventType.ACCOUNT_CREATING", "UserNotification.EventType.ACCOUNT_CREATED"})
public void createUser(User caller, User targetUser) throws PermissionException;


I also use the generic feature:
public interface User<P extends Profile<?> extends Entity
public interface Profile<U extends User<?>> extends Entity


That sounds a bit funny hey. I haven't yet found a good guide on how you should use generic smartly. Comments?

- yc