Posts tagged as:
httpclient
Daily del.icio.us for March 22nd through March 25th
- SaveTheDevelopers.org :: Making The Web A Better Place - Say no to IE 6! Our current campaign focuses on assisting users in upgrading their Internet Explorer 6 web browser. This campaign will result in former IE 6 users having a more enjoyable experience on the web while (hopefully) creating a less stressful an
- Save the Developers! Stop Using Internet Explorer 6 - There is a scourge on the Web. It is called Internet Explorer 6. Even though IE7 has been around for more than two years, IE6 still represents 31% of all browsers out there (versus only 22 % for IE7 and 36.5 % for Firefox).
- Amazon's cloud computing service fuels startup's launch | InfoWorld | News | 2008-03-25 | By Jon Brodkin, Network World - A startup called Elastra is launching Tuesday with software that helps customers build database management systems and other applications that can be deployed on top of Amazon's EC2 cloud computing service.
- Gartner Says Worldwide PC Shipments to Grow 11 Percent in 2008, Market Could Fall Victim to Weaker Global Economy - Worldwide PC shipments are forecast to total 293 million units in 2008, up 10.9 percent from 2007 shipments of 264 million units, according to Gartner, Inc. However, analysts warned that growth could fall into single digits if global economic headwinds st
- Microsoft partners with open source Jaspersoft, Sourcesense | Open Source | ZDNet.com - Microsoft and Jaspersoft are working together to ensure that Jasper’s business intelligence software suite runs well on the latest editions of Windows and SQL Server.
- The ’80s Video That Pops Up, Online and Off - New York Times - For rickrolling, the duck was replaced with the 20-year-old Astley video, and in the last year it has become a hugely successful “meme,” the Internet’s word for an idea repeated across the Web. The video from yougotrickrolled.com has been viewed mor
- Roundtable: The state of open source | InfoWorld | News | March 24, 2008 | By Jason Snyder - Any endeavor rooted in community is bound to spark passionate debate. After all, without contention, how else to determine the best way forward? Since its emergence, open source has embodied this spirit. Part defiant, part self-reliant, and often outspoke
- ETL for Free-Form Data - SQL Server Central - Would you like to learn a handy little process for extracting, transforming and loading data fields from a free-form source like a web page or word processing document into something structured like a staging table?
- Asynchronous HTTP and Comet architectures - Java World - In this article, Gregor Roth takes a wider view of asynchronous HTTP, explaining its role in developing high-performance HTTP proxies and non-blocking HTTP clients, as well as the long-lived HTTP connections associated with Comet.
- Ext.ux.grid.RowActions - RowActions Plugin for Ext 2.x - Beta1 by Saki - RowActions plugin allows you to add icons in a grid that you want to bind actions to: delete row, edit row, whatever. It displays an icon and fires two events: beforeaction (return false to cancel) and action (here you put the action you want to execute)
- Coding Horror: Paul Graham's Participatory Narcissism - Loved this comment
- I hadn't realized how unhappy I was until I watched Office Space and my wife said, "That seems like your job". I soon switched jobs
Related posts
{ 0 comments }
Life is beautiful with XMLBeans and XStream
XML creation, parsing and processing with Java has gotten so much easier with tools like XMLBeans, XStream and many other such tools. I personally love XMLBeans and XStream and I try to use them for all of my XML processing needs. While they both consume XML, they solve different problems. XMLBeans allows you to process XML by binding it to Java types using XML schema that has been compiled to generate Java types that represent schema types. XStream on the other hand allows you to serialize objects to XML and back again using special reflective secret sauce.
I've been using these tools for many years now and so you tend to forget just how useful and powerful they are and how productive they make you. Case in point – A friend of mine came to me for help. He was building an application that would allow him to resale items from Amazon on his site and he wanted to use the Amazon eCommerce Web Services to search for products programmatically and update a local database that housed his content. Having played with Amazon E-Commerce Service (ECS) before, I offered to write up a simple application that would make the Web Services call, process the results and present them back to you.
Amazon's ECS is an API that allows you to access Amazon data and functionality through a Web site or Web-enabled application. ECS follows the standard Web services model: users of the service request data through XML over HTTP (REST) or SOAP and data is returned by the service as an XML-formatted stream of text. In addition to the WSDL, ECS also provides XML schemas for validating the XML output of REST requests. So I decide to use XMLBeans to create my type system using the XML Schema provided by Amazon. XMLBeans provides you with a utility (scomp) to compile your schema into Java XMLBeans classes and metadata. To generate the Java code, use the following command:
scomp –jar amznws.jar AWSECommerceService.xsd
This generates a jar file named amznws.jar, which will contain all of the code needed to bind an XML instance to the Java types representing your schema. In my application, I use HttpClient to make my REST request and then use the XMLBeans generated jar file to process the result. Here's a snippet of code from my sample class:
[code lang="java"]
if (StringUtils.isNotBlank(searchCriteria)) {
String url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&" +
"AWSAccessKeyId=*YOUR_KEY*&AssociateTag=*YOUR_TAG*&Operation=ItemSearch&SearchIndex=Books&" +
"Keywords=" + searchCriteria + "&ResponseGroup=Large,Images";
GetMethod method = new GetMethod(url);
List
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
log.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
InputStream in = method.getResponseBodyAsStream();
String xmlPayload = parseISToString(in);
// Set up the validation error listener.
ArrayList validationErrors = new ArrayList();
XmlOptions validationOptions = new XmlOptions();
validationOptions.setErrorListener(validationErrors);
ItemSearchResponseDocument items = ItemSearchResponseDocument.Factory.parse(xmlPayload);
if (items != null) {
ItemsDocument.Items[] itemsArray = items.getItemSearchResponse().getItemsArray();
for (int i = 0; i < itemsArray.length; i++) {
AmazonWSObject amzn = processResults(itemsArray, i);
results.add(i, amzn);
}
// During validation, errors are added to the ArrayList
boolean isValid = items.validate(validationOptions);
// Print the errors if the XML is invalid.
if (!isValid) {
for (Object validationError : validationErrors) {
log.error(">> " + validationError + "\n");
}
}
} else {
log.error("Search returned no results");
}
} catch (HttpException e) {
log.error("Fatal protocol violation: " + e.getMessage());
} catch (IOException e) {
log.error("Fatal transport error: " + e.getMessage());
log.error(e.toString());
} catch (XmlException e) {
log.error(e.toString());
} finally {
method.releaseConnection();
}
return results;
} else {
return null;
}
[/code]
As you can tell, HttpClient makes the REST call a snap and XMLBeans makes processing the results easy as well. In total, I spent 3-4 hours getting the application working and a lot of the time was spent figuring out the data set returned from Amazon and trying to come up with a meaningful example. Here is a zip file with the IDEA project that has all the stuff needed to make this work including a simple JSP and a JUnit test class.
Links of Interest:
- Amazon Web Services
- Amazon ECS WSDL
- Amazon ECS XML Schema
- Localized editions of xsd and wsdl
- XMLBeans
- XStream
- HttpClient
Related posts