import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class damoon {
    public static void main(String[] args) throws IOException{
        String s = "";
        try {
            damoon d = new damoon();
            s = d.SendReceive("https://damoon.bankmelli-iran.com/DamoonVerificationController?x_login=822059300134&x_amount=4444444&x_fp_sequence=120356116&x_fp_timestamp=1347861315&x_currency_code=Rial&x_fp_hash=30498fb635a0882826267382ed87ffc2");
        } catch (KeyManagementException ex) {
            Logger.getLogger(damoon.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(damoon.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(s);
    }

    public String SendReceive(String pathURL) throws IOException,
            KeyManagementException, NoSuchAlgorithmException {
        String headerFieldKeys = "", headerFieldValues = "", content = "";
        try {
            // Create a URL for the desired page
            Vector tokenizedURL = tokenizePostURL(pathURL);
            if (tokenizedURL == null
                    || ((String) tokenizedURL.elementAt(0)).equals("")) {
                throw new IOException(
                        "Bad URL in post method simulator when trying to connect to merchant site. Requested URL : "
                        + pathURL);
            }
            URL url = new URL(pathURL);
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
            };
// Install the all-trusting trust manager // When you do this, you mean that you trust to certs. In our system it makes no problem!

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// We override this method to ignor the warnings of HostNameVerifier action.
            javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() {
                public boolean verify(String urlHostname, SSLSession ssls) {
                    System.out.println("WARNING: Hostname is not matched for cert.");
                    return true;
                }
            };

            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

            HttpsURLConnection https_conn = (HttpsURLConnection) url.openConnection();
            OutputStreamWriter out= null;
            https_conn.setRequestMethod("POST");
            https_conn.setRequestProperty("Content-type", "text/plain");
            https_conn.setDoOutput(true);
            https_conn.setDoInput(true);
            https_conn.setUseCaches(false);
//            try{
                out = new OutputStreamWriter(https_conn.getOutputStream());
//            }
//            catch(Exception e){
//                System.out.println(e.getMessage());
//            }
            out.flush();
            out.close();

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(https_conn.
                    getInputStream()));
            String str;
            while ((str = in.readLine()) != null) {
                content += str;
            }
            in.close();
        } catch (MalformedURLException e) {
            throw new IOException(
                    "Exception in communicating with merchant in URL Simulator because of : \n"
                    + e.getLocalizedMessage());
        } catch (IOException e) {
            throw new IOException(
                    "Exception in communicating with merchant in URL Simulator because of : \n"
                    + e.getLocalizedMessage());
        }
        return content;
    
    }
//***********************************************************************************************************************
private Vector tokenizePostURL(String xURL) {
    if (xURL == null || xURL.equals(""))
      return null;
    Vector tmpVector = new Vector(), retVector = new Vector();
    int myIndx = xURL.indexOf("?");
    if (myIndx == -1)
      tmpVector.addElement( (String) xURL);
    else {
      tmpVector.addElement( (String) xURL.substring(0, myIndx));
      xURL = xURL.substring(myIndx + 1);
      while (myIndx != -1) {
        myIndx = xURL.indexOf("&");
        if (myIndx == -1)
          tmpVector.addElement( (String) xURL);
        else
          tmpVector.addElement( (String) xURL.substring(0, myIndx));
        xURL = xURL.substring(myIndx + 1);
      }
    }
    String tmp;
    int tmpIndx;
    retVector.addElement(tmpVector.elementAt(0));
    for (int j = 1; j < tmpVector.size(); j++) {
      tmp = (String) tmpVector.elementAt(j);
      tmpIndx = tmp.indexOf("=");
      retVector.addElement(tmp.substring(0, tmpIndx));
      retVector.addElement(tmp.substring(tmpIndx + 1));
    }
    return retVector;
  }    
}
