Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, March 27, 2012

SNMP Introduction: Communicating with your Router

"Simple Network Management Protocol (SNMP) is an Internet-standard protocol for managing devices on IP networks. Devices that typically support SNMP include routers, switches, servers, workstations, printers, modem racks, and more. It is used mostly in network management systems to monitor network-attached devices for conditions that warrant administrative attention." - Wikipedia

Below is a Java code snippet which uses the 3rd party library snmp4j to communicate with a router. In this example we obtain the name of the router and the current data usage. Before executing the code confirm that your router supports SNMP and that it is enabled. Also verify that the SNMP read and write community is set to "public". These are configurable values that can be updated from within your router's administrative application.

Note that the OID variables contain long and cryptic numeric values. These values can be obtained using a free SNMP browser such as iReasoning's MIB Browser. When using an SNMP browser you must supply your router's IP address and SNMP port (usually 161) to connect to your router. Once connected you can browse through the different properties as a tree structure and obtain any of the numeric values for the OIDs.

import java.io.*;
import org.snmp4j.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;

public class SnmpClient
{
 public static final OID sysNameOID = new OID(".1.3.6.1.2.1.1.5.0");
 public static final OID ifNumberOID = new OID(".1.3.6.1.2.1.2.1.0");
 public static final OID ifOutOctetsOID = new OID(".1.3.6.1.2.1.2.2.1.16.1");
 public static final OID ifInOctetsOID = new OID(".1.3.6.1.2.1.2.2.1.10.1");
 
 private String address;
 private Snmp snmp;
 
 public static void main(String[] arg)
 {
  try
  {
   //Create a client with the router's IP Address and SNMP port (161 is default)
   SnmpClient client = new SnmpClient("udp:192.168.0.1/161");
   
   //Get the router's name
   String name = client.getAsString(sysNameOID);
   
   //Display the router's name
   System.out.println("ROUTER'S NAME: " + name);
   
   //Update the router's name (sysName is one of the few properties that are writable)
   client.setAsString(sysNameOID, "TEST");
   
   //I had to read this property before reading the other data usage properties
   client.getAsInt(ifNumberOID);
   
   //Get total number of bytes sent since last router reboot
   int bytesSent = client.getAsInt(ifOutOctetsOID);
   
   //Get total number of bytes received since last router reboot
   int bytesReceived = client.getAsInt(ifInOctetsOID);
   
   //Calculate total number of bytes sent and received
   int bytesTotal = bytesSent + bytesReceived;
   
   //Display combined total data usage in megabytes
   System.out.println("DATA USAGE: " + (bytesTotal / 1024 / 1024) + " MB");
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
 
 public SnmpClient(String address) throws IOException
 {
  this.address = address;
  start();
 }

 private void start() throws IOException
 {
  DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
  snmp = new Snmp(transport);
  transport.listen();
 }
 
 public void stop() throws IOException
 {
  snmp.close();
 }
 
 private Target createTarget()
 {
  Address targetAddress = GenericAddress.parse(address);
  CommunityTarget target = new CommunityTarget();
  target.setCommunity(new OctetString("public"));
  target.setAddress(targetAddress);
  target.setRetries(3);
  target.setTimeout(1500);
  target.setVersion(SnmpConstants.version1);
  return target;
 }
 
 private PDU createGetPDU(OID oid)
 {
  PDU pdu = new PDU();
  pdu.setType(PDU.GET);
  pdu.add(new VariableBinding(oid));   
  return pdu;
 }
 
 public Variable get(OID oid) throws IOException
 {
  PDU response = snmp.send(createGetPDU(oid), createTarget()).getResponse();
  if (response != null && response.size() > 0)
  {
   return response.get(0).getVariable();
  }
  throw new IOException("Unable to obtain response from server");
 }
 
 public String getAsString(OID oid) throws IOException
 {
  return get(oid).toString();
 }
 
 public int getAsInt(OID oid) throws IOException
 {
  return get(oid).toInt();
 }
 
 private PDU createSetPDU(OID oid, Variable value)
 {
  PDU pdu = new PDU();
  pdu.setType(PDU.SET);
  pdu.add(new VariableBinding(oid, value));
  return pdu;
 } 
 
 public void set(OID oid, Variable value) throws IOException
 {
  snmp.send(createSetPDU(oid, value), createTarget());
 }
 
 public void setAsString(OID oid, String value) throws IOException
 {
  set(oid, new OctetString(value));
 }
 
 public void setAsInt(OID oid, int value) throws IOException
 {
  set(oid, new Integer32(value));
 }
}

Saturday, September 17, 2011

Client-Side Caching of Dynamic Content with Java

To achieve optimum performance and results when caching content you should try to set both the Expires header and the Last-Modified header.

The Expires should be set to a date in the future. It instructs the browser to cache the content until it expires when the Expires date is surpassed. If the content is very volatile (changes frequently) then the Expires date should be set to a lower value (near in the future) otherwise it should be set to a higher value (far in the future). This type of caching is referred to as "hard" caching because the browser never reconnects to the server again until the appointed time. Because of this, this type of caching is relatively fast.

The Last-Modified header should be set to a date in the past. It instructs the browser to cache the content unless it has been modified since the Last-Modified date was last set. If the content has since been modified then the Last-Modified date should be updated to a new value (the date the content was modified) to reflect this. This type of caching is referred to as "soft" caching because the browser always reconnects to the server again to check if the content has been modified. Because of this, this type of caching is relatively slow.

The Last-Modified header works in conjunction with the If-Modified-Since header. The first time the content is requested the server sets the Last-Modified date in the response. The browser then receives this response and caches the content along with the Last-Modified date. In subsequent requests the browser sets the If-Modified-Since date equal to the Last-Modified date that was previously cached. The server then receives the request and gets the If-Modified-Since date for the purpose of comparing it to the content's Last-Modified date.

The server is responsible for comparing the If-Modified-Since date and the Last-Modified date to determine if the browser has the most recent version of the content. If the dates are equal then browser already has the most recent version of the content and the server responds with an HTTP status code of 304 (Not Modified) which is the signal for the browser to reload the content from its cache. If the dates are not equal then the browser does not already have the most recent version of the content and the server responds by sending the updated content in its entirety along with the updated Last-Modified date.

When you combine the Expires header and the Last-Modified header the resulting behavior will be a hybrid of the two types of caches which will be the best in terms of both performance and flexibility.

Below is sample code that demonstrates how to set both the Expires header and the Last-Modified header in a Java Servlet. This Servlet makes use of the getLastModified method which automatically sets the Last-Modified date to the method's return value which is then compared to the If-Modified-Since date. Please note that the order in which the Expires header is set and the getLastModified method is called is important. The Expires header must always be set first which is why the service method is overridden for this purpose.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.util.*;

public class CacheTestServlet extends HttpServlet
{
 private static long hits = 0;
 private static Date date;
 
 //This method sets the Expires date 15 seconds in the future
 //Typically the Expires date would be set to a higher value
 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  response.setDateHeader("Expires", new Date().getTime() + 15000);
  super.service(request, response);
 }
 
 //This method updates the Last-Modified date on every other request
 //This is meant to simulate content that is modified occasionally
 //Typically the Last-Modified date would be retrieved from a file or database
 public long getLastModified(HttpServletRequest request)
 {
  hits++;
  if (hits % 2 == 1)
  {
   date = new Date();
   System.out.println("FULL HIT");
  }
  else
  {
   System.out.println("PARTIAL HIT");
  }
  
  return date.getTime() / 1000 * 1000;
 }
 
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
 {
  response.getWriter().println("The current date & time is " + new Date());
 }
}

Below is a summary of the Servlet's output:

  1. The first time you load the page you will see the current date & time and the phrase "FULL HIT" will be printed.
  2. If you immediately reload the page, then the page will be reloaded from the browser's cache without reconnecting to the server. The date & time will not change and neither the phrase "FULL HIT" nor the phrase "PARTIAL HIT" will be printed because the server does not actually receive any requests.
  3. If you wait at least 15 seconds before reloading the page, then the browser will reconnect to the server to determine if the content has been modified but since the Last-Modified date has not changed it will reload the page from the browser's cache as opposed to reloading it from the server. The the date & time will not change but the phrase "PARTIAL HIT" will be printed.
  4. If you immediately reload the page, then the page will be reloaded from the browser's cache without reconnecting to the server. The date & time will not change and neither the phrase "FULL HIT" nor the phrase "PARTIAL HIT" will be printed because the server does not actually receive any requests.
  5. If you wait at least 15 seconds before reloading the page, then the browser will reconnect to the server to determine if the content has been modified and since the Last-Modified date has changed it will reload the page from the server as opposed to reloading it from the browser's cache. The date & time will change and the phrase "FULL HIT" will be printed.
  6. And so forth...

Tip: Pressing F5 in your browser will cause the browser to ignore any "soft" caches and reload the page. Pressing CTRL+F5 in your browser will cause the browser to ignore any "hard" caches and reload the page.

Here is a good link regarding caching:

http://code.google.com/speed/page-speed/docs/caching.html

Monday, June 6, 2011

JSF 2.0 Overview

7/12/2014: I've not used JSF since I wrote this post years ago, but I've come to the conclusion that a complicated, abstracted lifecycle is a bad thing for a web framework. Therefore I would not recommend using JSF.

I have been learning JSF 2.0 (Java Server Faces 2.0) over the last few days. I never used the original JSF 1.0 implementation so I was slightly intimidated when I read mostly horrendous reviews regarding it. However, my understanding is that the second implementation is much improved and most of the problems have been corrected. I still have a few reservations about the complexity of the application lifecycle, but hopefully my concerns will diminish as I continue to learn the framework.

JSF is a Java web framework. Defined in greater detail, it is essentially a MVC framework, a GUI controls and handlers framework, and an AJAX framework. It competes with other frameworks like Servlet/JSP, Seam, Spring, Struts, Tapestry, Wicket, etc. (although in some cases two frameworks can be used together collaboratively i.e. JSF+Seam, JSF+Spring, etc). The original version of JSF attempted to collaborate with JSP but it quickly became clear that JSF potential was being burdened by JSP limitations. As a result, newer versions of JSF do not make use of JSP at all! Instead it uses a new technology called Facelets. That's a large paradigm shift for many of us who have been using JSP since we first learned Java web development. The current version of JSF is 2.0. JSF 1.0 had some noteable problems, but JSF 2.0 addresses many of them. JSF 2.0 also adds new features like AJAX support. With JSF 2.0 it is possible to add AJAX support with 100% Java code without writing any JavaScript code!

JSF is an officially supported framework. This may be perceived as an advantage compared to other 3rd party frameworks like Struts. There are many different flavors of JSF: Mojarra (basic Sun/Oracle implementation), MyFaces (basic Apache implementation), IceFaces (extended Sun/Oracle implementation), Tomahawk (extended Apache implementation), RichFaces (extended JBoss implementation), etc. Anyone is free to implement their own version of JSF so long as they adhere to the JSR specification. Following the JSR guidelines guarantees that all implementations will have the same basic functionality and features. However, implementors are allowed to go above and beyond the specification. Therefore, some implementations may have additional functionality and features that is vendor specific and not officially supported. This is both an advantage and a disadvantage. If you use an extended JSF implementation with fuller features and functionality you may eventually suffer from vendor lock-in.

To run JSF 2.0 the minimum requirements are Java 5.0 or greater, and an application server that supports Servlet spec 2.5 or greater. Unfortunately, this is a fairly stiff requirement since it eliminates the majority of older application servers. Supported servers include Tomcat 6+, Glassfish 3+, Weblogic 11+, JBoss 5.2+, etc. Newer versions of J2EE compliant servers like Glassfish, Weblogic, and JBoss will have automatic support for JSF. Since Tomcat is only a servlet container and is not J2EE compliant, you must manually install JSF (include 2 jar files). Although there are many different implementations of JSF created by many different vendors, they should run on any application server as long as the minimum requirements are met regardless of the vendor. So, for example, the RichFaces (JBoss) implementation should work ok on the Tomcat (Apache) application server.

Since JSF 2.0 is relatively new the documentation is still a little sparse. I recommend these tutorials for starting:

http://www.coreservlets.com/JSF-Tutorial/jsf2/

I found these tutorials to be excellent overall, except the AJAX tutorial was a little difficult to follow.

Sunday, June 5, 2011

Cloud Computing (and Google App Engine)

There's a lot of buzz about cloud computing lately, but often the term is used in a vague or ambiguous way (such as Microsoft's "Take it to the Cloud!" commercials). All the hype may leave you scratching your head and asking the question, "what exactly does cloud computing mean and why is it so popular?" The simplest definition of cloud computing refers to "the on-demand provision of computational resources (data, software) via a computer network, rather than from a local computer" (Wikipedia). Recently, Google has taken this definition to an extreme with the introduction of their Chromebooks; these are computers but all of the applications and data are stored on the web instead of on the harddrive.

So basically cloud computing is a movement to host more applications on the web instead of your computer. This definition alone is very loose, not particularly extraordinary, and does not fully explain the mystique of cloud computing. Actually, there are a few other qualifiers often attributed to cloud computing that contribute to its popularity especially regarding web development. A cloud service usually is elastic, is fully managed by the provider, and is sold on demand. I will attempt to explain these attributes in more detail in the following paragraphs.

A cloud service is elastic - "a user can have as much or as little of a service as they want at any given time". A cloud application is automatically scaled and load balanced as traffic increases; this is accomplished by automatically spinning up additional servers and distributing requests across these servers to meet demand. The obvious advantage here is that you do not have to manage these details yourself in the case that your application is growing larger and requires more resources (this leads into the next point).

A could service is fully managed by the provider - "the consumer needs nothing but a personal computer and Internet access". Cloud applications tend to run on a complex distributed network of virtualized machines that are both efficient and highly available. If one server goes down the burden will be shifted and another server will instantly replace it (guaranteeing nearly 100% up-time). This sophisticated architecture is fully supplied by the provider and mostly runs in the background; it does not require any physical resources from or direct administration by the user.

A cloud service is sold on demand - in other words you "pay for only for what you use" measured as combination of bandwidth usage, storage usage, number of requests, number of web service/api calls, etc. As a result, a user can take full advantage of the cloud services for a minimal investment. This can mean significant cost savings for businesses, especially small to medium sized businesses. Because of this cloud computing has become increasingly popular during this weak economy.

A few of the most prominent cloud providers are Amazon, Rackspace, Microsoft Azure, and Google. Although I believe Amazon is probably the most popular of these offerings, I have only experimented with Google App Engine, and it is my favorite so far because it supports a Java development environment and... it's free! (within limits, see below).

Google App Engine generously allows a free quota of 500MB of storage and 5 million page views per month. As a result I have used Google App Engine to host my Java applications for the past couple of years without paying a dime. If you want to host simple applications for personal use then I would highly recommend Google App Engine. However, there are some limitations associated with Google App Engine that can be frustrating. Therefore, if you want to host complex applications for commercial use then I would probably recommend a different provider such as Amazon.

I copied, quoted, and paraphrased much of the information in this post from the following link:

http://searchcloudcomputing.techtarget.com/definition/cloud-computing

Friday, March 11, 2011

Prevent SQL Injection Attacks in Java

To prevent hackers from exploiting your Java website:

NEVER do this (manually concatenate SQL):

String sql = "select 1 from user where userId='" + userId + "' and password='" + password + "'";

Instead do this (use prepared statements):

String sql = "select 1 from user where userId = ? and password = ?";
PreparedStatement prepStmt = con.prepareStatement(sql);
prepStmt.setString(1, userId);
prepStmt.setString(2, password);

When you use prepared statements it passes the parameters directly to the database independent of the SQL statement so that the hacker never has a chance to alter them.

Clean your JSP Code with JSTL & JSP EL

Note: After writing this blog I realized 3rd party templating engines like Velocity or FreeMarker are viable alternatives to JSTL & JSP EL. However JSTL & JSP EL are the standard and have official support while the others do not. I may write a couple follow up blogs in the future detailing how to use Velocity or FreeMarker.

Below is an example of mixing HTML with JSP scriptlets and expressions:

<% if (user.getRole().equals("member")) { %>
    <p>Welcome, <%=user.getName() %>!</p>
<% } else { %>
    <p>Welcome, guest!</p>
<% } %>

The mixing and HTML's syntax and Java's syntax makes the code ugly and hard to read and understand. It can also encourage bad coding practices; it is sometimes tempting to add additional business logic in your JSP files. JSTL and JSP EL were created to remedy this situation.

JSTL (JSP Standard Tag Library) is a standardized tag library that can be used to replace JSP scriptlet tags (<% %>) inside of JSP files. It has tags for all the most common operations necessary to create your JSP file (conditional tags, looping tags, formatting tags, etc).

JSP EL (JSP Expression Language) is an expression language that can be used to replace JSP expression tags (<%= %>) inside your JSP files. JSP EL has many convenient shortcuts and allows for a much simpler syntax to manipulate application data.

JSTL has integrated support for JSP EL; JSP EL can be used inside of the JSTL tag attributes. If your application server supports JSP 2.0 specification or greater then JSP EL can also be used outside of the JSTL tag attributes; otherwise you will need to wrap your expression using the JSTL out tag (see example below). Using JSTL combined with JSP EL the above code becomes:

<c:choose>
<c:when test="${user.role == 'member'}">
    <p>Welcome, <c:out value="${user.name}"/>!</p>
</c:when>
<c:otherwise>
    <p>Welcome, guest!</p>
</c:otherwise>
</c:choose>

As you can see the code is much improved compared to its original state. Finally, you can rid yourself of all the ugly JSP tags.

JSTL may or may not be included with your application server. If it is not included you can download the JAR files and add them to your project's WEB-INF/lib folder or to your application server's shared library folder. The JSTL version you need to download will vary based on which JSP specification version your application server supports. Below is a table that maps the JSTL version to the JSP specification version:

Servlet VersionJSP VersionJSTL VersionJava EE Version
2.52.11.25
2.42.01.11.4
2.31.21.01.2

Note: I am having great difficulty trying to find downloads for the older versions of JSTL. The download links on the Jakarta site are broken. I have not found a solution to this problem yet.

For more information see the following links:

Portal Breadcrumbs

In a portal application all the navigation is theoretically pre-defined, since the structure of the portal application is defined in a hierarchal way. For example, to the right is the structure of the portal file created using Weblogic Portal 8.1.

To create the breadcrumbs for this portal application we simply have to iterate through the structure of the portal file, starting with the current page and working upwards towards the root.

The code to accomplish this is below (slight tweaks may be required for your own use). This code is specific to Weblogic Portal 8.1 but the basic concept should be applicable to all portal platforms. In this particular example all the code is saved in a single JSP file. (Sorry, I know the code is ugly):

<%@ page import="com.bea.netuix.servlets.controls.page.PagePresentationContext,
     com.bea.netuix.servlets.controls.page.BookPresentationContext,
     com.bea.netuix.servlets.controls.application.DesktopPresentationContext
     com.bea.netuix.servlets.controls.PresentationContext,
     com.bea.portlet.PageURL,
     java.util.List" %>
<%

ArrayList breadcrumbs = new ArrayList();

PagePresentationContext pageCtx = PagePresentationContext.getPagePresentationContext(request);

do
{
 PagePresentationContext parentPageCtx = pageCtx.getParentPagePresentationContext();

 String title;
 String url; 

 if (pageCtx instanceof BookPresentationContext)
 {
  title = pageCtx.getTitle();
  url = PageURL.createPageURL(request, response, ((BookPresentationContext)pageCtx).getDefaultPage()).toString();
 }
 else
 {
  title = pageCtx.getTitle();
  url = PageURL.createPageURL(request, response, pageCtx.getDefinitionLabel()).toString();
 }

 if (parentPageCtx == null)
 {
  title = "Home";
 }

 if (!(
   parentPageCtx != null &&
   parentPageCtx instanceof BookPresentationContext &&
   ((BookPresentationContext)parentPageCtx).getDefaultPage().equals(pageCtx.getDefinitionLabel())
  ))
 {
  breadcrumbs.add(new String[] {title, url});
 }

 pageCtx = parentPageCtx;
}
while (pageCtx != null);

%>

<p class="x-small bold">

<%

for (int i = breadcrumbs.size() - 1; i >= 0; i--)
{
 String title = ((String[])breadcrumbs.get(i))[0];
 String url = ((String[])breadcrumbs.get(i))[1];

 if (i > 0)
 {
 %>
  <a class="breadcrumb-hyperlink" href="<%=url%>"><%=title%></a> >
 <%
 }
 else
 {
 %>
  <%=title%>
 <%
 }
}

%>

</p>

Integrate Java with Microsoft SQL Server Reporting Services 2005/2008

The best way to accomplish this is through the use of the ReportExecution2005 web service that is provided out of the box by Microsoft SQL Server Reporting Services.

  1. Start Eclipse and create a new workspace named ssrsClient

  2. Create a new Java project called ssrsClient

  3. Configure the advanced Axis settings so that "Generate code for all elements, even unreferenced ones" is checked, and so that "Timeout in seconds" is set to -1. (See my previous post, Configure Advanced Axis Settings from Eclipse, for more details)

  4. Create a web service client proxy for the ReportExecution2005 web service; the URL for the WSDL definition will be http://<HOST>/reportserver/ReportExecution2005.asmx?wsdl. (See my previous post, Consume Any Web Service Using Eclipse + Axis, for more details)

  5. Enable NTLM Authentication in Axis by adding the Jakarta Commons HTTPClient and Codec JAR files to the classpath. (See my previous post, Enable NTLM Authentication in Axis, for more details)

  6. Create a new Java Class named Test.java

  7. Copy and paste the following code into Test.java (overwrite the existing code)
    import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.*;
    import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.holders.*;
    import java.net.URL;
    import javax.xml.rpc.holders.ByteArrayHolder;
    import javax.xml.rpc.holders.StringHolder;
    import javax.xml.soap.SOAPException;
    import org.apache.axis.message.SOAPHeaderElement;
    
    public class Test
    {
     public static void main(String[] arg)
     {
      ReportExecutionServiceSoapStub service = getService();
      ParameterValue[] parameters = new ParameterValue[1];
      parameters[0] = new ParameterValue();
      parameters[0].setName("<PARAMETER_1_NAME>");
      parameters[0].setValue("<PARAMETER_1_VALUE>");
      
      try
      {
       ExecutionInfo info = service.loadReport("/<FOLDER_NAME>/<REPORT_NAME>", null); //Load report
       setExecutionId(service, info.getExecutionID()); //You must set the session id before continuing
       service.setExecutionParameters(parameters, "en-us"); //Set report parameters
       
       String format = "HTML4.0"; //Valid options are HTML4.0, MHTML, EXCEL, CSV, PDF, etc
       String deviceInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>"; //Only generate an HTML fragment
       ByteArrayHolder result = new ByteArrayHolder();
       StringHolder extension = new StringHolder();
       StringHolder mimeType = new StringHolder();
       StringHolder encoding = new StringHolder();
       ArrayOfWarningHolder warnings = new ArrayOfWarningHolder();
       ArrayOfStringHolder streamIDs = new ArrayOfStringHolder();   
       service.render(format, deviceInfo, result, extension, mimeType, encoding, warnings, streamIDs); //Render report to HTML
       
       System.out.println(new String(result.value)); //Prints the report HTML; this could be embedded in a JSP
      }
      catch (Exception e)
      {
       e.printStackTrace();
      }
      
     }
     
     public static void setExecutionId(ReportExecutionServiceSoapStub service, String id) throws SOAPException
     {
      SOAPHeaderElement sessionHeader = new SOAPHeaderElement("http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices", "ExecutionHeader");
      sessionHeader.addChildElement("ExecutionID").addTextNode(id);
      service.setHeader(sessionHeader);
     }
     
     public static ReportExecutionServiceSoapStub getService()
     {
      try
      {
       String endpoint = "http://<HOST>/reportserver/ReportExecution2005.asmx";   
       ReportExecutionServiceSoapStub service = (ReportExecutionServiceSoapStub)new ReportExecutionServiceLocator(getEngineConfiguration()).getReportExecutionServiceSoap(new URL(endpoint));
       service.setUsername("<DOMAIN>\\<USER_NAME>");
       service.setPassword("<PASSWORD>");
       return service;
      }
      catch (Exception e)
      {
       e.printStackTrace();
      }
      
      return null;
     }
     
     public static org.apache.axis.EngineConfiguration getEngineConfiguration()
     {
      java.lang.StringBuffer sb = new java.lang.StringBuffer();
      
      sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
      sb.append("<deployment name=\"defaultClientConfig\"\r\n");
      sb.append("xmlns=\"http://xml.apache.org/axis/wsdd/\"\r\n");
      sb.append("xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\">\r\n");
      sb.append("<globalConfiguration>\r\n");
      sb.append("<parameter name=\"disablePrettyXML\" value=\"true\"/>\r\n");
      sb.append("<parameter name=\"enableNamespacePrefixOptimization\" value=\"true\"/>\r\n");
      sb.append("</globalConfiguration>\r\n");
      sb.append("<transport name=\"http\" pivot=\"java:org.apache.axis.transport.http.CommonsHTTPSender\"/>\r\n");
      sb.append("<transport name=\"local\" pivot=\"java:org.apache.axis.transport.local.LocalSender\"/>\r\n");
      sb.append("<transport name=\"java\" pivot=\"java:org.apache.axis.transport.java.JavaSender\"/>\r\n");
      sb.append("</deployment>\r\n");
      
      return new org.apache.axis.configuration.XMLStringProvider(sb.toString());
     }
    }
    

  8. Replace all the placeholders with actual values:
    Lines 13-17
    Replace the report parameter names/values with your own report parameter names/values. Increase the size of the array if you have more than one parameter.

    Line 21
    Replace the report path with the path to your own report. Do NOT include the .RDL extension in this path.

    Line 55
    Replace the report host with your own report host. This is the endpoint for the ReportExecution2005 web service.

    Lines 57-58
    Replace the domain, username, and password with your own. These are the Windows credentials that will be used to access the report.

  9. Execute the code. You should see the report HTML printed as output. If you face an authentication error (401) then verify NTLM is enabled and also try adding
    
    3
    
    
    
    
    in your rsreportserver.config under reportserver for basic authentication with SSRS (Thanks Sridhar Iyer).

    If you still receive an authentication error (401) then it may be that SSRS and/or Windows is using NTMLv2 (verified for Windows 7). See JB's comment near the bottom of this page and also visit the following link for more information: http://devsac.blogspot.com/2010/10/supoprt-for-ntlmv2-with-apache.html. (Thanks JB!)

  10. Package all the classes into a JAR file and copy it into the WEB-INF/lib folder of your web app. Use the same technique as above to embed the rendered report HTML in a JSP file.

  11. Build a nice user interface that accepts the appropriate report parameters and passes them through to the web service. Add an "Export" drop down list on the report page that allows users to export the report to different formats like Excel, PDF, CSV, etc. You do not have to completely reload the report every time you export it to a different format; once you initially obtain the Report Execution ID you can save it and re-use for rendering to other formats.

Enable NTLM Authentication in Axis

By default Axis is not configured to support NTLM Authentication. To enable NTLM Authentication Axis must be configured to use the Jakarta Commons HTTPClient library. NTLM Authentication is often required to use Windows based web services.

There are a few different methods for accomplishing this, but this is probably the quickest and simplest technique:

  1. Download and copy both the Jakarta Commons HTTPClient and Codec JAR files into your project and add them to the classpath.

  2. Copy and paste the following method into your own class; append it to the end of your pre-existing class or create a separate utility class:
     public static org.apache.axis.EngineConfiguration getEngineConfiguration()
     {
      java.lang.StringBuffer sb = new java.lang.StringBuffer();
      
      sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
      sb.append("<deployment name=\"defaultClientConfig\"\r\n");
      sb.append("xmlns=\"http://xml.apache.org/axis/wsdd/\"\r\n");
      sb.append("xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\">\r\n");
      sb.append("<globalConfiguration>\r\n");
      sb.append("<parameter name=\"disablePrettyXML\" value=\"true\"/>\r\n");
      sb.append("<parameter name=\"enableNamespacePrefixOptimization\" value=\"true\"/>\r\n");
      sb.append("</globalConfiguration>\r\n");
      sb.append("<transport name=\"http\" pivot=\"java:org.apache.axis.transport.http.CommonsHTTPSender\"/>\r\n");
      sb.append("<transport name=\"local\" pivot=\"java:org.apache.axis.transport.local.LocalSender\"/>\r\n");
      sb.append("<transport name=\"java\" pivot=\"java:org.apache.axis.transport.java.JavaSender\"/>\r\n");
      sb.append("</deployment>\r\n");
      
      return new org.apache.axis.configuration.XMLStringProvider(sb.toString());
     }

    Note: It's probably a good idea to separate the XML markup from the Java code (move XML markup to separate file). I just left the two joined together for the sake of simplicity / laziness since it eliminated one extra step from this blog posting.

  3. When you create an instance of your web service locator class pass the getEngineConfiguration() method as an argument in the constructor like this:
    MyWebServiceStub stub = (MyWebServiceStub)new MyWebServiceLocator(getEngineConfiguration());

  4. Set your user name and password like this:
    stub.setUsername("<DOMAIN>\\<USER_NAME>"); //Must use this format
    stub.setPassword("<PASSWORD>");

For more information see the following links:

Monday, March 7, 2011

Configure Advanced Axis Settings from Eclipse

Occasionally you may need to configure advanced Axis settings from Eclipse. Some common reasons for this are:
  • You need to increase or disable the Axis timeout if you are trying to consume a very large or complex web service.

  • You need to generate code for all elements, even unreferenced ones.

To access these settings, follow these instructions:

  1. Click Window -> Preferences from the Eclipse menu bar.

  2. Expand the Web Services node and then select Axis Emitter in the tree view located in the left pane.

You should see the Axis Emitter screen which contains a variety of options for both Wsdl2Java and Java2Wsdl. These settings are workspace specific so you will need to redefine them again if you switch workspaces. From this screen you can check the "Generate code for all elements, even unreferenced ones" checkbox, and you can set the "Timeout in seconds" to -1 to disable it (see screenshot below).

At the time of writing this tutorial I am using Eclipse Helios with the J2EE extensions installed; options may vary slightly if using a different version.

Sunday, March 6, 2011

Consume Any Web Service Using Eclipse + Axis

  1. Start Eclipse and create a new workspace named wsTest (click File -> Switch Workspace -> Other…)



  2. Create a new Java Project named wsTest (click File -> New -> Java Project)



  3. Create a new Web Service Client Proxy (click File -> New -> Other -> Web Services -> Web Service Client). In this case we are consuming a free, public web service that returns weather information for the United States. The URL for the WSDL definition is http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl.



  4. Create a new Java Class named Test.java (click File -> New -> Class)



  5. Copy and paste the following code into Test.java (overwrite the existing code):
    import com.cdyne.ws.WeatherWS.*;
    import java.net.URL;
    
    public class Test
    {
     public static void main(String[] arg)
     {
      try
      {
       WeatherSoapStub service = (WeatherSoapStub)new WeatherLocator().getWeatherSoap(new URL("http://ws.cdyne.com/WeatherWS/Weather.asmx"));
       WeatherReturn weather = service.getCityWeatherByZIP("47710");
       System.out.println("Location: " + weather.getCity() + ", " + weather.getState());
       System.out.println("Description: " + weather.getDescription());
       System.out.println("Temperature: " + weather.getTemperature() + " degrees");
      }
      catch (Exception e)
      {
       e.printStackTrace();
      }
     }
    }
    

    Note that we set the endpoint URL on line 10. The endpoint URL is typically the same as the WSDL definition URL except the endpoint URL does not include the ?WSDL query string parameter.

  6. Execute the code (click Run -> Run)

    You should see something resembling the following output:

    Location: Evansville, IN
    Description: Sunny
    Temperature: 49 degrees

At the time of writing this post I am using Eclipse Helios with the J2EE extensions installed; options may vary slightly if using a different version.




How It Works

Eclipse is executing the Axis Wsdl2Java process which parses the WSDL file and translates it into a set of Java client files that you can then use in your own application. It is possible to accomplish the same thing outside of Eclipse by directly executing the Axis Wsdl2Java process yourself.