// 20011205 mkr; created
// 20051103 mkr; add GPL, slightly reworked.
/*
author: mkraegeloh@ptc.com, now mkraegeloh@sulis.de

purpose: print data from calling a URL to stdout, possibly including headers.

This program is free software; you can redistribute it and/or modify it under the terms of the
GNU Lesser General Public License as published by the Free Software Foundation;
see http://www.gnu.org/licenses/lgpl.html (und deutsch: http://www.gnu.de/lgpl-ger.html)

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.

*/
package ext.tools;

import java.io.*;
import java.util.*;
import java.lang.*;
import java.net.*;
import com.infoengine.util.Base64;

/**
  *  print data from calling a URL to stdout, possibly including headers (to STDOUT).
  *
  * @author mkraegeloh
  * @version 1.0
  */

public class DumpURL{
   public static final String CVSVersion = "$Header: /usr/local/cvsroot/SULIS/src/ext/tools/DumpURL.java,v 1.3 2007/01/22 10:41:43 mkr Exp $";
   /**
     * main method acquiring the data from a URL and printing it to System.out.
     * <br>options:<ul>
     * <li> -h<br>will output the response headers to System.err
     * <li> -c user pass<br>sets credentials for the request
     * <li> -p [att value att value ...]<br>makes a POST request, passing att=value pairs
     * </ul>
     *
     * @param args	command line parameters
     * @return void	
   */
   public static void main(String[] args){
	String aut = null;
	boolean doPost=false;
	boolean useCredentials=false;
	boolean dumpHeaders=false;
	boolean deserialize=false;
	String cred="";
	int off=0;
	if(args.length == 0){
	   System.out.println("usage: DumpURL [-h] [-c user pass] [-p key val key val ...] protocol://host/...");
	   System.out.println("       -h = headers on stderr");
	   System.out.println("       -c user pass = set credentials");
	   System.out.println("       -p = use post, add pairwise arguments");
	   System.out.println("       -d = deserialize java obj, output with ToolUtils.prettyPrint");
	   System.exit(1);
	}
	try { 
	   while(args[off].startsWith("-")){
		if(args[off].equals("-h")){
		  dumpHeaders=true;
		  off++;
		}
		if(args[off].equals("-d")){
		  deserialize=true;
		  off++;
		}
		if(args[off].equals("-p")){
		  doPost=true;
		  off++;
		}
		if(args[off].equals("-c")){
		  useCredentials=true;
		  cred="Basic " + Base64.encode(args[off+1]+":"+args[off+2]);
		  off+=3;
		}
	   }
	   URL url = new URL(args[off++]);
	   URLConnection urlconnection = url.openConnection();
	   if(useCredentials)
		urlconnection.setRequestProperty("authorization", cred);
	   if(doPost){
		urlconnection.setDoOutput(true);
		PrintWriter o = new PrintWriter(urlconnection.getOutputStream());
		for(int i=off;i<args.length; i+=2){
		   o.println(URLEncoder.encode(args[i]) + "=" + URLEncoder.encode(args[i+1]));
		}
		o.close();
	   }
	   InputStream i=urlconnection.getInputStream();
	   if(deserialize){
	      Object o;
		ObjectInputStream ois = new ObjectInputStream(i);
		o=ois.readObject();
		System.out.println("deserialized obj:");
		System.out.println(ToolUtils.prettyPrint(o));
	   }
	   else{
		byte buf[] = new byte[8192];
		int n;
		while ((n = i.read(buf)) >= 0)
		   System.out.write(buf,0,n);
	   }
	   if(dumpHeaders){
		System.err.println("\nHEADERS (on stderr):\n");
		Map m=urlconnection.getHeaderFields();
		Set s=m.keySet();
		Iterator it=s.iterator();
		Object o;
		while(it.hasNext()){
		   o=it.next();
		   if(o!=null)
			System.err.println(o.toString()+"="+m.get(o));
		}
	   }
	   return;
	}
	catch(Exception exception)
	{
	    String e="error: "+exception;
	    System.out.println("Exception: " + exception);
	    exception.printStackTrace();
	    return;
	}
   }
}
