Sunday, December 26, 2010

How to Dump/Inspect Object or Variable in Java

Scala (console) has a very useful feature to inspect or dump variables / object values :

scala> def b = Map("name" -> "Yudha", "age" -> 27)
b: scala.collection.immutable.Map[java.lang.String,Any]

scala> b
res1: scala.collection.immutable.Map[java.lang.String,Any] = Map((name,Yudha), (age,27))

Inside our application, especially in Java programming language (although the techniques below obviously works with any JVM language like Scala and Groovy) sometimes we want to inspect/dump the content of an object/value. Probably for debugging or logging purposes.

My two favorite techniques is just to serialize the Java object to JSON and/or XML. An added benefit is that it's possible to deserialize the dumped object representation back to an actual object if you want.

JSON Serialization with Jackson

Depend on Jackson (using Maven):
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.6.3</version>
</dependency>
Then use it:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

..
Logger logger = LoggerFactory.getLogger(getClass());

@Test
public void level() throws ServiceException, JsonGenerationException, JsonMappingException, IOException {
MagentoServiceLocator locator = new MagentoServiceLocator();
Mage_Api_Model_Server_HandlerPortType port = locator.getMage_Api_Model_Server_HandlerPort();
String sessionId = port.login("...", "...");
logger.info(String.format("Session ID = %s", sessionId));
Map[] categories = (Map[]) port.call(sessionId, "catalog_category.level", new Object[] { null, null, 2 } );
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
logger.info( mapper.writeValueAsString(categories) );
}

Example output :

6883 [main] INFO id.co.bippo.shop.magentoclient.AppTest - [ {
  "position" : "1",
  "level" : "2",
  "is_active" : "1",
  "name" : "Gamis",
  "category_id" : "3",
  "parent_id" : 2
}, {
  "position" : "2",
  "level" : "2",
  "is_active" : "1",
  "name" : "Celana",
  "category_id" : "5",
  "parent_id" : 2
} ]

XML Serialization with XStream

As a pre-note, XStream can also handle JSON with either Jettison or its own JSON driver, however people usually prefer Jackson than XStream for JSON serialization.

Maven dependency for XStream:
<dependency>
<groupId>xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.2.2</version>
</dependency>
Use it:
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Map;

import javax.xml.rpc.ServiceException;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
...
@Test
public void infoXml() throws ServiceException, RemoteException {
MagentoServiceLocator locator = new MagentoServiceLocator();
Mage_Api_Model_Server_HandlerPortType port = locator.getMage_Api_Model_Server_HandlerPort();
String sessionId = port.login("...", "...");
logger.info(String.format("Session ID = %s", sessionId));
Map category = (Map) port.call(sessionId, "catalog_category.info",
new Object[] { 3 } );
XStream xstream = new XStream();
logger.info( xstream.toXML(category) );
}

Sample output:

5949 [main] INFO id.co.bippo.shop.magentoclient.AppTest - <map>
  <entry>
    <string>position</string>
    <string>1</string>
  </entry>
  <entry>
    <string>custom_design</string>
    <string></string>
  </entry>
  <entry>
    <string>custom_use_parent_settings</string>
    <string>0</string>
  </entry>
  <entry>
    <string>custom_layout_update</string>
    <string></string>
  </entry>
  <entry>
    <string>include_in_menu</string>
    <string>1</string>
  </entry>
  <entry>
    <string>custom_apply_to_products</string>
    <string>0</string>
  </entry>
  <entry>
    <string>meta_keywords</string>
    <string>gamis, busana muslim</string>
  </entry>
  <entry>
    <string>available_sort_by</string>
    <string></string>
  </entry>
  <entry>
    <string>url_path</string>
    <string>gamis.html</string>
  </entry>
  <entry>
    <string>children</string>
    <string></string>
  </entry>
  <entry>
    <string>landing_page</string>
    <null/>
  </entry>
  <entry>
    <string>display_mode</string>
    <string>PRODUCTS</string>
  </entry>
  <entry>
    <string>level</string>
    <string>2</string>
  </entry>
  <entry>
    <string>description</string>
    <string>Gamis untuk muslimah</string>
  </entry>
  <entry>
    <string>name</string>
    <string>Gamis</string>
  </entry>
  <entry>
    <string>path</string>
    <string>1/2/3</string>
  </entry>
  <entry>
    <string>created_at</string>
    <string>2010-12-24 11:37:41</string>
  </entry>
  <entry>
    <string>children_count</string>
    <string>0</string>
  </entry>
  <entry>
    <string>is_anchor</string>
    <string>1</string>
  </entry>
  <entry>
    <string>url_key</string>
    <string>gamis</string>
  </entry>
  <entry>
    <string>parent_id</string>
    <int>2</int>
  </entry>
  <entry>
    <string>filter_price_range</string>
    <null/>
  </entry>
  <entry>
    <string>all_children</string>
    <string>3</string>
  </entry>
  <entry>
    <string>is_active</string>
    <string>1</string>
  </entry>
  <entry>
    <string>page_layout</string>
    <string></string>
  </entry>
  <entry>
    <string>image</string>
    <null/>
  </entry>
  <entry>
    <string>category_id</string>
    <string>3</string>
  </entry>
  <entry>
    <string>default_sort_by</string>
    <null/>
  </entry>
  <entry>
    <string>custom_design_from</string>
    <null/>
  </entry>
  <entry>
    <string>updated_at</string>
    <string>2010-12-24 11:37:41</string>
  </entry>
  <entry>
    <string>meta_description</string>
    <string>Jual baju gamis untuk muslim</string>
  </entry>
  <entry>
    <string>custom_design_to</string>
    <null/>
  </entry>
  <entry>
    <string>path_in_store</string>
    <null/>
  </entry>
  <entry>
    <string>meta_title</string>
    <string>Gamis</string>
  </entry>
  <entry>
    <string>increment_id</string>
    <null/>
  </entry>
</map>

Which one is better?

I personally prefer JSON, but fortunately, you always have a choice. :-)

25 comments:

Yudha F said...

waw.. nyambungnya cuman dikit.. ga ngertinya banyak he..

Javin @ Tibco RV Tutorial said...

Hi,

Just to add while writing Serializable class , its good practice to put a Seriazlizable alert in file so that when some one else add a new field in the class he must ensure that field is either transient or Serializable , so that Serializability of class should not break.

Thanks
Javin
Why String is immutable in Java

asray said...

thx infonya sangat membantu
gamis murah

ADmin said...

And since March 2011, there is currently the included www.bestcustomessay.org layer of recuperation from the Great Tohoku Earthquake.

jena grey said...

I like your post, the fact that your site is a little bit different makes it so interesting, I get sick up seeing the same old boring recycled stuff all of the time, exam dumps, We are a group of experienced experts that bring hope in passing major certification exams. All the way through training with our study materials, anyone will get an understanding about major points. WE guarantee that if you study our exam dumps, you will surely achieve something in the examinations.

certification study guide said...

Thanks for an insightful post. These comments are really helpful. I found a lot of useful tips from this post. 74-343, 74-344, LOT-403 and more detail.

colaveri d said...

I was very encouraged to find this site. I wanted to thank you for this special read.
pakistani matrimony | pakistani matrimonial | pakistani matrimonial sites | pakistani dating

colaveri d said...

Wonderful story, reckoned we could combine several unrelated data, nevertheless really really worth taking a look
Imported Cars in Pakistan | Used Toyota Invincible in Pakistan | Used Lexus in Pakistan | Used Toyota Pirus in Pakistan

blaircraig said...

You got a really useful blog. I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.
Advertising agencies in lahore | furniture | advertising agencies in Pakistan

Nick Damron said...

Excellent read, I just passed this onto a colleague who was doing a little research on this topic.
Advertising agencies | Office furniture catalogue | Advertising agency

devindennis said...

It’s really a great post..I would like to appreciate your work and I am going to recommend it to my friends. Thanks for sharing.
Advertising agencies in karachi | Cheap office furniture | Advertising agencies in Islamabad

China tours said...

Congratulations for this wonderful reading article. I found it very informative and interesting too, I think you are a brilliant writer. I have bookmarked your blog and will return in the future. I want to encourage you to continue that marvelous work, have a great daytime!I am a china tour lover,You can learn more: Beijing tour packages | travel to guide | Lhasa Tourist Attractions

deven zar said...

Excellent post. I really appreciate you for doing this job... keeps it up so i can do comments on your post. Thanks :) –
http://www.chansports.com

deven zar said...

Really your blog is very interesting.... it contains great and unique information. I enjoyed to visiting your blog. It's just amazing.... Thanks very much for the share
Nfl Free Stream Online | Nhl Free Stream Online | football free stream online | Nba Free Stream Online

Anonymous said...

"Really awesome work with the blog. I do like your hard work on and will wait for more post as from you as post gave me pleasure and gives some helps to do same work right here. Thanks a lot……………"www.learniteducationservices.com |

www.feshionhouse.com |

www.homesbymaryanngraboyes.com |

www.immigration-lawyer-utah.com |

www.sportsautoplex.com |

www.orangebeachcomputerrepair.com |

polo outlet said...

http://www.burbagssale2014.com/ Burberry Outlet
http://www.airmaxshoesfactory.com/ Air Max Shoes
http://www.coachblackfriday2014.com/ Coach Black Friday
http://www.coach-storeoutletonline.com/ Coach Black Friday
http://www.coachcoachoutlet.com/ Coach Cyber Monday
http://www.coachxfactory.com/ Coach Factory
http://www.coach-factoryoutletonline.net/ Coach Outlet Factory
http://www.coach-outletonlineusa.com/ Coach Outlet USA
http://www.coach-pursesfactory.com/ Coach Purses Factory
http://www.coachpurseusa.com/ Coach Purses USA
http://www.coach-storeoutlet.com/ Coach Store Outlet
http://www.coach-pursesonline.com/ Coach Purses On Sale
http://www.monsterbeatsbydres.com/ Monster Beats Outlet
http://www.louis-vuittonblackfriday.com/ Louis Vuitton Outlet
http://www.lv-guccishoesfactory.com/ Louis Vuitton Factory
http://www.marcjacobsonsale.com/ Marc Jacobs On Sale
http://www.mcmworldwides.com/ MCM Outlet
http://www.mcmoutlet-jp.com/ MCM 店铺
http://www.oakleysunglassesfactory.com/ cheap oakley sunglasses
http://www.michaelkorsmas.com/ Michael Kors Outlet
http://www.michaelkors.so/ Michael Kors Outlet
http://www.michaelkorsfactory-store.com/ Michael Kors Factory
http://www.michaelkorsoutletr.com/ Michael Kors Outlet
http://www.michael-korsfactoryonline.com/ Michael Kors Factory Online
http://www.newcoachfactoryoutlet.com/ Coach Factory Outlet
http://www.north-faceoutletonlines.net/ North Face Outlet Online
http://www.polo-outletstore.com/ Polo Outlet Store
http://www.ralph-laurenhome.com/ Ralph Lauren UK
http://www.saclongchamppairs.com/ Sac Longchamp Pairs
http://www.tcoachoutletonline.com/ Coach Outlet Online
http://www.the-coachfactoryoutlet.com/ Coach Factory Oultet
http://www.barbour-jacketsoutlet.com/ Barbour Jackets Outlet Online
http://www.canada-gooser.com/ Canada Goose Outlet
http://www.guccishoesuk-2014.com/ Gucci Outlet Online
http://www.michaelkorsstates.com/ Michael Kors Outlet
http://www.moncler-clearance.com/ Moncler Clearance
http://www.moncler-jacketsoutletonline.com/ Moncler Jackets Outlet Online
http://www.northsclearance.com/ North Clearace Outlet
http://www.polo-ralphlaurenonline.com/ Polo Ralph Lauren Outlet Online
http://www.woolrich-clearance.com/ Woolrich Clearance
http://www.cvshopfactory.com/ shop.coachfactory.com
http://www.mksfactoryoutlet.com/ Michael Kors Factory Outlet
http://www.zxcoachoutlet.com/ Coach Outlet Online USA
http://www.thebeatsbydre.net/ Beats by Dre
http://www.superbagsmarket.com/
http://www.newoutletonlinemall.com/ Coach Purses Outlet Online
http://www.clickmichaelkors.com/ Michael Kors USA

Metamorfosis said...

Pelatihan SDM is network marketing and training information or training an employee who has worked with many consulting firms and training institutions.
pelatihan hrd, pelatihan pengembangan diri, pendidikan dan pelatihan sdm, pelatihan akuntansi keuangan, pelatihan sales marketing, pelatihan kehumasan, pelatihan sdm jogja, lembaga pelatihan sdm, pelatihan manajemen bisnis, pelatihan administrasi perkantoran, lembaga training motivasi, pelatihan sekretaris, pelatihan karyawan, lembaga training di jogja, pelatihan in house training, pelatihan public training, jasa konsultan, pelatihan pengembangan sdm, pelatihan manajemen sdm, program training karyawan, diklat sdm, program training sdm, pelatihan sdm rumah sakit, pelatihan sdm untuk rumah sakit, _____ id card murah, harga id card, cetak kartu santri, produksi id card, bikin id card, cetak id card jogja, id card murah jogja, cetak id card, percetakan id card, pabrik id card, cetak member card, cetak kartu pelajar,

Learn Chinese language on hanbridgemandarin said...

Hanbridge offers a range of language learning programs from beginner to advanced . These programs are designed to arm you with basic linguistic competency up to full fluency in Mandarin Chinese. To ensure relevancy, Hanbridge will tailor our courses to meet your particular needs and to help you flourish in your daily life in China.



More Chinese learning tags : Chinese language class | Chinese language course | Study Chinese

Sonam Jaan said...

Indian Escorts in Dubai +971552300726 Top Escorts Dubai have Lot of Indian Model escorts in Dubai & Student Escorts in Dubai Indian Escorts Perfect Match for your Romantic Meting.

TOPESCORTSDUBAI said...
This comment has been removed by the author.
Eric Simmons said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Java Course in Chennai

oakleyses said...

burberry handbags, prada outlet, ray ban sunglasses, gucci handbags, tiffany and co, louis vuitton, christian louboutin outlet, christian louboutin uk, tory burch outlet, ray ban sunglasses, polo ralph lauren outlet online, louis vuitton outlet, jordan shoes, michael kors outlet online, nike air max, christian louboutin, ray ban sunglasses, louis vuitton outlet, longchamp outlet, prada handbags, michael kors outlet online, uggs outlet, christian louboutin shoes, uggs on sale, ugg boots, louis vuitton outlet, chanel handbags, longchamp outlet, oakley sunglasses, nike outlet, louis vuitton, uggs outlet, polo outlet, michael kors outlet, burberry outlet, tiffany jewelry, michael kors outlet online, oakley sunglasses, nike air max, ugg boots, michael kors outlet online, oakley sunglasses, replica watches, nike free, michael kors outlet, replica watches, longchamp outlet, kate spade outlet

oakleyses said...

sac vanessa bruno, hollister uk, polo lacoste, vans pas cher, nike roshe run uk, nike free uk, true religion outlet, air max, polo ralph lauren, coach purses, louboutin pas cher, hollister pas cher, kate spade, lululemon canada, timberland pas cher, michael kors outlet, sac longchamp pas cher, michael kors pas cher, ray ban pas cher, true religion outlet, abercrombie and fitch uk, nike air max uk, replica handbags, nike air max uk, nike blazer pas cher, coach outlet, nike roshe, michael kors, mulberry uk, coach outlet store online, burberry pas cher, guess pas cher, nike air max, sac hermes, michael kors, north face uk, hogan outlet, north face, converse pas cher, oakley pas cher, ralph lauren uk, true religion outlet, new balance, jordan pas cher, nike free run, nike tn, longchamp pas cher, true religion jeans, nike air force, ray ban uk

oakleyses said...

hollister, north face outlet, mac cosmetics, baseball bats, nike huaraches, babyliss, new balance shoes, iphone cases, chi flat iron, louboutin, ferragamo shoes, iphone 5s cases, longchamp uk, soccer shoes, mcm handbags, nike roshe run, timberland boots, mont blanc pens, vans outlet, bottega veneta, instyler, oakley, ralph lauren, valentino shoes, giuseppe zanotti outlet, s6 case, p90x workout, celine handbags, iphone 6s plus cases, herve leger, north face outlet, nike trainers uk, ipad cases, iphone 6s cases, lululemon, wedding dresses, nike air max, abercrombie and fitch, nfl jerseys, hermes belt, insanity workout, ghd hair, asics running shoes, beats by dre, iphone 6 cases, reebok outlet, jimmy choo outlet, soccer jerseys, hollister clothing, iphone 6 plus cases

oakleyses said...

pandora jewelry, canada goose uk, canada goose, barbour, moncler, karen millen uk, swarovski crystal, replica watches, louis vuitton, canada goose, louis vuitton, juicy couture outlet, nike air max, lancel, swarovski, canada goose jackets, gucci, converse, thomas sabo, canada goose outlet, pandora charms, ugg,uggs,uggs canada, juicy couture outlet, doudoune moncler, hollister, moncler, montre pas cher, coach outlet, links of london, hollister, ugg uk, ugg, toms shoes, marc jacobs, pandora uk, vans, canada goose, moncler, canada goose outlet, moncler outlet, moncler outlet, louis vuitton, moncler, ray ban, louis vuitton, louis vuitton, converse outlet, moncler uk, ugg,ugg australia,ugg italia, supra shoes, barbour uk

Post a Comment

 
Copyright 2009 Spring vs Java EE Web Dev. Powered by Blogger Blogger Templates create by Deluxe Templates. WP by Masterplan