Skip to main content

Posts

Showing posts with the label Java

Tests your logs using logback

You want to test what your application logging and you don't know how to do that in simplest manner, well we've logback to rescue. (If your using slf4j but with other than logback as a implementation, then you have to add logback as a test dependency with logback.xml in src/test/resources) One (not exactly) caveat is that, for testing logs using logback we need to use Mockito for creating mock Appnder and asserting for the exact log string in argument. Here is the actual code- 1. Create a base test class for log testing. public abstract class BaseLoggerTest { final Appender mockAppender = mock(Appender.class); @Before public void setup() { when(mockAppender.getName()).thenReturn("MOCK"); (ch.qos.logback.classic.Logger)LoggerFactory .getLogger(ACCESS_LOGGER_NAME)) .addAppender(mockAppender); } protected void verifyLog(final String expectedLog, final Level level) { verify(mockAppender, atLeastOnce()) ...

How to test objects equality if they don't implement Object#equals()

Problem: There are cases when you want to test whether two objects are equal, mean did they contain same state or not ? This occurs mostly when you're trying to test JAXB generated beans or any VO/DTO which doesn’t' implement Object#equals() method or/and whose source code you can't modify . Solution: I knew there is a class (Commons lib's EqualsBuilder class) available which "reflectively" creates the equals method for you taking care all the rules for writing good equals method. But that class doesn’t have a method to test whether two object are equal or not. At back of my mind, I know Mockito library internally uses the same commons class to solve my problem. I quickly scan the mockito jar and found this class. Here is the code snippet for the same (please note, you have to add mockito jar on classpath for this) import org.mockito.internal.matchers.apachecommons.ReflectionEquals; . . . public <T> void assertObjectEquals(final T expected, final T...

VM arguments in spring context

In case you trying to access the VM arguments in spring application context, then just add the below bean definition in context file: <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true"></property> </bean> And access the VM args as ${vm_property}, e.g if you passed the –Dfoo=bar, which can be access as, <bean class="com.company.test.MyClazz"> <property name="myProperty" value="${foo}"></property> </bean>

What I've learned from TDD

TDD, I'm practicing development using unit test from 1 year now and frankly speaking I'm loving it. I listed some points/notes/importance I learned from TDD. You might like to add some points or want to correct me, so please comment. Here the list goes: Caught 80% of bugs at first place before your code goes to production. Explore and forces to think the development and design in proper Object Oriented way, means less class dependencies, loose coupling's, SRP etc. You can fearlessly do refactoring and enhance the quality of existing code if you have enough unit test code surrounding. If you have been reported any bug/issue in production code, write the unit test that produce that bug and fail(red), then fix the code(refactor) and ultimately make the unit test to success( green). Gives idea about the usage of API you're developing. I know this are not the only points which make TDD incredibly great practice, but I'll update this blog for some more points as...

Read file outside the JAR

Hi All, I’m back from loooong vacation. Actually haven’t done anything great to blog about, only update is, I switched the company… Here is recent Java trick I found and I think I should share it.. Problem: I’m wondering about how can I read the file which is in the same directory of my executable JAR ? [Edited: Read the comment to get easy and obvious answer :)] Solution: Its simple, just get the current directory and append the file you want to access whose path is relevant to the JAR. Like /mydir/Myjar.jar /mydir/my.properties In order to read the “my.properties”, I just used the following code. FileReader reader = new FileReader(new File(new File(“.”), “my.properties”)); Simple.

Easy Start with JNA

JNA (Java Native Access) is the good and easy answer to the JNI(Java Native Interface). Those who find it cumbersome to to call C, C++ DLL functions using JNI, then JNA is for you. The project is hosted at https://jna.dev.java.net/ . Here is my first encounter(experiment) with the JNA. Problem: I want to call one DLL function in Java program Solution: The first thing that comes into my mind is JNI, coz I heard a lot about it whenever something "native" has to be called in Java. Just while surfing for the more information on basic JNI programming, I came across the JNA project/api and find it interesting to give it try. Here are the basic two things you need to have in order to use JNA 1) JNA api JAR file (jna.jar): Download it from here 2) DLL which you want to call in your Java program Now this may be the big thing for a guy who haven't worked on VC++, DLL, MFC etc things. So here is the quick link about how to create the DLL http://www.icynorth.com/development/createdl...

Java Generics: Why I get "name clash" exception when I override methods with different "type" parameter ?

import java.util.*; class Parent { void foo(List<String> list) { System.out.println("parent"); } } class Child extends Parent { void foo(List<Integer> list) { System.out.println("child"); } } When you compile this code you will get an error like Parent.java:7: name clash: foo(java.util.List<java.lang.Integer>) in Child and foo(java.util.List<java.lang.String>) in Parent have the same erasure, yet neither overrides the other class Child extends Parent { ^ 1 error This "name clash" error thrown because of "type erasure" thing when "generics" code gets complied. Let’s see how, When we complied any generics code, the compiler removes the type from the code and treat it as a simple pre Java 1.5 code, like, in our case, compiler saw something like this, import java.util.*; class Parent { void foo(List list) { // oops, <String> get erased. System.out.println("parent"); } } class Child extend...

Job storage in Quartz using Files, A FileJobStore Class

Quartz supports mainly two types of Job Storage for Scheduler information. • Memory (non persistent) storage The memory job storage facility for Quartz is provided by a class called org.quartz.simpl.RAMJobStore , The RAMJobStore is the default, i.e unless you change the configuration, and this is the JobStore that will be used for any Quartz application. Using this JobStore has some advantage 1. Easy to configure, because already configured by Scheduler as a default 2. It’s fast - a plain old simple memory access But, as a computer memory is volatile, when your Quartz application is stopped, it releases the memory back to the operating system. Of course, along with everything else stored in that released memory is the scheduling information. • Persistent storage Second is using database for Job storage which implements JobStoreSupport abstract class Quartz offers two different types of concrete persistent JobStores, each one designed for a specific database environment and co...