/**  ServletInvoker  Class
   * @version 1.0  18 October 2000
   * @author Lawrence Rodrigues
   **/
package com.vistech.net;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.net.*;
import java.util.*;

public class ServletInvoker {
   protected URL servletURL;

   public ServletInvoker(URL servlet) {
      servletURL = servlet;
   }

   public InputStream performGet(Properties params){

      try {
        String qs = "";
        if(params != null)qs = createQueryString(params);
        URL servUrl = new URL(servletURL.toExternalForm()+"?"+qs);
        URLConnection uc = servUrl.openConnection();
        uc.setUseCaches(false);
        return uc.getInputStream();
      } catch (Exception e) { return null;}
    }

    public InputStream performPost( Properties params){
       try {
         URLConnection uc = servletURL.openConnection();
         uc.setUseCaches(false);
         uc.setDoInput(true);
         uc.setDoOutput(true);
         uc.setRequestProperty("Content-Type",
                               "application/x-www-form-urlencoded");
         if(params != null) {
            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
            String qs = createQueryString(params);
            out.writeBytes(qs);
            out.flush();
            out.close();
         }
         return uc.getInputStream();
       }catch (Exception e) { return null;}
   }

   protected String createQueryString(Properties params) {
      if(params == null) return null;
      StringBuffer qs= new StringBuffer();
      for (Enumeration e= params.propertyNames(); e.hasMoreElements(); ){
           String key = (String)e.nextElement();
           String value = params.getProperty(key);
           qs.append(URLEncoder.encode(key) + "="+
                     URLEncoder.encode(value)+((e.hasMoreElements())?"&":""));
      }
      return qs.toString();
   }
}