Monday, August 24, 2009

Part II: Using UPS Address Validation API for Java SE or EE

Step 1: Call your doPost method within your service method.

public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doPost(req,resp);
}

Step 2: Pull your XML out of POST object, do some cleanup, pass to your relevant objects to your sendrequestgetresponse method. In my case, I'm cleaning the XML and retrieving the HOST URL, passing them both through my method.

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{

String strKey = " String strValue = req.getParameter(strKey);
String strConcat = strKey + "=" + strValue;

if (!WSUtils.isNullOrEmpty(strConcat)){
sendRequestGetResponse(upsHostUrl, strConcat, req, resp);
}

}

Step 3: Send your request, get your response and put it into output stream back to client.


public boolean sendRequestGetResponse(String url, String xml, HttpServletRequest req, HttpServletResponse resp)
{
//Create a method instance.
PostMethod post = new PostMethod(url);

try
{
// Create an instance of HttpClient.
HttpClient client = new HttpClient();

// set various config specs
client.getParams().setConnectionManagerTimeout(30 * 10000);
client.getHostConfiguration().setProxy(proxyHost, proxyPort);

List authPrefs = new ArrayList();
authPrefs.add(AuthPolicy.NTLM);

//provide auth policy
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

// set proxy specs
client.getState().setProxyCredentials(
new AuthScope(null, proxyPort, null),
new NTCredentials(proxyUserName, proxyPassword, "", proxyDomain));


//build request body
StringBuilder postbody = new StringBuilder(2000);
//define header
Header contentTypeHeader = new Header("Content-type", "application/x-www-form-urlencoded");
//append header object to request body
post.setRequestHeader(contentTypeHeader);

//append xml string to stringbuilder object
postbody.append(xml);

StringRequestEntity sre = new StringRequestEntity(postbody.toString(),null,null);
// append string request entity(xml) to request body
post.setRequestEntity(sre);

// execute the method
int statusCode = client.executeMethod(post);
System.out.println(statusCode);

// Read the response body - For Debugging purposes only
//byte[] responseBody = post.getResponseBody();

// Deal with the response - For Debugging purposes only
//System.out.println(new String(responseBody));

//handle response by putting into output stream back to form
InputStream is = post.getResponseBodyAsStream();
OutputStream os = resp.getOutputStream();
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);

if (statusCode == HttpStatus.SC_OK)
{
return true;
}
else
{
System.err.println("Method failed: " + post.getStatusLine());
return false;
}

}catch(HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
return false;

}catch(IOException e){
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
return false;

} finally {
// Release the connection.
post.releaseConnection();
}


}

/**
*verify URL existence
*@param urlString
*@return boolean indicating success/failure for existence
*/

public boolean verifyURL(String url)
{
try
{
if (!WSUtils.isNullOrEmpty(url))
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
}
}
}

Tuesday, August 11, 2009

Using UPS Address Validation API for Java SE or EE

Part I: Using UPS Address Validation API for Java SE or EE

Step 1: Create a servlet with the appropriate name convention.
I'm using RAD7, so first I created a package relevant to my environment. Your package name could be anything but in my case it's "server" on the end because my servlet will execute some request/response activities to the server in question
*com.tti.ws.addressvalidation.server
I then created a class called AddressValidationServlet.java

Step 2: Define your class in the web.xml for mapping purposes (If this were an action class, you'd define the mapping in the struts-config.xml)



AddressValidationServlet
AddressValidationServlet
com.tti.ws.addressvalidation.server.AddressValidationServlet





AddressValidationServlet
/addressvalidation/AddressValidationServlet


Step 3: Import the following object libraries so you can use their methods. Copy/Paste and place this right below the "package com.tti.ws.addressvalidation.server;"

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.tti.ws.util.IWSConstants;
import com.tti.ws.util.WSProperties;
import com.tti.ws.util.WSUtils;

Step 4: Extend your servlet by doing the following.
public class AddressValidationServlet extends HttpServlet implements Servlet{

Step 5: Define a serialVersionUID for the purpose of generics code cleanup and define it
right under your "public class" line so your servlet, here's why:

static final long serialVersionUID = -1L;

Generics cleanup
* If a serializable class does not explicitly declare a serialVersionUID,
* then the serialization runtime will calculate a default serialVersionUID
* value for that class based on various aspects of the class, as described
* in the Java(TM) Object Serialization Specification. However, it is
* strongly recommended that all serializable classes explicitly declare
* serialVersionUID values, since the default serialVersionUID computation
* is highly sensitive to class details that may vary depending on compiler
* implementations, and can thus result in unexpected
* InvalidClassExceptions during deserialization. Therefore, to guarantee a
* consistent serialVersionUID value across different java compiler
* implementations, a serializable class must declare an explicit
* serialVersionUID value.

Step 6: Define a constructor for your static proxy info. Note: this step is done only because I need to Authenticate in/out of my firewall. The references are setup in my application.properties:

public AddressValidationServlet() throws Exception
{
proxyHost = WSProperties.getRuntimeProperty("proxy.host");
proxyPort = Integer.parseInt(WSProperties.getRuntimeProperty("proxy.port"));
proxyUserName = WSProperties.getRuntimeProperty("proxy.username");
proxyPassword = WSProperties.getRuntimeProperty("proxy.password");
proxyDomain = WSProperties.getRuntimeProperty("proxy.domain");
}

Step 7: In my case, I'm looking for the POST object from my client, so I use the "service" and "doPost" method. When the servlet is executed, the "service" method is executed first.
So I proceed to execute my "doPost" method through the "service" method.

public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doPost(req,resp);
}

Step 8: Set a breakpoint on your "doPost(req,resp);", save everything, restart your server. Fire off your servlet URL to see if your breakpoint is hit. If so, continue to Part II, If not, publish, restart your server, verify your URL.

http://www.yourapp.com/yourWeb/addressvalidation/AddressValidationServlet