/**
 * @fileoverview
 * 
 * A simple SOAP service implementation that can be deployed on the OpenSCDP Scripting Server
 */


/**
 * Creates a SOAP service instance.
 *
 * @class <p>Provides for a simple SOAP service.</p>
 *
 * @constructor
 */
function SOAPService() {
	this.crypto = new Crypto();
	this.sk = new Key();
	this.sk.setComponent(Key.DES, this.crypto.generateRandom(16));
}



/**
 * Handle incoming SOAP request.
 *
 * @param {XML} the SOAP request
 * @return the SOAP response
 * @type XML
 */
SOAPService.prototype.handleRequest = function (soapRequest) {

	print("Request: " + soapRequest);
	
	var typ = soapRequest.namespace();
	print("Request namespace: " + typ);
	default xml namespace = typ;
	
	var input = soapRequest.input.toString();
	print("Input: " + input);

	input = new ByteString(input, ASCII);
	input = input.pad(Crypto.ISO9797_METHOD_2);
	
	var output = this.crypto.encrypt(this.sk, Crypto.DES_ECB, input);
	
	var response =
			<typ:ConvertResponse xmlns:typ={typ}>
				<typ:output>{output}</typ:output>
			</typ:ConvertResponse>;
	
	print("Response: " + response.toXMLString());

	return response;
}



//
// Create service instance
//
var soapService = new SOAPService();

function handleRequest(req, res) {
	var soapenv = req.getEntityAsXML();
	print("Request:\n" + soapenv.toXMLString());

	var soapns = soapenv.namespace();
	var soap12 = (soapns == "http://www.w3.org/2003/05/soap-envelope")

	var soapprefix = soapns.prefix;
	
	default xml namespace = soapns;

	var soapbody = soapenv.Body.elements();
	print(soapbody[0]);
	var bodyns = soapbody.namespace();
	
	var result = soapService.handleRequest(soapbody);
	
	var response =
	<{soapprefix}:Envelope xmlns:{soapprefix}={soapns}>
		<{soapprefix}:Header/>
		<{soapprefix}:Body>
			<response/>
		</{soapprefix}:Body>
	</{soapprefix}:Envelope>;
	
	response.Body.response = result;
	
	if (soap12) {
		res.setContentType("application/soap+xml; charset=utf-8");
	} else {
		res.setContentType("text/xml; charset=utf-8");
	}

	print("Response:\n" + response.toXMLString());
	res.print(response.toXMLString());
	
	
}

GPSystem.trace("soaptest.js processed...");
