473,396 Members | 2,082 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Convert Java to Servlet

5
Hello all,

I want to create a web application for sending booking requests to DHL. I already found a toolkit (http://xmlshippingtest.dhl-usa.com/toolkit/index.html) that uses XML files to send the bookings.

But how can I convert the Java code in this toolkit in to a servlet, so I can use it on the web. The Java code in that toolkit looks like this:

Expand|Select|Wrap|Line Numbers
  1. //IO Classes
  2. import java.io.FileInputStream;                                         
  3. import java.io.InputStream;                                                             
  4. import java.io.ObjectOutputStream;                              
  5. import java.io.DataOutputStream;                                        
  6. import java.io.OutputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.PrintStream;
  9. import java.io.BufferedInputStream;
  10. import java.io.ByteArrayInputStream;
  11. import java.io.ByteArrayOutputStream;           
  12. import java.io.ObjectInputStream;                                       
  13. import java.io.DataInputStream;                                 
  14. import java.io.IOException;                                                             
  15. import java.net.MalformedURLException;
  16. // Net classes
  17. import java.net.URL;                                                                                      
  18. import java .net.URLConnection;                                 
  19.  
  20. //Text Classes
  21. import java.text.DateFormat;
  22. import java.text.SimpleDateFormat;
  23.  
  24. //Util classes
  25. import java.util.Date;
  26. import java.util.zip.GZIPOutputStream;  
  27.  
  28. //Parse Packages
  29. import org.w3c.dom.*;
  30. import javax.xml.parsers.*;
  31. import org.w3c.dom.Document;
  32. import org.w3c.dom.Element;
  33. import org.xml.sax.SAXParseException;
  34. import org.xml.sax.SAXException;
  35.  
  36. /**
  37.  *   This class contains is a sample client class used to send request XML messages to XML Shipping service of DHL
  38.  * 
  39.  *   @author Dhawal Jogi (Infosys)
  40.  **/
  41. public class  DHLClient
  42. {        
  43.                 public static void main(String[] args)
  44.                 {
  45.                          if(args.length != 3)
  46.                         {
  47.                             System.out.println("Usage : java DHLClient Request XML MessagePath  httpURL ResponseXMLMessage Path \n");
  48.                             System.out.println(" where \n");
  49.                             System.out.println("Request XML MessagePath : The complete path of the request XML message to be send. E.g. C:\\RequestXML\\ShipmentValidateRequest.xml \n");
  50.                             System.out.println("httpURL : The complete url of the server. E.g. http://IP ADDRESS:PORT NUMBER//SERVLET PATH \n");
  51.                             System.out.println("ResponseXMLMessage : The complete directory path where the respose XML messages are to be saved. E.g. C:\\ResponseXML\\\n");
  52.                             System.exit(9);    
  53.                         }
  54.                         else
  55.                         {
  56.                             DHLClient dhlClient = new DHLClient(args[0],args[1],args[2]);
  57.                         }
  58.  
  59.                 }  //end of main method
  60.  
  61.                /**
  62.                 * Private method to write the response from the input stream to a file in local directory.
  63.                 * @param     strResponse  The string format of the response XML message
  64.                 **/
  65.                private static void fileWriter(String strResponse , String responseMessagePath)
  66.                 {
  67.  
  68.                          DateFormat today = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
  69.  
  70.                          String path = responseMessagePath;
  71.                          //String responseFileName = "Dhawal.xml";
  72.                          String responseFileName = new String(checkForRootElement(strResponse)+"_"+today.format(new java.util.Date())+".xml");
  73.                          String ufn = new String(path + responseFileName);
  74.  
  75.                         try
  76.                         {
  77.                                 OutputStream output = new FileOutputStream(ufn);
  78.                                 PrintStream p = null; // declare a print stream object 
  79.                                 // Connect print stream to the output stream
  80.                                 p = new PrintStream( output );
  81.                                 p.println (strResponse);
  82.                                 p.close();
  83.                                 System.out.println("Response received and saved successfully at :" + path +"\n");
  84.                                 System.out.println("The file name is :" + responseFileName);
  85.                         }
  86.                         catch(Exception e)
  87.                         {
  88.                                 System.err.println(e.getMessage());
  89.                         }
  90.                 }// end of  fileWriter method
  91.  
  92.                 /**
  93.                 * Returns the value of the root element of the response XML message send by DHL Server
  94.                 * @param     strResponse  The string format of the response XML message
  95.                 * @return      name of the root element of type string
  96.                 **/
  97.                 private static String checkForRootElement(String strResponse)
  98.                 {
  99.                     Element element = null;
  100.                     try
  101.                     {
  102.                         byte [] byteArray = strResponse.getBytes();
  103.                         ByteArrayInputStream baip = new ByteArrayInputStream( byteArray);
  104.                         DocumentBuilderFactory factory       = DocumentBuilderFactory.newInstance();
  105.                         DocumentBuilder documentBuilder = factory.newDocumentBuilder();
  106.                         Document doc = documentBuilder.parse(baip); //Parsing the inputstream
  107.                         element = doc.getDocumentElement(); //getting the root element           
  108.  
  109.                     }
  110.                     catch(Exception e)
  111.                     {
  112.                         System.out.println("Exception in checkForRootElement "+e.getMessage());
  113.                     }
  114.                         String rootElement = element.getTagName();
  115.                         //Check if root element has res: as prefix
  116.  
  117.                         if(rootElement.startsWith("res:")||rootElement.startsWith("req:")||rootElement.startsWith("err:")||rootElement.startsWith("edlres:")||rootElement.startsWith("ilres:"))
  118.                         {
  119.  
  120.                             int index = rootElement.indexOf(":");
  121.  
  122.                             rootElement = rootElement.substring(index+1);
  123.                         }
  124.                     return rootElement; // returning the value of the root element
  125.                 } //end of checkForRootElement method
  126.  
  127.  /*
  128.        This constructor is used to do the following important operations
  129.         1) Read a request XML
  130.         2) Connect to Server
  131.         3) Send the request XML
  132.         4) Receive response XML message
  133.         5) Calls a private method to write the response XML message
  134.  
  135.         @param requestMessagePath  The path of the request XML message to be send to server
  136.         @param httpURL The http URL to connect ot the server (e.g. http://<ip address>:<port>/application name/Servlet name)
  137.         @param responseMessagePath The path where the response XML message is to be stored
  138. */
  139. public DHLClient(String requestMessagePath, String httpURL, String responseMessagePath)
  140. {
  141.              try
  142.                     {
  143.                                 //Preparing file inputstream from a file        
  144.                                 FileInputStream fis = new FileInputStream(requestMessagePath);
  145.  
  146.                                  //Getting size of the stream
  147.                                  int fisSize = fis.available();
  148.                                  byte[] buffer = new byte[fisSize];
  149.  
  150.                                   //Reading file into buffer                                                                      
  151.                                  fis.read(buffer);
  152.  
  153.                                 String clientRequestXML = new String(buffer);
  154.  
  155.                                 /* Preparing the URL and opening connection to the server*/
  156.                                 URL servletURL = null;
  157.                                 servletURL = new URL(httpURL);
  158.  
  159.                                 URLConnection servletConnection = null;
  160.                                 servletConnection = servletURL.openConnection();
  161.                                 servletConnection.setDoOutput(true);  // to allow us to write to the URL
  162.                                 servletConnection.setDoInput(true);
  163.                                 servletConnection.setUseCaches(false); 
  164.  
  165.                                 /*Code for sending data to the server*/
  166.                                 DataOutputStream dataOutputStream;
  167.                                 dataOutputStream = new DataOutputStream(servletConnection.getOutputStream());
  168.  
  169.                                 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
  170.  
  171.                                  byte[] dataStream = clientRequestXML.getBytes();
  172.                                 dataOutputStream.write(dataStream);  //Writing data to the servlet
  173.                                 dataOutputStream.flush();
  174.                                 dataOutputStream.close();
  175.  
  176.                                  /*Code for getting and processing response from DHL's servlet*/
  177.                                 InputStream inputStream = null;
  178.                                 inputStream = servletConnection.getInputStream();
  179.                                 StringBuffer response = new StringBuffer();
  180.                                 int printResponse;
  181.  
  182.                                 //Reading the response into StringBuffer
  183.                                 while ((printResponse=inputStream.read())!=-1) 
  184.                                 {
  185.                                     response.append((char) printResponse);
  186.                                 }
  187.                                 inputStream.close();
  188.  
  189.                                  //Calling filewriter to write the response to a file
  190.                                 fileWriter(response.toString() , responseMessagePath);
  191.                     }
  192.                      catch(MalformedURLException mfURLex)
  193.                     {
  194.                         System.out.println("MalformedURLException "+mfURLex.getMessage());
  195.                     }
  196.                     catch(IOException e)
  197.                     {
  198.                         System.out.println("IOException "+e.getMessage());
  199.                         //e.printStackTrace();
  200.                     }
  201.  
  202.  
  203.                 }
  204. }// End of Class DHLClient
  205.  
  206.  
Can anyone help me with this?
Cheers!
Jun 22 '10 #1
0 3085

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Phil Powell | last post by:
I have a PHP script that will be doing an @fopen file open command to a Java servlet, sending content via a query string. Problem is that it appears the Java servlet does not receive anything...
1
by: Chris Morgan | last post by:
I'm trying to get php to run on my webserver as a Java Servlet, it works the first time but fails the second time and crashes the JVM with the following error: I have tried the latest versions...
6
by: alan | last post by:
Dear all, I have a servlet problem. When I modified my java servlet program and then uploaded it to my web hosting server, then I start my web browser(I.E) to see the result. But it loaded...
1
by: Vasil Slavov | last post by:
I apologize for the long email. I hope somebody will have time to read it and give some suggestions. I am working on a school project written in Python (using mod_python) and I need to upload a...
3
by: ppcguy | last post by:
i've got a progress bar that tracks a process running on a server (java servlet). i know i can refresh the page and update the status...but this results in the page being redrawn everytime. ...
1
by: Kevin Schneider | last post by:
I am trying to POST an XML string to a Java servlet, but I am getting the error "The underlying connection was closed: An unexpected error occurred on a receive." when I try to get the response....
1
by: Vimala Sri | last post by:
Hello all, Have a great day. I wish to made interaction from c program in unix to the java servlet. That is i want to send a request from the Unix c program to the servlet. ...
4
by: shivapadma | last post by:
1.I installed apache tomcat. 2.I have the following java servlet import java.io.*; import javax.sevlet.*; import javax.servlet.http.*; public class ser extends HttpServlet {
8
by: inpuarg | last post by:
I 'm developing a c# (.net 2.0) windows forms application and in this application i want to connect to a java servlet page (HTTPS) (which is servlet 2.4 and which may be using Web Based SSO Sun...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.