package com.ejie.p06b.x43.handler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.namespace.QName;
import javax.xml.rpc.JAXRPCException;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import weblogic.webservice.GenericHandler;

public class X43TokenHandler extends GenericHandler{
	
	HandlerInfo hi;
	
	  public void init(HandlerInfo info) {
	    hi = info;
	  }

	  public QName[] getHeaders() {
	    return hi.getHeaders();
	  }


	
	 public boolean handleRequest(MessageContext m)  {
		 try {      
	     
		 SOAPMessageContext ctx = (SOAPMessageContext) m;
		 SOAPMessage message = ctx.getMessage();
	
		 String sSessionToken = (String)hi.getHandlerConfig().get("sessionToken");
			
			// recuperar cabecera SOAP
			SOAPHeader soapHeader = message.getSOAPPart().getEnvelope().getHeader();
			if (sSessionToken.startsWith("<?xml version=\"1.0\"")) {
				int pos = sSessionToken.indexOf(">") + 1;
				sSessionToken = sSessionToken.substring(pos).trim();
			}
			soapHeader.addTextNode(sSessionToken);
			
			ByteArrayOutputStream myByteArrayOutputString = new ByteArrayOutputStream();
			message.writeTo(myByteArrayOutputString);
			String sSoapMessage = new String(myByteArrayOutputString.toByteArray(), "UTF-8");
			sSoapMessage = processHeaderScape(sSoapMessage);
			ByteArrayInputStream in = new ByteArrayInputStream(sSoapMessage.getBytes());
			MessageFactory factory = MessageFactory.newInstance();
			message =  factory.createMessage(null, in);
			ctx.setMessage(message);		
		 
		 
		} catch (Exception e) { 
			e.printStackTrace(); 
			throw new JAXRPCException(e);
		}    
		return true; 
		
		}
	 
	 
		private String processHeaderScape(String sSoapMessage) {

			int posEndIni = sSoapMessage.indexOf("Header>") + "Header>".length();

			int posEndEnd = sSoapMessage.indexOf("Header>", posEndIni) + "Header>".length() - 1;
			int posIniEnd = sSoapMessage.lastIndexOf("<", posEndEnd);

			StringBuffer sb = new StringBuffer();
			sb.append(sSoapMessage.substring(0, posEndIni));

			StringBuffer headerContentSb = new StringBuffer();
			String headerContent = sSoapMessage.substring(posEndIni, posIniEnd);
			headerContent = headerContent.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
			headerContentSb.append(headerContent);
			sb.append(headerContentSb);
			sb.append(sSoapMessage.substring(posIniEnd));
		    String ret = sb.toString();

	
			return ret;
		}
		
	 
	 public boolean handleResponse(MessageContext context) {	
   return true;
		  
	 }


	 
	 public boolean handleResponse(MessageContext m, String error) {    	
		return true;  
	}


}
