Interact uploadify3.1 with jsp

== Environment ==

IBM Rational® Application Developer™ for WebSphere® Software
Version: 7.5.5.5
Build ID: RADO7555-I20111019_2114

(J2EE projects and IBM has its MQv7 API jars inside)


== Introduction ==

The utility is built on our existing WEB application. In order to bypass the existing login authentication, will only use JSP to implement.


== uploadify JSP ==

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- FileUpload and SendMQMesg(only for UAT) -->
<%@page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> 
<html>
<head>
<link rel="stylesheet" href="theme/Master.css" type="text/css">
<link rel="stylesheet" type="text/css" href="script/uploadify-v3.1/uploadify.css">
<script type="text/javascript" src="script/uploadify-v3.1/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="script/uploadify-v3.1/jquery.uploadify-3.1.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('#file_upload').uploadify({
           		 'swf'      		: 'script/uploadify-v3.1/uploadify.swf',
           		 'width'			: 80,
           		 'height'			: 20,
           		 'buttonText'		: 'BROWSE',
          		 'uploader' 		: '<%=request.getContextPath()%>/uploadServlet.jsp',
          		 //'uploader' 		: '<c:url value="MSGUIServlet"><c:param name="sendMQMesg" value="sendMQMesg" /></c:url>',
          		 'successTimeout'	: 60, //second
          		 'fileSizeLimit' 	: '100KB',
            	 'auto' 			: false,
            	 'fileTypeDesc' 	: '*.xml',//;  
                 'fileTypeExts' 	: '*.xml', 
                 'auto' 			: false,  
                 'multi' 			: true,
                 'formData'			: {'environmentType':'','channelType':''},
                 'onUploadStart'	: function(file) {
                 						var env = $("#environmentType").val();
                 						var biz = $("#channelType").val();
                 						$("#file_upload").uploadify("settings", 'formData', {'environmentType':env,'channelType':biz});
                 					  },
                 'onUploadSuccess'  : function(file, data, response) {
                 						//alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
                 						if(response==true)$("#response").html('<font style="color:blue;font-size:12px">' + file.name + ' uploaded at ' + data + '</font>');
                 					  },
                 'onUploadError' 	: function(file, errorCode, errorMsg, errorString) {
                 						if(errorCode!=-280)alert('The file ' + file.name + ' could not be uploaded: ' + errorString);         
                 					  }
        });
    });
    /* understand more usage @ http://www.uploadify.com/documentation/ */
</script>
<title>Upload File To TKY - Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<jsp:include page="/sideMenu.jsp"/>

<table width="800" border="0" cellpadding="5" cellspacing="5" align="center">
	<tr><td>
		
		<H2>Upload File To TKY</H2>
	</td></tr>
	
	<tr><td>
		<table class="searchCriteria">
		<tr>
			<td class="rowname"><br>Choose Test Environment: </td>
			<td><br>
				<select id="environmentType">
					<option value="SAT">SAT</option>	
					<option value="UAT">UAT</option>			
				</select>
			</td>
			<td style="vertical-align:left"><br><img src = "script/Question_mark.png" border="0" width="18" height="18" alt="SAT - For IT to perform system acceptance test 
UAT - For user to perform user acceptance test" /></td>
		</tr>
		
		<tr>
			<td class="rowname"><br>Choose System Channel: </td>
			<td><br>
				<select id="channelType">
					<option value="PSMS">PSMS</option>
					<option value="BETS">BETS</option>
				</select>
			</td>
			<td style="vertical-align:left"><br><img src = "script/Question_mark.png" border="0" width="18" height="18" alt="PSMS - to upload PSMS message files 
BETS - to upload BETS message files" /></td>
		</tr>
		
		<tr>
			<td class="rowname" style="vertical-align:top"><br>Choose File to upload: </td>
			<td>
				<br>
				<input type="file" name="file_upload" id="file_upload" />
				<div id="response"></div>
			</td>
			<td style="vertical-align:top"><br><img src = "script/Question_mark.png" border="0" width="18" height="18" alt="You can choose multiple files. Each file should only contain 1 message. Click 'Start Upload' button to start upload all files. Click 'Cancel All' to cancel all selected files." />
			</td>
		</tr>
		<tr>
			<td style="vertical-align:center">
				<input class="sub1" type="button" value="Start Upload" οnclick="javascript:jQuery('#file_upload').uploadify('upload','*')" />
				<input class="sub1" type="button" value="Cancel All" οnclick="javascript:jQuery('#file_upload').uploadify('cancel','*')" />
			</td>
		</tr>
		
		</table>
	</td></tr>
	
</body>
</html>

== Servlet (jsp) ==

Instead of parsing the HTTP input, we may use apache common-fileupload. As it's only a very simple rough utility, boss don't like to add 2 many 3rd jars.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"
	import="java.io.BufferedReader,
			java.io.PrintWriter,
			java.io.IOException,
			java.util.Date,
			java.util.Locale,
			java.text.SimpleDateFormat,
			com.xxxx.common.logging.LogManager,
			com.ibm.mq.constants.MQConstants,
			com.ibm.mq.MQEnvironment,
			com.ibm.mq.MQException,
			com.ibm.mq.MQMessage,
			com.ibm.mq.MQQueue,
			com.ibm.mq.MQQueueManager,
			com.xxxx.xx.xxxxx.xml.PDUFactory,
			java.util.HashMap"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="c"%>
<%	//   FileUpload and SendMQMesg(only for UAT) - PAUL
		
		/******************************
		 * MQ Environment UAT Setting *
		 ******************************
		 */
		final String HOST_NAME = "133.13.148.57";
		final int PORT = 1414;
		final String MQ_CHANNEL = "SYSTEM.DEF.SVRCONN";
		//final int CCSID = 437;
		final String USER_ID = "";
		final String PASSWORD = "";
		final String MQ_MANAGER = "MWQM";
		final String SAT_PSMS_MQ_QUEUE = "Dummy";
		final String SAT_BETS_MQ_QUEUE = "Dummy";
		final String UAT_PSMS_MQ_QUEUE = "Dummy";
		final String UAT_BETS_MQ_QUEUE = "Dummy";
	
		LogManager.getInstance().logInfo(this, LogManager.MAIN_LOGGER_NAME, " Enter uploadServlet.jsp");		
		
		try {
			/************************************************
			1. Get the http inputstream/chars then parse it 
			*************************************************/
			String contentType = request.getContentType();
			if(contentType.indexOf("multipart/form-data")==-1){
				throw new RuntimeException("Not multipart/form-data");
			}
			int b = contentType.indexOf("boundary=");
			if(b==-1){
				throw new RuntimeException("No boundary");
			}
			String boundary = "--" + contentType.substring(b + 9, contentType.length());
			
			BufferedReader br = request.getReader();
			//PrintWriter pw = new PrintWriter("c:/http.log");
			String tmp;
			String newLine = System.getProperty("line.separator");
			StringBuffer content = new StringBuffer();
			while ((tmp = br.readLine()) != null) {
				content.append(tmp + newLine);
				//pw.println(tmp);
				//pw.flush();
			}
			br.close();
			//very simple rough to parse the http input; hardcode to get related parameters
			String fileName = 
				content.substring(content.indexOf("name=\"Filename\"") + ("name=\"Filename\"" + newLine + newLine).length(), content.indexOf(boundary, content.indexOf("name=\"Filename\"") + ("name=\"Filename\"" + newLine + newLine).length()) - newLine.length()); 
			String environmentType = 
				content.substring(content.indexOf("name=\"environmentType\"") + ("name=\"environmentType\"" + newLine + newLine).length(), content.indexOf(boundary, content.indexOf("name=\"environmentType\"") + ("name=\"environmentType\"" + newLine + newLine).length()) - newLine.length()); 
			String channelType = 
				content.substring(content.indexOf("name=\"channelType\"") + ("name=\"channelType\"" + newLine + newLine).length(), content.indexOf(boundary, content.indexOf("name=\"channelType\"") + ("name=\"channelType\"" + newLine + newLine).length()) - newLine.length()); 
			String fileData = 
				content.substring(content.indexOf("application/octet-stream") + ("application/octet-stream" + newLine + newLine).length(), content.indexOf(boundary, content.indexOf("application/octet-stream") + ("application/octet-stream" + newLine + newLine).length()) - newLine.length()); 
			
			LogManager.getInstance().logInfo(this, LogManager.MAIN_LOGGER_NAME, " Received file="+ fileName + " from HOST=" + request.getRemoteHost() + ";IP=" + request.getRemoteAddr() + ";USER=" + request.getRemoteUser());
			
			
			/************************************************
			2. Generate the complete PDU mesg with fileData and output its key id
			*************************************************/
			PDUFactory fac = new PDUFactory();
			HashMap<String, String> hashMap = fac.constructPDU(fileData, channelType);
			String PDUMesg = hashMap.get("PDU");
			String mesgId = hashMap.get("SenderReference");
			if(PDUMesg==null || mesgId==null){
				throw new RuntimeException("Fail to generate the PDU mesg");
			}
			
			/************************************************
			3. Define which MQ to put by environmentType & channelType
			*************************************************/
			String putQ = null;
			if("SAT".equalsIgnoreCase(environmentType)){
				if("PSMS".equalsIgnoreCase(channelType))putQ = SAT_PSMS_MQ_QUEUE;
				if("BETS".equalsIgnoreCase(channelType))putQ = SAT_BETS_MQ_QUEUE;
			}else if("UAT".equalsIgnoreCase(environmentType)){
				if("PSMS".equalsIgnoreCase(channelType))putQ = UAT_PSMS_MQ_QUEUE;
				if("BETS".equalsIgnoreCase(channelType))putQ = UAT_BETS_MQ_QUEUE;
			}
			if(putQ==null){
				throw new RuntimeException("No MQ can be defined");
			}
			
			/************************************************
			4. init the MQ connection then put the PDU mesg to MQ
			*************************************************/
			MQEnvironment.hostname = HOST_NAME;
			MQEnvironment.port = PORT;
			MQEnvironment.channel = MQ_CHANNEL;
			//MQEnvironment.CCSID = CCSID;
			MQEnvironment.userID = USER_ID;
			MQEnvironment.password = PASSWORD;
			
			MQQueueManager mqqueuemanager = new MQQueueManager(MQ_MANAGER);
			MQQueue mq = mqqueuemanager.accessQueue(putQ, MQConstants.MQOO_OUTPUT);//16
			MQMessage mqMsg = new MQMessage();
			mqMsg.correlationId = MQConstants.MQCI_NONE;
			mqMsg.messageId = MQConstants.MQMI_NONE;
			mqMsg.characterSet = 1208;
			mqMsg.encoding = 273;
			mqMsg.format = "MQSTR";
			mqMsg.writeString(PDUMesg);//put the PDU mesg to MQ
			mq.put(mqMsg);//put the PDU mesg to MQ
			LogManager.getInstance().logInfo(this, LogManager.MAIN_LOGGER_NAME, " mesg <ID=" + mesgId +"> sent to MQ_MANAGER=" + MQ_MANAGER + ";MQ_QUEUE=" + putQ);
			
			mqMsg.clearMessage();
			
			/* To test
			MQQueue mqIn = mqqueuemanager.accessQueue(putQ, MQConstants.MQOO_INPUT_SHARED);	//use input mode to access MQ
			mqIn.get(mqMsg);	//get the mesg from MQ
			PrintWriter pw = new PrintWriter("c:/mq.log");
			while(mqMsg.getDataLength()>0){
				pw.println(mqMsg.readLine());
				pw.flush();
			}
			pw.close();
			mqIn.close();
			*/
			mq.close();
			mqqueuemanager.close();
			
			
			/************************************************
			5. response to uploadify ajax call
			*************************************************/
			SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy kk:mm:ss 'GMT'Z");//29May2013 15:00:29 GMT+0800 
			out.println(sdf.format(new Date()));//response to the uplaodify
			
			LogManager.getInstance().logInfo(this, LogManager.MAIN_LOGGER_NAME, " Exit uploadServlet.jsp");
		} catch (MQException e) {
			LogManager.getInstance().logError(this, LogManager.ERROR_LOGGER_NAME, " uploadServlet : getMessages : MQ ex", e);
		} catch (IOException e) {
			LogManager.getInstance().logError(this, LogManager.ERROR_LOGGER_NAME, " uploadServlet : getMessages : IO ex", e);
		} catch (Exception e){
			LogManager.getInstance().logError(this, LogManager.ERROR_LOGGER_NAME, " uploadServlet : getMessages : ? ex", e);
		}
		
		
%>

Client sends http request in "form-data" format - a sample below:

------------KM7cH2ae0Ij5ae0Ef1Ij5gL6cH2ae0
Content-Disposition: form-data; name="Filename"

abc.xml
------------KM7cH2ae0Ij5ae0Ef1Ij5gL6cH2ae0
Content-Disposition: form-data; name="Filedata"; filename="abc.xml"
Content-Type: application/octet-stream

abcsdsdsdsdsdsdsdsdsdsdsdsdsd
asda
------------KM7cH2ae0Ij5ae0Ef1Ij5gL6cH2ae0
Content-Disposition: form-data; name="Upload"

Submit Query
------------KM7cH2ae0Ij5ae0Ef1Ij5gL6cH2ae0--

 


== JAVA class ==

package com.xxxx.di.xxxxx.xml;

import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class PDUFactory {
	private static final String NS_SAA = "urn:xxxxx:saa:xsd:saa.2.0";
	private static final String NS_PREFIX_SAA = "Saa";
	private static final String NS_SW = "urn:xxxxx:snl:ns.Sw";
	private static final String NS_PREFIX_SW = "Sw";
	private static final String NS_SWINT = "urn:xxxxx:snl:ns.SwInt";
	private static final String NS_PREFIX_SWINT = "SwInt";
	private static final String NS_SWGBL = "urn:xxxxx:snl:ns.SwGbl";
	private static final String NS_PREFIX_SWGBL = "SwGbl";
	private static final String NS_SWSEC = "urn:xxxxx:snl:ns.SwSec";
	private static final String NS_PREFIX_SWSEC = "SwSec";
	private static final String COLON = ":";
	private static final String XML_ENCODING = "UTF-8";
	private static final String NS_APPHDR = "urn:iso:std:iso:20022:tech:xsd:head.001.001.01";
	private static final String NS_PREFIX_APPHDR = "h";
	
	
	public HashMap<String, String> constructPDU(String MJMsg, String channelType) throws Exception {
		
		//get DataPDU and SenderReference
		HashMap<String, String> returnHashMap = constructDataPDU(MJMsg, channelType);
		
		String dataPDU = returnHashMap.get("DataPDU");
		
		//0x1f
		char HEX_US = 0x1F;
		//0x00 NULL character
		char HEX_NL = 0x00;
		
		//construct the whole PDU msg
		String PDU = HEX_US + String.format("%06d", dataPDU.length() + 24);
		//NULL character * 24
		for(int i = 1; i <= 24; i++){
			PDU += HEX_NL;
		}		
		PDU += dataPDU;
		
		//return PDU and SenderReference
		returnHashMap.remove("DataPDU");
		returnHashMap.put("PDU", PDU);
		
		return returnHashMap;
	}	
	
	public HashMap<String, String> constructDataPDU(String MJMsg, String channelType) throws Exception {
		//HashMap for return DataPDU and SenderReference
		HashMap<String, String> returnHashMap = new HashMap<String, String>();
		
		//Parse the MJ XML msg and extract MJ fields
		HashMap<String, String> pduFieldValueHashMap = parseMJXML(MJMsg, channelType);
		
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		
		// Saa:DataPDU root element
		Document document = documentBuilder.newDocument();
		Element dataPDU = document.createElement(NS_PREFIX_SAA + COLON + "DataPDU");
		
		// set NameSapce to Saa:dataPDU
		dataPDU.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + COLON + NS_PREFIX_SAA, NS_SAA);
		dataPDU.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + COLON + NS_PREFIX_SW, NS_SW);
		dataPDU.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + COLON + NS_PREFIX_SWINT, NS_SWINT);
		dataPDU.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + COLON + NS_PREFIX_SWGBL, NS_SWGBL);
		dataPDU.setAttribute(XMLConstants.XMLNS_ATTRIBUTE + COLON + NS_PREFIX_SWSEC, NS_SWSEC);
		
		document.appendChild(dataPDU);
		
		// Saa:DataPDU/Revision 
		Element revision = document.createElement("Revision");
		revision.appendChild(document.createTextNode("2.0.3"));
		dataPDU.appendChild(revision);
		
		// Saa:DataPDU/Header 
		Element header = document.createElement("Header");
		dataPDU.appendChild(header);

		// Saa:DataPDU/Header/Message 
		Element message = document.createElement("Message");
		header.appendChild(message);
		
		// Saa:DataPDU/Header/Message/SenderReference 
		Element senderReference = document.createElement("SenderReference");
		senderReference.appendChild(document.createTextNode(pduFieldValueHashMap.get("SenderReference")));
		message.appendChild(senderReference);
		
		
		// Saa:DataPDU/Header/Message/MessageIdentifier 
		Element messageIdentifier = document.createElement("MessageIdentifier");
		messageIdentifier.appendChild(document.createTextNode(pduFieldValueHashMap.get("MessageIdentifier")));
		message.appendChild(messageIdentifier);
		
		// Saa:DataPDU/Header/Message/Format 
		Element format = document.createElement("Format");
		format.appendChild(document.createTextNode("MX"));
		message.appendChild(format);
		
		// Saa:DataPDU/Header/Message/Sender 
		Element sender = document.createElement("Sender");
		message.appendChild(sender);
		
		// Saa:DataPDU/Header/Message/Sender/DN 
		Element senderDN = document.createElement("DN");
		senderDN.appendChild(document.createTextNode("cn=live-dtm,ou=psms,o=jjsdjpjt,o=xxxxx"));
		sender.appendChild(senderDN);
		
		// Saa:DataPDU/Header/Message/Sender/FullName 
		Element senderFullName = document.createElement("FullName");
		sender.appendChild(senderFullName);
		
		// Saa:DataPDU/Header/Message/Sender/FullName/X1 
		Element senderX1 = document.createElement("X1");
		senderX1.appendChild(document.createTextNode("JJSDJPJTXXX"));
		senderFullName.appendChild(senderX1);
		
		// Saa:DataPDU/Header/Message/Receiver 
		Element receiver = document.createElement("Receiver");
		message.appendChild(receiver);
		
		// Saa:DataPDU/Header/Message/Receiver/DN 
		Element receiverDN = document.createElement("DN");
		receiverDN.appendChild(document.createTextNode("cn=live-dtm,ou=psms,o=xxxxjpjt,o=xxxxx"));
		receiver.appendChild(receiverDN);
		
		// Saa:DataPDU/Header/Message/Receiver/FullName 
		Element receiverFullName = document.createElement("FullName");
		receiver.appendChild(receiverFullName);
		
		// Saa:DataPDU/Header/Message/Receiver/FullName/X1 
		Element receiverX1 = document.createElement("X1");
		receiverX1.appendChild(document.createTextNode("xxxxJPJTXXX"));
		receiverFullName.appendChild(receiverX1);
		
		// Saa:DataPDU/Header/Message/InterfaceInfo 
		Element interfaceInfo = document.createElement("InterfaceInfo");
		message.appendChild(interfaceInfo);
		
		// Saa:DataPDU/Header/Message/InterfaceInfo/Saa:UserReference 
		Element userReference = document.createElement(NS_PREFIX_SAA + COLON + "UserReference");
		userReference.appendChild(document.createTextNode(pduFieldValueHashMap.get("UserReference")));
		interfaceInfo.appendChild(userReference);
		
		// Saa:DataPDU/Header/Message/NetworkInfo 
		Element networkInfo = document.createElement("NetworkInfo");
		message.appendChild(networkInfo);
		
		// Saa:DataPDU/Header/Message/NetworkInfo/Service 
		Element service = document.createElement("Service");
		service.appendChild(document.createTextNode(pduFieldValueHashMap.get("Service")));
		networkInfo.appendChild(service);
		
		// Saa:DataPDU/Header/Message/NetworkInfo/xxxxxNetNetworkInfo 
		Element xxxxxNetNetworkInfo = document.createElement("xxxxxNetNetworkInfo");
		networkInfo.appendChild(xxxxxNetNetworkInfo);
		
		// Saa:DataPDU/Header/Message/NetworkInfo/xxxxxNetNetworkInfo/xxxxxRef
		Element xxxxxRef = document.createElement("xxxxxRef");
		xxxxxRef.appendChild(document.createTextNode(pduFieldValueHashMap.get("xxxxxRef")));
		xxxxxNetNetworkInfo.appendChild(xxxxxRef);		
		
		// Saa:DataPDU/Body
		Element body = document.createElement("Body");
		dataPDU.appendChild(body);	
		
		//XML convert to String
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty("encoding", XML_ENCODING);
        
        DOMSource source = new DOMSource(document);
        
        StringWriter stringWriter = new StringWriter();
        StreamResult result = new StreamResult(stringWriter);
        //StreamResult result2 = new StreamResult(new File("C:\\test.txt"));
    
        transformer.transform(source, result);
        
        //replace <Body/> by MJMsg uploaded from UI
        //return DataPDU and SenderReference
        returnHashMap.put("DataPDU", stringWriter.toString().replace("<Body/>", MJMsg));
        returnHashMap.put("SenderReference", pduFieldValueHashMap.get("SenderReference"));
        
        return returnHashMap;
	}
	
	public HashMap<String, String> parseMJXML(String MJMsg, String channelType) throws Exception {
		
		// Parse XML to DOM
		InputSource inputSource = new InputSource();
	    inputSource.setCharacterStream(new StringReader(MJMsg));	
	    
	    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		// parse XML with NameSpace
	    documentBuilderFactory.setNamespaceAware(true);	    
	    Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource);

	    //Create current TimeStamp and convert to string
	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	    String dateString = simpleDateFormat.format(new Date());
	    
	    //Setup PDUFieldValue for function return
	    HashMap<String, String> pduFieldValueHashMap = new HashMap<String, String>();
	    
	    pduFieldValueHashMap.put("SenderReference", channelType + dateString);
	    pduFieldValueHashMap.put("UserReference", channelType + dateString);
	    
	    //use XPath to parse XML
	    XPathFactory xpathFact = XPathFactory.newInstance();
	    XPath xpath = xpathFact.newXPath();
	    
	    //resolved Prefix to a NameSpace
	    NamespaceContext namespaceContext = new NamespaceContext(){

			@Override
			public String getNamespaceURI(String s) {
				// TODO Auto-generated method stub
				return NS_APPHDR;
			}

			@Override
			public String getPrefix(String s) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Iterator<?> getPrefixes(String s) {
				// TODO Auto-generated method stub
				return null;
			}
	    	
	    };
	    // parse XML with NameSpace
	    xpath.setNamespaceContext(namespaceContext);
	    
	    //extract /AppHdr/MsgDefIdr
	    XPathExpression xpathExpr = xpath.compile("/Body" + ("/AppHdr/MsgDefIdr").replace("/", "/"+NS_PREFIX_APPHDR+COLON));
	    pduFieldValueHashMap.put("MessageIdentifier", xpathExpr.evaluate(document, XPathConstants.STRING).toString());
	    //extract /AppHdr/BizSvc
	    xpathExpr = xpath.compile("/Body" + ("/AppHdr/BizSvc").replace("/", "/"+NS_PREFIX_APPHDR+COLON));
	    String bsCode = xpathExpr.evaluate(document, XPathConstants.STRING).toString();
	    
	    //extract /AppHdr/CreDt
	    xpathExpr = xpath.compile("/Body" + ("/AppHdr/CreDt").replace("/", "/"+NS_PREFIX_APPHDR+COLON));
	    pduFieldValueHashMap.put("xxxxxRef", "SWITCH21-" + xpathExpr.evaluate(document, XPathConstants.STRING).toString());
	    
	    //set value for Service by MsgType and BSCode
	    List<String> typeList_BETS_SB = new ArrayList<String>();
	    typeList_BETS_SB.add("sese.024.001.03_05-22000020-00101");
	    typeList_BETS_SB.add("sese.025.001.03_05-22000050-00101");
	    
	    List<String> typeList_BETS_CP = new ArrayList<String>();
	    typeList_BETS_CP.add("sese.024.001.03_06-22000020-00101");
	    typeList_BETS_CP.add("sese.025.001.03_06-22000050-00101");
	    
	    if(channelType == "PSMS"){
	    	pduFieldValueHashMap.put("Service", "xxxxx.psms.nsm!p");
	    }else{
	    	if(typeList_BETS_SB.contains(pduFieldValueHashMap.get("MessageIdentifier")+"_"+bsCode)){
	    		pduFieldValueHashMap.put("Service", "xxxxx.bets.sb!p");
	    	}else if(typeList_BETS_CP.contains(pduFieldValueHashMap.get("MessageIdentifier")+"_"+bsCode)){
	    		pduFieldValueHashMap.put("Service", "xxxxx.bets.cp!p");
	    	}else{
	    		pduFieldValueHashMap.put("Service", "xxxxx.bets.st!p");
	    	}    	
	    }    
	    
		return pduFieldValueHashMap;
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值