/*
 * Created on Jul 17, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

package XmlCommunication;
import java.net.*;
import java.io.*;
import java.util.*;

public class ServletConnection {

	/**
	 * This is the constructor for ServletConnection.java
	 */
	public ServletConnection() {
	}

	/**
	 * This method is being used for sending an xml packet to the 
	 * TMS mediation engine.
	 * @param str The xml string to be sent to TMS.
	 * @return String The xml string received back in response from the TMS.
	 */
	public String sendXml(String str) {
		try {
			String path = System.getProperty("user.dir");
			System.out.println(path);

			Properties p = new Properties();
			p.load(new FileInputStream("stocktrading.txt"));
			String location = p.getProperty("URL");

			//String location = "http://127.0.0.1:8080/tmsMediation/MediationEngine";
			System.out.println("SERVLET LOCATION : " + location);

			//	connect to the servlet
			URL testServlet = new URL(location);
			URLConnection connection =
				(URLConnection) testServlet.openConnection();

			//	inform the connection that we will send output and accept input
			connection.setDoInput(true);
			connection.setDoOutput(true);

			//	Don't use a cached version of URL connection.
			connection.setUseCaches(false);
			connection.setDefaultUseCaches(false);

			//	Specify the content type that we will send binary data
			connection.setRequestProperty(
				"Content-Type",
				"application/x-www-form-urlencoded");

			//	get input and output streams on servlet
			DataOutputStream dos =
				new DataOutputStream(connection.getOutputStream());
			//InputStreamReader in = new InputStreamReader(connection.getInputStream());

			//	send your data to the servlet
			String content =
				"j_username="
					+ URLEncoder.encode("username", "UTF-8")
					+ "&j_password="
					+ URLEncoder.encode("password", "UTF-8")
					+ "&TmsXmlData="
					+ URLEncoder.encode(str, "UTF-8");

			dos.writeBytes(content);
			dos.flush();
			dos.close();

			// read the response from the servlet
			// Wait for response message from next party
			DataInputStream dis;
			dis = new DataInputStream(connection.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));

			String output = "";
			String temp;
			while ((temp = br.readLine()) != null) {
				output += temp + "\n";
			}
			dis.close();

			return output;

		} catch (Exception e) {
			System.out.println("Exception occurred: " + e.toString());
			return null;
		}
	}
}
