Creating the order processing application

The order processing application is a Java application. The source code is described.

About this task

The order processing application consists of two Java source files, Main.java and OrderProcessor.java. Main.java makes the GET request to the new orders file and then calls OrderProcessor.java. OrderProcessor.java processes the orders by checking the stock levels of the product ordered, makes the POST requests to either the fulfilled or unfulfilled files. The last section of the OrderProcessor.java makes the DELETE request to the new orders file to delete the original order.

You must create the two source files and copy the Java code into them, compile the files into a .class file and then run the program.

To simplify the order processing application, the stock levels for all products has been set to 100. Code for a dynamic stock levels could be coded, however, it is outside the scope of this scenario.

Procedure

  1. Create the Main.java source file and copy the following Java code into it.
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class Main {
    
    	/**
    	 * @param args
    	 */
    	private static String ordersURL = "http://example.com:50001/cics/services/orderFile/feed";
    
    	public static void main(String[] args) {
    
    		// Create the order processor object
    		OrderProcessor worker = new OrderProcessor();
    
    		
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    		DocumentBuilder db;
    		NodeList nodesInOrder = null;
    		try {
    			db = dbf.newDocumentBuilder();
    			// Make an XML doc for the ATOM XML for the Orders feed
    			Document doc = db.parse(new URL(ordersURL).openStream());
    			
    			// Get a list of all entries - each one representing a new order
    			NodeList list = doc.getElementsByTagName("entry");
    			System.out.println("We have " + list.getLength() + " new orders\n");
    			
    			// List of fields we want from the XML order entry
    			String order_number = "";
    			String item_id = "";
    			String description = "";
    			String quantity = "";
    			String price = "";
    			String fulfilled = "";
    			NodeList detailList = null;
    			for (int i = 0; i < list.getLength(); i++) {
    				nodesInOrder = list.item(i).getChildNodes();
    
    				
    
    				for (int p = 0; p < nodesInOrder.getLength(); p++) {
    					Node orderFields = nodesInOrder.item(p);
    					// Get the content XML node
    					if (orderFields.getNodeName().equals("content")) {
    						// Get the OrdStruc XML node
    						Node OrdStruc = orderFields.getFirstChild();
    						// Get the order_details XML node
    						Node details = OrdStruc.getFirstChild();
    						// Get all nodes in the order_details node
    						detailList = details.getChildNodes();
    						for (int n = 0; n < detailList.getLength(); n++) {
    							Node detailItem = detailList.item(n);
    							String nodeName = detailItem.getNodeName();
    							// if we have the order_number
    							if (nodeName.equals("order_number")) {
    								order_number = detailItem.getTextContent();
    								continue;
    							}
    							
    							// if we have the item_id
    							if (nodeName.equals("item_id")) {
    								item_id = detailItem.getTextContent();
    								continue;
    							}
    							// if we have the item_desc
    							if (nodeName.equals("item_desc")) {
    								description = detailItem.getTextContent();
    								continue;
    							}
    							// if we have the item_quant
    							if (nodeName.equals("item_quant")) {
    								quantity = detailItem.getTextContent();
    								continue;
    							}
    							// if we have the item_price
    							if (nodeName.equals("item_price")) {
    								price = detailItem.getTextContent();
    								continue;
    							}
    							// if we have the fulfilled
    							if (nodeName.equals("fulfilled")) {
    								fulfilled = detailItem.getTextContent();
    								continue;
    							}
    							// There is some unrecognised XML nodes...
    								System.out
    										.println("Unrecognised segment of XML:");
    								System.out.println(nodeName
    										+ " and the content is :"
    										+ detailItem.getTextContent());
    
    							}
    
    						}
    					}
    
    				}
    
    				System.out.println("Order Number:" + order_number);
    				System.out.println("Item ID:" + item_id);
    				System.out.println("Description:" + description);
    				System.out.println("Quantity:" + quantity);
    				System.out.println("Item Price:" + price);
    				System.out.println("Fulfilled:" + fulfilled);
    				System.out.println("\n\n");
    
    				
    				worker.processOrder(order_number, item_id, description, Integer.valueOf(quantity), 
            price,Boolean.getBoolean(fulfilled),nodesInOrder);
    
    		} 
    		catch(Exception e){
    			
    		}
    
    	}
    
    }
  2. Create the OrderProcessor.java source file and copy the following Java code into it.
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    import org.apache.http.Header;
    import org.apache.http.HeaderElement;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.cache.HeaderConstants;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.InputStreamEntity;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.w3c.dom.NodeList;
    
    public class OrderProcessor {
    	
    	
    	private URL successUrl;
    	private URL deleteOrderEntry;
    	private URL failUrl;
    	
    	
    	public OrderProcessor() {
    
    	}
    	
    	private void writeToSuccessFile(String order_number, String item_id, String description, int quantity, 
     String item_price, boolean fulfilled, NodeList detailList){
    		try{
    		   URLConnection urlConnection;
    	        DataOutputStream outStream;
    	        DataInputStream inStream;
    
    	        //  Build request body
             String body ="<?xml version=\"1.0\" ?><entry xmlns=\"http://www.w3.org/2005/Atom\">;
             body += "<content><OrdStruc xmlns=\"http://www.OrdStruc.com\"><order_details>:;
             body += "<order_number>"+order_number+"</order_number><item_id>"+item_id+"</item_id>";
             body += "<item_desc>"+description+"</item_desc><item_quant>"+quantity+"</item_quant>";
             body += "<item_price>"+item_price+"</item_price><fulfilled>Y</fulfilled></order_details></OrdStruc></content></entry>";
    
             String bodyLength = new String();
    	        bodyLength += body.length();
    	        // Create connection
    	        successUrl= new URL("http://example.com:50001/cics/services/goodFile/feed");  
    	        urlConnection = successUrl.openConnection();
    
             ((HttpURLConnection)urlConnection).setRequestMethod("POST");
    	        urlConnection.setDoInput(true);
    	        urlConnection.setDoOutput(true);
    	        urlConnection.setUseCaches(false);
    	        urlConnection.setRequestProperty("Content-Type", "application/atom+xml;type=entry");
    	        urlConnection.setRequestProperty("Host", "example.com" );
    	 
    	        // Create I/O streams
    	        outStream = new DataOutputStream(urlConnection.getOutputStream());
    	        // Send request
    	        outStream.writeBytes(body);
    	        outStream.flush();
    	        outStream.close();
    	        
    	        inStream = new DataInputStream(urlConnection.getInputStream());
    	 
    	        // Get Response
    	        // - For debugging purposes only!
    	        String buffer;
    	        while((buffer = inStream.readLine()) != null) {
    	            System.out.println(buffer);
    	        }
    	 
    	        // Close I/O streams
    	        inStream.close();
    	        outStream.close();
    	    }
    	    catch(Exception ex) {
    	        System.out.println("Exception cauught:\n"+ ex.toString());
    	    }
    	}
    	
    	
    
    	public void processOrder(String order_number, String item_id,
    			          String description, int quantity, String item_price,
    			          boolean fulfilled, NodeList detailList) {
    
    		     System.out.println("\n\n===================================");
    		     System.out.println("Starting to process the order");
    		     System.out.println("=======================================\n\n");
    		
    		     //we have enough stock
    		     if(quantity < 100){
    			          //add to success file
    			          //with fulfilled being true
    			          //remove from orders file 
    			          writeToSuccessFile(order_number,item_id,description,quantity,item_price,fulfilled,detailList);
    			          deleteFromOrdersFile(order_number);
    				
    		     }
    		     //we do not have enough stock - reject the order
    		     else{
    			          //add to fail file
    			          writeToFailFile(order_number,item_id,description,quantity,item_price,fulfilled,detailList);
    		}
    		
    		
    		     System.out.println("\n\n===================================");
    		     System.out.println("Processed Order");
    		     System.out.println("=======================================\n\n");
    		
    
    	}
    
    	private void writeToFailFile(String order_number, String item_id,
    			          String description, int quantity, String item_price,
    			          boolean fulfilled, NodeList detailList) {
    		// TODO Auto-generated method stub
    		try{
    			
    		failUrl= new URL("http://example.com:50001/cics/services/failFile/feed");
    			   URLConnection urlConnection;
    		     DataOutputStream outStream;
    		     DataInputStream inStream;
    		 
    		     // Build request body
             String body ="<?xml version=\"1.0\" ?><entry xmlns=\"http://www.w3.org/2005/Atom\">;
             body += "<content><OrdStruc xmlns=\"http://www.OrdStruc.com\"><order_details>:;
             body += "<order_number>"+order_number+"</order_number><item_id>"+item_id+"</item_id>";
             body += "<item_desc>"+description+"</item_desc><item_quant>"+quantity+"</item_quant>";
             body += "<item_price>"+item_price+"</item_price><fulfilled>N</fulfilled></order_details></OrdStruc></content></entry>";
               
             String bodyLength = new String();
    		      bodyLength += body.length();
    		      // Create connection
    		         
    		      urlConnection = successUrl.openConnection();
    
    		      ((HttpURLConnection)urlConnection).setRequestMethod("POST");
    		      urlConnection.setDoInput(true);
    		      urlConnection.setDoOutput(true);
    		      urlConnection.setUseCaches(false);
    		      urlConnection.setRequestProperty("Content-Type", "application/atom+xml;type=entry");
    		      urlConnection.setRequestProperty("Host", "example.com" );
    		 
    		      // Create I/O streams
    		      outStream = new DataOutputStream(urlConnection.getOutputStream());
    		        
    		 
    		      // Send request
    		      outStream.writeBytes(body);
    		      outStream.flush();
    		      outStream.close();
    		        
    		      inStream = new DataInputStream(urlConnection.getInputStream());
    		 
    		      // Get Response
    		      // - For debugging purposes only!
    		      String buffer;
    		      while((buffer = inStream.readLine()) != null) {
    		          System.out.println(buffer);
    		        }
    		 
    		      // Close I/O streams
    		      inStream.close();
    		      outStream.close();
    		    }
    		    catch(Exception ex) {
    		      System.out.println("Exception cauught:\n"+ ex.toString());
    		    }
    	}
    
    	private void deleteFromOrdersFile(String order_number) {
    		// TODO Auto-generated method stub
    		   try{
    	        URLConnection urlConnection;
    	        DataOutputStream outStream;
    	        DataInputStream inStream;
    	 
    	        
    	        // Create connection
    	        deleteOrderEntry = new URL("http://example.com:50001/cics/services/orders/entry/"+order_number);
    	        urlConnection = deleteOrderEntry.openConnection();
    
    	        ((HttpURLConnection)urlConnection).setRequestMethod("DELETE");
    	        urlConnection.setDoInput(true);
    	        urlConnection.setDoOutput(true);
    	        urlConnection.setUseCaches(false);
    	        urlConnection.setRequestProperty("Host", "example.com" );
    	 
    
    	        inStream = new DataInputStream(urlConnection.getInputStream());
    	 
    	        String buffer;
    	        while((buffer = inStream.readLine()) != null) {
    	            System.out.println(buffer);
    	        }
    	 
    	        // Close I/O streams
    	        inStream.close();
    	    }
    	    catch(Exception ex) {
    	        System.out.println("Exception cought:\n"+ ex.toString());
    	    }
    		
    	}
    }
  3. Compile the source files into a .class file
  4. Run the order processor application

Results

An order processing application is created that can obtain order information from the new orders Atom collection, process the order, make a POST request to either the fulfilled or unfulfilled Atom collection, and make a DELETE request to delete the original order.