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

Saturday, December 28, 2013

Maven plugins & extensions for working with WSDLs, XSDs and POJOs

My favorite plugin for generating a webservice from a WSDL file (WSDL-first-approach) is Apache CXF because it loops in Spring, JAX-WS and other standards and implementations to make it happen.

Before CXF became by BFF I had gone looking for a maven archetype/template that would bring everything together for me in Eclipse. I did some templates but none that used the WSDL-first-approach to generate a sample project for me. So I gave up on looking for archetypes and instead followed a mix of instructions from the following links:
Anyway, CXF is awesome for the following reasons:
  • It is easy to configure cxf-codegen-plugin for generating a Java webservice code from a WSDL file.
  • It is easy to configure cxf-xjc-plugin for generating POJO (plain-old-java-objects) classes from a XSD (schema) file.
  • Other maven extensions can be used to enhance the cxf-xjc-plugin's schema to POJO conversion process:
    • Lets say you want to use something like a builder-pattern which makes your written code more beautiful. You can do that by configuring the jaxb-fluent-api extension!
    • If some of your POJOs share the same methods then not being able to categorize all those POJOs under a common interface can lead to duplicate code. For example, lets say you have a method named: performCommonTaskOnIncomingObject(ClassName argument) ... now you may need to have multiple such method with different names because you'll need to change the argument's classname everytime to match the object you're passing in!

Thursday, April 21, 2011

Log4j: Log concrete and abstract classes

In the past I've often pondered how to get better logging when I'm dealing with abstract classes.

Let's take the following class struture as an example:
  • SomeInterface
    • AbstractImpl
      private static final Logger logger = Logger.getLogger(AbstractImpl.class)
      • ConcreteImpl_A
        private static final Logger logger = Logger.getLogger(ConcreteImpl_A.class)
      • ConcreteImpl_B
        private static final Logger logger = Logger.getLogger(ConcreteImpl_B.class)
This usually results in logs like:
21 Apr 2011 DEBUG [main] (AbstractImpl.java:10) - the actual log message
21 Apr 2011 DEBUG [main] (AbstractImpl.java:10) - the actual log message
... which makes it difficult to distinguish between the concrete implementation classes that are actually being used when the message was logged.

This entry helped me realize that the (AbstractImpl.java:10) portion of the logged line was being placed there by the regex (%F:%L) from the PatternLayout that was specified in the log4j.properties file like so:
log4j.appender.CONSOLE.layout.ConversionPattern=%d{dd MMM yyyy} %5p [%t] (%F:%L) - %m%n
Therefore, the solution would be to add the regex [%c{1}]:
log4j.appender.CONSOLE.layout.ConversionPattern=%d{dd MMM yyyy} %5p [%t] [%c{1}] (%F:%L) - %m%n
Hoping to get logs that look like:
21 Apr 2011 DEBUG [main] [ConcreteImpl_A] (AbstractImpl.java:10) - the actual log message
21 Apr 2011 DEBUG [main] [ConcreteImpl_B] (AbstractImpl.java:10) - the actual log message
... but that will not happen yet because there is still one major flaw in the way the logger code in the java classes above has been written!

The code needs to be like this:
  • SomeInterface
    • AbstractImpl
      protected Logger logger = null;
      • ConcreteImpl_A
        private static final Logger myLogger = Logger.getLogger(ConcreteImpl_A.class)
        public ConcreteImpl_A() {
        super();
        super.logger = myLogger;
        }
      • ConcreteImpl_B
        private static final Logger myLogger = Logger.getLogger(ConcreteImpl_B.class)
        public ConcreteImpl_B() {
        super();
        super.logger = myLogger;
        }

Wednesday, March 16, 2011

Running external commands from Java

I am not a big fan of Runtime.exec for running commands via Java because there are so many fine points to take into account that running one or two simple commands requires the creation of an entire robust ecosystem. And if I ever have to repeat the process in a different codebase then writing the code again from scratch is very cumbersome.

One fine day I said to myself: Someone's got to have already written and shared these fail-safes in open-source ... right?

My search led me to commons-exec and I was thrilled! The apache website tutorial is not very enlightening about the API itself. Instead, it is this blog entry that fully allows one to understand and utilize the power of commons-exec. But an example of how to capture user-input using commons-exec is still missing from the web.

Also I ran across a library provided by Maven as part of their cookbook for maven plugin developers. I haven't experimented with it enough to talk about it but its out there.

Wednesday, November 17, 2010

Caveats of converting images from GIF to JPG using Java

Java has come so far that we expect it to be mature enough and handle any possible use-cases such as a simple GIF to JPG image conversion without any hiccups. But when converting GIFs which happen to have an alpha (transparency) property about them, the results of the conversion seem less than appealing.

To the layman (myself included) who knows nothing of alpha or transparencies, the impression the resulting image leaves is often described as:
  1. some how the colors have been inverted or reversed
  2. feels like you are looking at an image in a film roll
  3. everything seems to have had its black & white colors somehow switched about
These impressions make for a very difficult google search but when you do get the search words right (transparent gif jpeg alpha convert) you should hopefully end up at a post similar to this one which educates us about what is really going on and that there is much more to still look forward to from Java.

Saturday, November 6, 2010

Send different logs to separate files in Tomcat with log4j

Everyone who works with web applications must have at least once wished for separating out his/her log files. It is painful to scan for infomation when multiple threads are dumping information from all over. I'm sure that all the great admins who watch over production or staging systems must quickly learn to use tools that allow them to set up rules and get a clean view of what they need but developers tend to be a more lethargic breed.

I finally decided to dig though the web and put this extremely basic skill into my bag of known tricks.
  1. If you use log4j, do not waste your time reading the instructions for JULI when you land on the page in Tomcat's documentation which talks about logging.properties file etc.
  2. Everything that you need to do in order to send the logs to a separate file can be done in log4j.properties.
    • Unless you are looking to do something really advanced, in which case you should use log4j.xml file.
    • You can read more about that in this Log4j tutorial with Tomcat examples.
  3. Here's the basic blurb (+/-) that you can throw in with minimal edits to get the job done.
    ##
    # Name your appender whatever you want, and choose whatever
    # implementation makes most sense for you.
    ##
    log4j.appender.yourAppenderNameGoesHere=org.apache.log4j.RollingFileAppender
    ##
    # You will most likely want to place the log file in a known location.
    # Leverage ${catalina.base}/logs/yourFilename.log to accomplish this.
    ##
    log4j.appender.yourAppenderNameGoesHere.File=${catalina.base}/logs/yourFileName.log
    ##
    # The rest is generic stuff which you can tweak as you please.
    ##
    log4j.appender.yourAppenderNameGoesHere.MaxFileSize=2MB
    log4j.appender.yourAppenderNameGoesHere.MaxBackupIndex=10
    log4j.appender.yourAppenderNameGoesHere.layout=org.apache.log4j.PatternLayout
    log4j.appender.yourAppenderNameGoesHere.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %5p [%t] (%F:%L) - %m%n
  4. Use this blurb to direct the output from a particular package or a class to the appender you have created for the new separate file.
    # Redirect the logs from an entire package
    log4j.logger.com.my.packageName=ERROR, yourAppenderNameGoesHere
    # Redirect logs from only a specific class
    log4j.logger.com.my.packageName.MyClass=DEBUG, yourAppenderNameGoesHere
    # Set the additivity flag to false if you do NOT want the logs to show up redundantly in log files that the parent loggers point to
    log4j.additivity.com.my.packageName=false
    log4j.additivity.com.my.packageName.MyClass=false
  5. By the way, do NOT make the mistake of putting the name of your appender as one of the values in the following line of your log4j.properties file.
    # don't change this
    log4j.rootLogger=INFO, blah, blah, yourAppenderNameGoesHere

Sunday, October 31, 2010

How to list multiple encrypted passwords in properties files

Jasypt is an extremely useful toolkit for encrypting and decrypting passwords. It provides simple instructions for those who want to use Spring and load properties files with encrypted passwords in them.

But, what if you need to provide a whole series of usernames and passwords. How would you accomplish this?
Jasypt's out-of-the-box implementations only read one encrypted value per key=ENC(value) pair in a property file.

Here's a solution:
  1. Override the EncryptablePropertyPlaceholderConfigurer's convertPropertyValue() method. Then you can split a list like the following:
    listOfUsernamePasswords=LIST(username1,ENC(encryptedPassword1),username2,ENC(encryptedPassword2))
    into separate values and only send the encrypted values to the parent convertPropertyValue() implementation to get the decrypted values.
  2. Sew the list back together as a string and return a value that now reads:
    username1,password1,username2,password2
  3. You may be wondering as to who will do the work of breaking up these comma-separated values when they get to your spring bean? The answer is simple: Spring will! For ex: If you had configured you spring bean like so:
    <bean id="someBean" class="com.MyBean">
        <property name="multipleUsernamePasswords" value="${listOfUsernamePasswords}" />
    </bean>
    and the multipleUsernamePasswords property is of type String[] in MyBean class, then StringArrayPropertyEditor will be used implicitly, which will break it up into a string array auto-magically. If you are interested, you can read this blog about how various structures interpret property values for Spring.

  4. Now its up to use that String[] to your advantage in your code.

Saturday, June 12, 2010

Multiple Row Filters for JTable

When using the JTable from Java's swing UI, one might often come across a requirement when data filters need to be combined to offer results from searching multiple columns ... the Java Tutorials cover the simple stuff but they don't talk about combining filters! What to do? You can just hit the javadocs and put the pieces together OR after you've read the simple stuff, just try this and it should work like magic:

RowFilter<TableModel, Object> firstFiler = null;
RowFilter<TableModel, Object> secondFilter = null;
List<RowFilter<TableModel,Object>> filters = new ArrayList<RowFilter<TableModel,Object>>();
RowFilter<TableModel, Object> compoundRowFilter = null;
try {
    firstFiler = RowFilter.regexFilter(yourRegexString, columnIndex);
    secondFilter = RowFilter.regexFilter(yourRegexString, columnIndex);
    filters.add(firstFiler);
    filters.add(secondFilter);
    compoundRowFilter = RowFilter.andFilter(filters); // you may also choose the OR filter
} catch (java.util.regex.PatternSyntaxException e) {
    return;
}
sorter.setRowFilter(compoundRowFilter);
Easy Huh?

Wednesday, June 9, 2010

Ramp Up on Java

When I decided to take my SJCP exam, I choose this book as my "blind date" ... and after I finished reading it cover-to-cover, I felt that there couldn't possibly have been a better choice. It was amusing, engaging and insightful ... all the things I wouldn't expect from a book preparing me for what I thought was a run-of-the-mill test.

If you decide to ahead with taking the SCJP exam then (a) expect satire from your co-workers, (b) a tip-of-the-hat from your manager and friends, and finally (c) extra meaningless hits from recruiters assuring you that you're qualified for some position but have no idea what the project is about.

Ah! But most importantly, if you love java, expect to feel smarter and blissfully satisfied =)

Anyway hats off to the folks who put the book together ... Now, without any claims of any ties to them, this blog posting is my meager attempt at putting together a quick review.


  1. What is an Interface? It is a contract which the classes implementing it must abide by.
  2. What is an Abstract Class? It is a class with the abstract modifier placed before it. Any other class which inherits from an abstract class must provide implementations for its methods. Or Else? The code will not compile.
  3. Can a regular class have abstract methods? No, the class must be an abstract class to define abstract methods.
  4. Does having abstract methods make a regular class abstract? Stupid question, given what we just established.
  5. Are all the methods inside an abstract class considered abstract by default? No, they need to be explicitly marked as abstract.
  6. Why would you use an abstract class? Unlike an Interface whose methods cannot have a body defined for its methods, abstract classes allow you to have non-abstract methods which can provide default functionality for its child classes to inherit while providing specific implementations of their own for the abstract methods of their parent. In such a use case an abstract class can be useful.
  7. What has higher visibility? package or protected? The protected level access provides higher visibility.
  8. Does the order in which exceptions are caught in a try-catch block matter? Yes it does. You can't even compile code where a more specific exception gets caught after a more generic one ... because then that piece of code is unreachable which is not something that any compiler would look down upon kindly.
  9. What method allows a thread to give up control of the current synchronized context/object/monitor immediately? The wait() method.
  10. What about notify() or notifyAll()? Regardless of which line they are placed on inside the synchronized block, these methods run/take-effect after the rest of the code in the sync-block has finished executing.
  11. Can the notifyAll() method control the order in which the waiting candidates get notified? Nope.
  12. What is the significance of a final class? It cannot be extended.
  13. What is the significance of a final method? It cannot be overriden in a child class.
  14. What is the significance of a final variable? The reference cannot be changed after it is set.
  15. Can an anonymous class be declared as both extending a class and implementing an interface? Nope, it can only do one of the two at a time.
  16. What is the finalize() method all about? This method is guaranteed to be called once by Java's GC at least, after it determines that an object has no more active references left.
  17. What would be one reason for avoiding the use of the finalize() method all together? Since this method is called only once ... for an object that already had it called once but did not ultimately get garbage collected for some reason ... there is no guarantee that this method will be visited again the next time the GC decides to consider that object for recycling. So relying on this method for some sort of predictable behavior would be ill advised.
  18. What are the different generations of the GC? Basically there are: young, tenured and permanent generations. They are just memory pools holding objects of different ages. Garbage collection occurs in each generation when the generation fills up.
  19. What is the scope/monitor of a static sync method? It locks-on/monitors the class.
  20. Can a static sync method and a non-static sync method butt-heads for locks? No ... one locks the class itself object whereas the other locks an instance object.
  21. Which collection would you use for unique entries? Any implementation of Set.
  22. What is a good collection for only inserting/appending tons of data? Think about ArrayList vs LinkedList?
  23. What about retrieval? Hmm ... HashMap?
  24. What does the join() method do? It puts the current thread in a blocking-mode where it waits for the other thread ... on which the join was invoked ... to finish running.
  25. What is the purpose of WeakReference
  26. What is a ReentrantLock all about?
  27. What are class loaders all about? link1 link2
  28. What is the difference between Enumerators and Iterators?
  29. What happens if a thread is using an iterator and another one tries to insert into the underlying list? ConcurrentModificationException should be thrown.
  30. If a thread t locks a particular monitor multiple times ... will an unlock reverse the effect of all the lock operations? No ... each unlock reverses the effect of one lock operation.
  31. Can elements be removed while traversing a list via an iterator in a single threaded environment? Yes, the remove() method guarantees safe-same-thread deletion.
  32. Can the remove() method be used safely with the new for-loop style introduced in Java 5? Nope.
  33. Why are thread pools useful? A common type of thread pool where we have a fixed number of threads running allows application to degrade gracefully. Rather than try to do much and crashing ... an application can service the fixed/maximum requests that its hardware can handle/sustain in a predictable fashion.
  34. What is the purpose of the volatile keyword? It is similar to asking the Java runtime to provide a guarantee that all the reads on the given variable are synchronized by forcing the threads to always read-from/stay-in-sync-with the master copy. Reads and writes are atomic for all variables declared volatile. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
  35. What is the ideal # of threads that should be used on a machine with N cores? Umm...(n+1)/2 ?
  36. How do too many threads adversely affect a CPU intensive system? The context switching causes the thread-data to be loaded in & out of the chip level cache, this is an expensive overhead for hardware which is build around the precept of optimizing execution by retaining data in the chip level cache for the longest period possible.
  37. If the hashCode() and equals() methods are implemented properly for a given class, when can the equals() method return false even though the two objects being compared are equal? This happens when the classloaders for the two objects are different. For example: (a) in application servers, different application contexts (WARs) get their own separate classloaders, (b) two different classloaders can be in use for applications using RMI ... not so sure about this one ...
  38. How would you design your own GC in a language that had only objects? And how would you locate circular dependencies or islands?
  39. What happens when java classes are loaded into JVM? What is Java class file's magic number?