13/05/2012

Convert Java bean to Map using Groovy

Persisting java bean into MongoDB, means that you have to create a DBObject.
The easiest way to do it is to implement for each bean you want to persist a kind of mapper that will populate the DBObject adding all the bean's fields you want to persist.
But, what if you would to have something more general ? Well the answer seems to be relatively simple: transform the bean into a Map, then new BasicDBObject(map), done! Ok, have you tried to transform a java bean into a LinkedHashMap ?
If you google for it, you will find tons of java libraries that do all kind of bean to bean mapping, reflection and all sort of bean utils! But nothing really simple like BeanUtils.toMap(bean).

So here a very simple Groovy script that will achieve the task :

 def Map toMap(object) { return object?.properties.findAll{ (it.key != 'class') }.collectEntries {
           it.value == null || it.value instanceof Serializable ? [it.key, it.value] : [it.key, toMap(it.value)]
     }
 }

and back to bean :


def toObject(map, obj) {
  map.each {
       def field = obj.class.getDeclaredField(it.key)
       if (it.value != null) {
            if (field.getType().equals(it.value.class)){
               obj."$it.key" = it.value
            }else if (it.value instanceof Map){
               def objectFieldValue = obj."$it.key"
              def fieldValue = (objectFieldValue == null) ? field.getType().newInstance() : objectFieldValue
              obj."$it.key" = toObject(it.value,fieldValue) 
            }
         }
      }
   return obj;
}

18/03/2012

Spring + JUnit + RestTemplate + Jetty + Jersey

After a whole day spent struggling, finally I managed to make it work. Now I can easily test my rest services.


@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class UserResourceTest {
 
 @Autowired RestTemplate restTemplate;

 @BeforeClass
 static public void setUp() throws Exception {
  Server server = new Server(8080);
  ServletContextHandler resource = new ServletContextHandler(ServletContextHandler.SESSIONS);

  resource.setContextPath("/");

  resource.getInitParams().put("contextConfigLocation", "classpath:applicationContext.xml");

  ServletHolder servletDef = new ServletHolder(SpringServlet.class);
  servletDef.setInitParameter("com.sun.jersey.config.property.packages","org.codehaus.jackson.jaxrs");
  resource.addServlet(servletDef, "/*");

  resource.addEventListener(new ContextLoaderListener());
  resource.addEventListener(new RequestContextListener());

  server.setHandler(resource);
  server.setStopAtShutdown(true);
  server.start();    
 }

 @Test
 public void test_rest_crud() throws Exception {
  Object users = restTemplate.getForObject("http://localhost:8080/users", Object.class);
  Assert.assertNotNull(users); 
 }

}

03/03/2010

Replace string occurrences recursively

I am so proud of my first post :) . I know that is not such a very big and interesting contribute (also because you can find it just googling) but let's say that I have a very bad memory and I am pretty sure that I will need this ONE precious line of perl/bash script in the future. At that time I won't spend any time googling again for it.

Replace all the occurrences of "apple" with "banana" in all the files found recursively from the current folder.

perl -p -i -e "s/apple/banana/g" `find . -name * `

Thanks to : http://joseph.randomnetworks.com/2005/08/18/perl-oneliner-recursive-search-and-replace/