web service --- request soap message

wrap the web servicesoap request to a self defined object.

package com.metlife.ins.product.metguard.service.impl;


import java.util.Map;
import org.w3c.dom.Element;
import com.metlife.ins.product.metguard.framework.util.Constants;
import com.metlife.ins.product.metguard.framework.util.HandleProperties;


/**
 * This class is used to handle a get profile request from a Web Service Proxy.
 * This class build the right XML SOAP request for the Web Service.
 * Copyright:    Copyright (c) 2011
 * @author: cognizant
 * @version 1.0
 */
public class GetProfileRequest extends ProxyRequest{


public static final String URN = HandleProperties.getSmHeaderServiceUrn();
public static final int REQUEST_TYPE = Constants.GET_PROFILE;


    protected transient Element processRequest;
    protected transient Element request;
    protected transient Element credentials;
    protected transient Element userId;
    protected transient Element password;
    protected transient Element data;
    protected transient Element action;
    protected transient Element eseLoginId;
    protected transient Element metRefId;
    protected transient Element prfTypCd;
    
    /*
     * constructor 
     */
    public GetProfileRequest(){
     super();
     this.processRequest = this.document.createElement("m:processRequest");    


     this.request = this.document.createElement("Request");
     this.credentials = this.document.createElement("Credentials");
     this.userId = this.document.createElement("UserID");    
     this.password =  this.document.createElement("Password");
    
     this.data = this.document.createElement("Data");
     this.action = this.document.createElement("Action");
     this.eseLoginId = this.document.createElement("ESELoginID");
     this.metRefId =  this.document.createElement("MetRefID");
     this.prfTypCd =  this.document.createElement("PrflTypCd");
    
     this.document.appendChild(this.processRequest);
     this.processRequest.appendChild(this.request);
    
     this.request.appendChild(this.credentials);
     this.credentials.appendChild(this.userId);
     this.credentials.appendChild(this.password);
    
     this.request.appendChild(this.data);
     this.data.appendChild(this.action);
     this.data.appendChild(this.eseLoginId);
     this.data.appendChild(this.metRefId);
     this.data.appendChild(this.prfTypCd);
    }
    
    /**
     * set the request URN.
     */ 
    public void setProcessRequestUrn(){
     this.processRequest.setAttribute("xmlns:m", GetProfileRequest.URN);
    }
    
    
/**
     * set the user credentials (userid and password).
     */ 
    public void setCredentials(final Map credentialsMap){
        setTextNode(this.userId, credentialsMap.get(Constants.IBSE_CREDENTIAL_USER_ID_KEY)==null?"":
         credentialsMap.get(Constants.IBSE_CREDENTIAL_USER_ID_KEY).toString());
        setTextNode(this.password, credentialsMap.get(Constants.IBSE_CREDENTIAL_PASSWORD_KEY)==null?"":
         credentialsMap.get(Constants.IBSE_CREDENTIAL_PASSWORD_KEY).toString());
    }
    
    /**
     * set the request data.
     */ 
    public void setData(final Map  dataMap){
        setTextNode(this.action, dataMap.get("action")==null?"":dataMap.get("action").toString());
        setTextNode(this.eseLoginId, dataMap.get(Constants.LOGIN_ID)==null?"":dataMap.get(Constants.LOGIN_ID).toString());
        setTextNode(this.metRefId, dataMap.get("metRefId")==null?"":dataMap.get("metRefId").toString());
        setTextNode(this.prfTypCd, dataMap.get("prfTypCd")==null?"":dataMap.get("prfTypCd").toString());
    }
    
    public String getUrn(){
     return GetProfileRequest.URN;
    }
    
    public int getRequestType(){
     return GetProfileRequest.REQUEST_TYPE;
    }
    
}




/**
 * Base class for all documents that are requests used by a Web Service Proxy.
 * Copyright:    Copyright (c) 2011
 * @author: cognizant
 * @version 1.0
 */
public abstract class ProxyRequest extends ProxyDocument {


    /**
     * the request document
     */
    protected Document document;


    /**
     * default constructor. The document is initialised here
     */
    protected ProxyRequest() {
        // get a new document
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        }
        catch(ParserConfigurationException e) {
            throw new ProxyConfigurationException(e, "Error in ProxyRequest");
        }
        this.document = docBuilder.newDocument();
    }


    public Element getRequestElement() {
        return this.document.getDocumentElement();
    }


    
    /**
     * set the request URN.
     */ 
    public abstract void setProcessRequestUrn(); 
/**
     * set the user credentials (userid and password).
     */ 
    public abstract void setCredentials(Map credentialsMap);
    /**
     * set the request data.
     */ 
    public abstract void setData(Map dataMap);
    /**
     * Get the URN of the Web Service.
     */
    public abstract String getUrn();
    /**
     * Get the request type of the Web Service.
     */
    public abstract int getRequestType();
    
    /**
     * method to set the text node of a element. It is assumed that the parent node will only
     * have one child Node that is a Text node. If the child node does not exist a Text node
     * will be created and appended to the parent node. If the child node already exists then
     * the data of the child Text node will be set with the new data.
     * <br>The format of the element is as follows. 'someElement' is the parent <b>Element</b> node with 'sometext'
     * as the child <b>Text</b> node.
     * <pre>
     *    <someElement>sometext</someElement>
     * </pre>
     */
    protected void setTextNode(Element parent, String data) {
        // get the child node
        Node child = parent.getFirstChild();


        // if there is a child node make sure it is a Text Node
        if (child != null) { 
            if (Node.TEXT_NODE == child.getNodeType()) {
                // set the data of the Text node to the new data
                ((Text)child).setData(data);
            }
            else {
                // the child node is not a Text node
                throw new IllegalArgumentException("child node should be a Text node. Parent: " + 
                                                   parent.getNodeName() +  ", Child type: " + child.getNodeType() + ", name: " + child.getNodeName());
            }
        }
        else {
            // there is not child Text node. Append a new Text node
            // to the parent node
            parent.appendChild(this.document.createTextNode(data));
        }
    }


    /**
     * returns xml as a string but does not add a linefeed after each element
     * or indent each child element
     */
    public String getString() {
        return getString(this.document, -1);
    }


    /**
     * returns xml as a formated string. Each element is on an new line
     * and the child elements are indented.
     */
    public String toString() {
        return getString(this.document, 0);
    }
}



package com.metlife.ins.product.metguard.service.impl;


import java.io.PrintWriter;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;




/**
 * Abstract class for a document that is used by a Web Service Proxy. All this class
 * has is methods that will render an org.w3c.dom.Node to a PrintWriter in a readable format.
 * Copyright:    Copyright (c) 2011
 * @author: cognizant
 * @version 1.0
 */
public abstract class ProxyDocument {


    protected ProxyDocument() {
    }


    public String get(Node node) {
        return getString(node, 0);
    }


    // return the string format of the Node and it's child nodes
    protected String getString(Node node, int indent) {
        // convert to a string
        java.io.StringWriter writer = new java.io.StringWriter();
        java.io.PrintWriter out = new java.io.PrintWriter(writer);
        print(node, indent, out);
        return writer.toString();
    } 


    /**
     * Prints the specified node, recursively. If the indent value is one
     * then the output will not be formated with element on newlines and child elements
     * embeded
     */
    protected void print(Node node, int indent, PrintWriter out) {
        boolean lBreak = false;
        String strIndent = "  ";
        // is there anything to do?
        if (node == null) {
            return;
        }
        //"Debug# nodetype= " + node.getNodeType() + " name= " + node.getNodeName()
        int type = node.getNodeType();
        switch (type) {
            // print document
            case Node.DOCUMENT_NODE:
                {
                    out.print("<?xml version=\"1.0\" encoding=\"UTF8\"?>");
                    if (indent >= 0) {
                        out.println();
                    }
                    NodeList children = node.getChildNodes();
                    for (int iChild = 0; iChild < children.getLength(); iChild++) {
                        lBreak = true;
                        print(children.item(iChild), indent < 0 ? indent : indent + 1, out);
                    }
                    if (indent >= 0) {
                        out.println();
                    }
                    break;
                }
                // print element with attributes
            case Node.ELEMENT_NODE:
                {
                    if (indent >= 0) {
                        out.println();
                        // print the indent
                        for (int i = 1; i <= indent; i++) {
                            out.print(strIndent);
                        }
                    }
                    out.print('<');
                    out.print(node.getNodeName());
                    Attr attrs[] = sortAttributes(node.getAttributes());
                    for (int i = 0; i < attrs.length; i++) {
                        Attr attr = attrs[i];
                        out.print(' ');
                        out.print(attr.getNodeName());
                        out.print("=\"");
                        out.print(normalize(attr.getNodeValue(), false));
                        out.print('"');
                    }
                    out.print('>');
                    NodeList children = node.getChildNodes();
                    if (children != null) {
                        int len = children.getLength();
                        Node child = null;
                        for (int i = 0; i < len; i++) {
                            child = children.item(i);
                            if (child.getNodeType() == Node.ELEMENT_NODE)
                                lBreak = true;
                            print(children.item(i), indent < 0 ? indent : indent + 1, out);
                        }       // end for
                    }           // end if
                    break;
                }
                // handle entity reference nodes
            case Node.ENTITY_REFERENCE_NODE:
                {
                    out.print('&');
                    out.print(node.getNodeName());
                    out.print(';');
                    break;
                }
                // print cdata sections
            case Node.CDATA_SECTION_NODE:
                {
                    out.print("<![CDATA[");
                    out.print(node.getNodeValue());
                    out.print("]]>");
                    break;
                }
                // print text
            case Node.TEXT_NODE:
                {
                    out.print(normalize(node.getNodeValue(), false));
                    break;
                }
                // print processing instruction
            case Node.PROCESSING_INSTRUCTION_NODE:
                {
                    out.print("<?");
                    out.print(node.getNodeName());
                    String data = node.getNodeValue();
                    if (data != null && data.length() > 0) {
                        out.print(' ');
                        out.print(data);
                    }
                    out.print("?>");
                    if (indent >= 0) {
                        out.println();
                    }
                    break;
                }
        }       // end switch
        if (type == Node.ELEMENT_NODE) {
            if (lBreak && indent >= 0) {
                out.println();
                // print the indent
                for (int i = 1; i <= indent; i++) {
                    out.print(strIndent);
                }
            }
            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        out.flush();
    }


    /**
     * Normalizes the given string for XML. 
     */
    private String normalize (String s, boolean htmlBreaks) {
        StringBuffer str = new StringBuffer();
        int len = (s != null) ? s.length() : 0;
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '<':
                    {
                        str.append("&lt;");
                        break;
                    }
                case '>':
                    {
                        str.append("&gt;");
                        break;
                    }
                case '&':
                    {
                        str.append("&amp;");
                        break;
                    }
                case '"':
                    {
                        str.append("&quot;");
                        break;
                    }
                case '\r':case '\n':
                    {
                        // htmlBreaks=false, do not append the line break
                        if (htmlBreaks) {
                            str.append("<BR />");
                        }
                        else {
                            break;
                        }
                    }
                default:
                    {
                        str.append(ch);
                    }
            }                   // end switch
        }       //end for
        return  (str.toString());
    }


    /**
     * Returns a sorted list of attributes.
     */
    private Attr[] sortAttributes (NamedNodeMap attrs) {
        int len = (attrs != null) ? attrs.getLength() : 0;
        Attr array[] = new Attr[len];
        for (int i = 0; i < len; i++) {
            array[i] = (Attr)attrs.item(i);
        }
        for (int i = 0; i < len - 1; i++) {
            String name = array[i].getNodeName();
            int index = i;
            for (int j = i + 1; j < len; j++) {
                String curName = array[j].getNodeName();
                if (curName.compareTo(name) < 0) {
                    name = curName;
                    index = j;
                }               // end if
            }                   //end for
            if (index != i) {
                Attr temp = array[i];
                array[i] = array[index];
                array[index] = temp;
            }                   // end if
        }       // end for
        return  (array);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值