Login | Register
My pages Projects Community openCollabNet

Discussions > cvs > CVS update: /antelope/src/ise/antelope/tasks/

antelope
Discussion topic

Back to topic list

CVS update: /antelope/src/ise/antelope/tasks/

Author danson
Full name Dale Anson
Date 2004-10-12 18:42:50 PDT
Message User: danson
Date: 04/10/12 18:42:50

Modified:
 /antelope/src/ise/an​telope/tasks/
  PostTask.java

Log:
 updates

File Changes:

Directory: /antelope/src/ise/an​telope/tasks/
====================​====================​====

File [changed]: PostTask.java
Url: http://antelope.tigr​is.org/source/browse​/antelope/src/ise/an​telope/tasks/PostTas​k.java?r1=1.4&r2​=1.5
Delta lines: +626 -431
-----------------------
--- PostTask.java 4 Sep 2004 03:52:16 -0000 1.4
+++ PostTask.java 13 Oct 2004 01:42:49 -0000 1.5
@@ -60,18 +60,16 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.HttpURLConnection;
 
 import java.net.URL;
 import java.net.URLConnection;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
-import java.net.HttpURLConnection;
 
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.Vector;
+import java.util.*;
 
 import org.apache.tools.ant​.BuildException;
 import org.apache.tools.ant.Project;
@@ -89,7 +87,7 @@
  * and the appropriate property values will be filled in at run time.
  *
  * @author Dale Anson, danson at germane-software dot com
- * @version $Revision: 1.4 $
+ * @version $Revision: 1.5 $
  */
 public class PostTask extends Task {
 
@@ -111,10 +109,17 @@
    private boolean verbose = true;
    /** want to keep the server response? */
    private boolean wantResponse = true;
+
+ private String property = null;
+
    /** how long to wait for a response from the server */
    private long maxwait = 180000; // units for maxwait is milliseconds
    /** fail on error? */
    private boolean failOnError = false;
+
+ private String cookiePrefix = null;
+ private boolean useCookies = false;
+
    /** connection to the server */
    private URLConnection connection = null;
    /** for thread handling */
@@ -126,7 +131,7 @@
     *
     * @param name the url to post to.
     */
- public void setTo( URL name ) {
+ public void setTo(URL name) {
       to = name;
    }
 
@@ -136,29 +141,29 @@
     *
     * @param f the file
     */
- public void setFile( File f ) {
+ public void setFile(File f) {
       propsFile = f;
    }
 
 
    /**
- * Set the name of a file to save the response to. Optional. Ignored if "want
- * response" is false.
+ * Set the name of a file to save the response to. Optional. Ignored if
+ * "want response" is false.
     *
     * @param f the file
     */
- public void setLogfile( File f ) {
+ public void setLogfile(File f) {
       log = f;
    }
 
 
    /**
- * Should the log file be appended to or overwritten? Default is true, append
- * to the file.
+ * Should the log file be appended to or overwritten? Default is true,
+ * append to the file.
     *
     * @param b append or not
     */
- public void setAppend( boolean b ) {
+ public void setAppend(boolean b) {
       append = b;
    }
 
@@ -169,7 +174,7 @@
     *
     * @param b true = verbose
     */
- public void setVerbose( boolean b ) {
+ public void setVerbose(boolean b) {
       verbose = b;
    }
 
@@ -180,16 +185,20 @@
     *
     * @param b print/log server response
     */
- public void setWantresponse( boolean b ) {
+ public void setWantresponse(boolean b) {
       wantResponse = b;
    }
 
+ public void setProperty(String name) {
+ property = name;
+ }
+
    /**
     * Sets the encoding of the outgoing properties, default is UTF-8.
     *
     * @param encoding The new encoding value
     */
- public void setEncoding( String encoding ) {
+ public void setEncoding(String encoding) {
       this.encoding = encoding;
    }
 
@@ -199,15 +208,15 @@
     * process (sending and receiving), maxwait is applied separately to each
     * part, that is, if 180 is passed as the wait parameter, this task will
     * spend at most 3 minutes to connect to the remote server and at most
- * another 3 minutes waiting on a response after the post has been sent. This
- * means that the wait period could total as much as 6 minutes (or 360
+ * another 3 minutes waiting on a response after the post has been sent.
+ * This means that the wait period could total as much as 6 minutes (or 360
     * seconds). <p>
     *
     * The default wait period is 3 minutes (180 seconds).
     *
     * @param wait time to wait in seconds, set to 0 to wait forever.
     */
- public void setMaxwait( int wait ) {
+ public void setMaxwait(int wait) {
       maxwait = wait * 1000;
    }
 
@@ -217,10 +226,28 @@
     *
     * @param fail true = fail the build, default is false
     */
- public void setFailonerror( boolean fail ) {
+ public void setFailonerror(boolean fail) {
       failOnError = fail;
    }
 
+ /**
+ * Sets the cookieprefix attribute of the PostTask object
+ *
+ * @param prefix The new cookieprefix value
+ */
+ public void setCookieprefix(String prefix) {
+ cookiePrefix = prefix;
+ }
+
+ /**
+ * Sets the usecookies attribute of the PostTask object
+ *
+ * @param use The new usecookies value
+ */
+ public void setUsecookies(boolean use) {
+ useCookies = use;
+ }
+
 
    /**
     * Adds a name/value pair to post. Optional.
@@ -228,19 +255,19 @@
     * @param p A property pair to send as part of the post.
     * @exception BuildException When name and/or value are missing.
     */
- public void addConfiguredProp( Prop p ) throws BuildException {
+ public void addConfiguredProp(Prop p) throws BuildException {
       String name = p.getName();
- if ( name == null ) {
- throw new BuildException( "name is null", getLocation() );
+ if (name == null) {
+ throw new BuildException("name is null", getLocation());
       }
       String value = p.getValue();
- if ( value == null ) {
- value = getProject().getProperty( name );
+ if (value == null) {
+ value = getProject().getProperty(name);
       }
- if ( value == null ) {
- throw new BuildException( "value is null", getLocation() );
+ if (value == null) {
+ throw new BuildException("value is null", getLocation());
       }
- props.put( name, value );
+ props.put(name, value);
    }
 
 
@@ -249,7 +276,7 @@
     *
     * @param text The feature to be added to the Text attribute
     */
- public void addText( String text ) {
+ public void addText(String text) {
       textProps = text;
    }
 
@@ -260,12 +287,12 @@
     * @exception BuildException On any error.
     */
    public void execute() throws BuildException {
- if ( to == null ) {
- throw new BuildException( "'to' attribute is required", getLocation() );
+ if (to == null) {
+ throw new BuildException("'to' attribute is required", getLocation());
       }
       final String content = getContent();
       try {
- log( "Opening connection for post to " + to.toString() + "..." );
+ log("Opening connection for post to " + to.toString() + "...");
 
          // do the POST
          Thread runner =
@@ -275,128 +302,197 @@
                   try {
                      // set the url connection properties
                      connection = to.openConnection();
- connection.setDoInput( true );
- connection.setDoOutput( true );
- connection.setUseCaches( false );
+ connection.setDoInput(true);
+ connection.setDoOutput(true);
+ connection.setUseCaches(false);
                      connection.setRequestProperty(
                            "Content-Type",
- "application/x-www-f​orm-urlencoded" );
+ "application/x-www-f​orm-urlencoded");
+
+ if (useCookies && cookiePrefix != null) {
+ Hashtable map = getProject().getProperties();
+ for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
+ StringBuffer sb = new StringBuffer();
+ Object name = it.next();
+ if (name != null) {
+ String key = name.toString();
+ if (key.startsWith(cookiePrefix)) {
+ sb.append("$Version=\"1\";");
+ key = key.substring(cookie​Prefix.length());
+ Object value = map.get(name);
+ if (value == null)
+ value = "";
+ sb.append(key).appen​d("=").append(value.​toString()).append("​;");
+ sb.append("$Path=\​"").append(to.getPat​h()).append("\";");​
+ connection.addReques​tProperty("Cookie", sb.toString());
+ }
+ }
+ }
+ }
 
                      // do the post
- if ( verbose ) {
- log( "Connected, sending data..." );
+ if (verbose) {
+ log("Connected, sending data...");
                      }
- out = new DataOutputStream( connection.getOutputStream() );
- if ( verbose ) {
- log( content );
+ out = new DataOutputStream(con​nection.getOutputStr​eam());
+ if (verbose) {
+ log(content);
                      }
- out.writeBytes( content );
+ out.writeBytes(content);
                      out.flush();
- if ( verbose ) {
- log( "Data sent." );
+ if (verbose) {
+ log("Data sent.");
                      }
                   }
- catch ( Exception e ) {
- if ( failOnError ) {
- throw new BuildException( e, getLocation() );
+ catch (Exception e) {
+ if (failOnError) {
+ throw new BuildException(e, getLocation());
                      }
                   }
                   finally {
                      try {
                         out.close();
                      }
- catch ( Exception e ) {
+ catch (Exception e) {
                         // ignored
                      }
                   }
                }
             };
          runner.run();
- runner.join( maxwait );
- if ( runner.isAlive() ) {
+ runner.join(maxwait);
+ if (runner.isAlive()) {
             runner.interrupt();
- if ( failOnError ) {
- throw new BuildException( "maxwait exceeded, unable to send data", getLocation() );
+ if (failOnError) {
+ throw new BuildException("maxwait exceeded, unable to send data", getLocation());
             }
             return;
          }
 
          // read the response, if any, optionally writing it to a file
- if ( wantResponse ) {
- if ( verbose ) {
- log( "Waiting for response..." );
+ if (wantResponse) {
+ if (verbose) {
+ log("Waiting for response...");
             }
             runner =
                new Thread() {
                   public void run() {
- FileWriter fw = null;
+ PrintWriter fw = null;
+ StringWriter sw = null;
+ PrintWriter pw = null;
                      BufferedReader in = null;
                      try {
                          if (connection instanceof HttpURLConnection) {
- if(verbose) {
- log(String.valueOf((​(HttpURLConnection)c​onnection).getRespon​seCode()));
- log(((HttpURLConnect​ion)connection).getR​esponseMessage());
+ if (cookiePrefix != null) {
+ Map map = ((HttpURLConnection) connection).getHeaderFields();
+ for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
+ String name = (String) it.next();
+ if (name != null && name.equals("Set-Cookie")) {
+ List cookies = (List)map.get(name);
+ for (Iterator c = cookies.iterator(); c.hasNext(); ) {
+ String cookie = (String)c.next();
+ String key = cookie.substring(0, cookie.indexOf("="));
+ String value = cookie.substring(coo​kie.indexOf("=") + 1, cookie.lastIndexOf(";"));
+ getProject().setProp​erty(cookiePrefix + key, value);
+ }
+ }
+ }
+ }
+ if (verbose) {
+ log(String.valueOf((​(HttpURLConnection) connection).getRespo​nseCode()));
+ log(((HttpURLConnection) connection).getRespo​nseMessage());
+ StringBuffer sb = new StringBuffer();
+ Map map = ((HttpURLConnection) connection).getHeaderFields();
+ for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
+ String name = (String) it.next();
+ sb.append(name).append("=");
+ List values = (List) map.get(name);
+ if (values != null) {
+ if (values.size() == 1)
+ sb.append(values.get(0));
+ else if (values.size() > 1) {
+ sb.append("[");
+ for (Iterator v = values.iterator(); v.hasNext(); ) {
+ sb.append(v.next()).​append(",");
+ }
+ sb.append("]");
+ }
+ }
+ sb.append("\n");
+ log(sb.toString());
+ }
                              }
                          }
                         in = new BufferedReader(
- new InputStreamReader( connection.getInputStream() ) );
- if ( log != null ) {
- fw = new FileWriter( log, append );
+ new InputStreamReader(co​nnection.getInputStr​eam()));
+ if (log != null) {
+ fw = new PrintWriter(new FileWriter(log, append));
+ }
+ if (property != null) {
+ sw = new StringWriter();
+ pw = new PrintWriter(sw);
                         }
                         String line;
- while ( null != ( ( line = in.readLine() ) ) ) {
- if ( currentRunner != this ) {
+ while (null != ((line = in.readLine()))) {
+ if (currentRunner != this) {
                               break;
                            }
                            //line = URLDecoder.decode( line, "UTF-8" );
- if ( verbose ) {
- log( line );
+ if (verbose) {
+ log(line);
                            }
- if ( fw != null ) {
- fw.write( line );
+ if (fw != null) {
+ fw.println(line);
                            }
+ if (pw != null) {
+ pw.println(line);
                         }
                      }
- catch ( Exception e ) {
- if ( failOnError ) {
- throw new BuildException( e, getLocation() );
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ if (failOnError) {
+ throw new BuildException(e, getLocation());
                         }
                      }
                      finally {
                         try {
                            in.close();
                         }
- catch ( Exception e ) {
+ catch (Exception e) {
                            // ignored
                         }
                         try {
- if ( fw != null ) {
+ if (fw != null) {
                               fw.flush();
                               fw.close();
                            }
                         }
- catch ( Exception e ) {
+ catch (Exception e) {
                            // ignored
                         }
                      }
+ if (property != null && sw != null) {
+ getProject().setProp​erty(property, sw.toString());
+ }
                   }
                };
             currentRunner = runner;
             runner.run();
- runner.join( maxwait );
- if ( runner.isAlive() ) {
+ runner.join(maxwait);
+ if (runner.isAlive()) {
                currentRunner = null;
                runner.interrupt();
- if ( failOnError ) {
- throw new BuildException( "maxwait exceeded, unable to receive data", getLocation() );
+ if (failOnError) {
+ throw new BuildException("maxwait exceeded, unable to receive data", getLocation());
                }
             }
          }
- log( "Post complete." );
+ log("Post complete.");
       }
- catch ( Exception e ) {
- if ( failOnError ) {
- throw new BuildException( e );
+ catch (Exception e) {
+ if (failOnError) {
+ throw new BuildException(e);
          }
       }
    }
@@ -408,29 +504,29 @@
     * @return the message to send to the server, UTF-8 encoded.
     */
    private String getContent() {
- if ( propsFile != null ) {
- loadFile( propsFile );
+ if (propsFile != null) {
+ loadFile(propsFile);
       }
 
- if ( textProps != null ) {
- loadTextProps( textProps );
+ if (textProps != null) {
+ loadTextProps(textProps);
       }
 
       StringBuffer content = new StringBuffer();
       try {
- Enumeration en = props.keys();
- while ( en.hasMoreElements() ) {
- String name = (String)en.nextElement();
- String value = (String)props.get( name );
- content.append( URLEncoder.encode( name, encoding ) );
- content.append( "=" );
- content.append( URLEncoder.encode( value, encoding ) );
- if ( en.hasMoreElements() ) {
- content.append( "&" );
+ Enumeration enum = props.keys();
+ while (enum.hasMoreElements()) {
+ String name = (String) enum.nextElement();
+ String value = (String) props.get(name);
+ content.append(URLEn​coder.encode(name, encoding));
+ content.append("=");
+ content.append(URLEn​coder.encode(value, encoding));
+ if (enum.hasMoreElements()) {
+ content.append("&");
             }
          }
       }
- catch ( Exception e ) {
+ catch (Exception e) {
          // ignored
       }
       return content.toString();
@@ -443,29 +539,65 @@
     * @param file file to load
     * @exception BuildException Description of the Exception
     */
- private void loadFile( File file ) throws BuildException {
+ private void loadFile(File file) throws BuildException {
       Properties fileprops = new Properties();
       try {
- if ( file.exists() ) {
- FileInputStream fis = new FileInputStream( file );
+ if (file.exists()) {
+ FileInputStream fis = new FileInputStream(file);
             try {
- fileprops.load( fis );
+ fileprops.load(fis);
             }
             finally {
- if ( fis != null ) {
+ if (fis != null) {
                   fis.close();
                }
             }
- addProperties( fileprops );
+ addProperties(fileprops);
          }
          else {
- log( "Unable to find property file: " + file.getAbsolutePath(),
- Project.MSG_VERBOSE );
+ log("Unable to find property file: " + file.getAbsolutePath(),
+ Project.MSG_VERBOSE);
          }
+ log( "Post complete." );
       }
- catch ( IOException ex ) {
+ catch ( Exception e ) {
          if ( failOnError ) {
- throw new BuildException( ex, getLocation() );
+ throw new BuildException( e );
+ }
+ }
+ }
+
+
+ /**
+ * Builds and formats the message to send to the server.
+ *
+ * @return the message to send to the server, UTF-8 encoded.
+ */
+ private String getContent() {
+ if ( propsFile != null ) {
+ loadFile( propsFile );
+ }
+
+ if ( textProps != null ) {
+ loadTextProps( textProps );
+ }
+
+ StringBuffer content = new StringBuffer();
+ try {
+ Enumeration en = props.keys();
+ while ( en.hasMoreElements() ) {
+ String name = (String)en.nextElement();
+ String value = (String)props.get( name );
+ content.append( URLEncoder.encode( name, encoding ) );
+ content.append( "=" );
+ content.append( URLEncoder.encode( value, encoding ) );
+ if ( en.hasMoreElements() ) {
+ content.append( "&" );
+ }
+ }
+ catch (IOException ex) {
+ if (failOnError) {
+ throw new BuildException(ex, getLocation());
          }
       }
    }
@@ -476,22 +608,22 @@
     *
     * @param tp
     */
- private void loadTextProps( String tp ) {
+ private void loadTextProps(String tp) {
       Properties p = new Properties();
       Project project = getProject();
- StringTokenizer st = new StringTokenizer( tp, "$" );
- while ( st.hasMoreTokens() ) {
+ StringTokenizer st = new StringTokenizer(tp, "$");
+ while (st.hasMoreTokens()) {
          String token = st.nextToken();
- int start = token.indexOf( "{" );
- int end = token.indexOf( "}" );
- if ( start > -1 && end > -1 && end > start ) {
- String name = token.substring( start + 1, end - start );
- String value = project.getProperty( name );
- if ( value != null )
- p.setProperty( name, value );
+ int start = token.indexOf("{");
+ int end = token.indexOf("}");
+ if (start > -1 && end > -1 && end > start) {
+ String name = token.substring(start + 1, end - start);
+ String value = project.getProperty(name);
+ if (value != null)
+ p.setProperty(name, value);
          }
       }
- addProperties( p );
+ addProperties(p);
    }
 
 
@@ -501,55 +633,56 @@
     *
     * @param fileprops The feature to be added to the Properties attribute
     */
- private void addProperties( Properties fileprops ) {
- resolveAllProperties( fileprops );
+ private void addProperties(Properties fileprops) {
+ resolveAllProperties​(fileprops);
       Enumeration e = fileprops.keys();
- while ( e.hasMoreElements() ) {
- String name = (String)e.nextElement();
- String value = fileprops.getProperty( name );
- props.put( name, value );
+ while (e.hasMoreElements()) {
+ String name = (String) e.nextElement();
+ String value = fileprops.getProperty(name);
+ props.put(name, value);
       }
    }
 
 
    /**
- * Borrowed from Property -- resolve properties inside a properties hashtable
+ * Borrowed from Property -- resolve properties inside a properties
+ * hashtable
     *
     * @param fileprops Description of the Parameter
     * @exception BuildException Description of the Exception
     */
- private void resolveAllProperties( Properties fileprops ) throws BuildException {
- for ( Enumeration e = fileprops.keys(); e.hasMoreElements(); ) {
- String name = (String)e.nextElement();
- String value = fileprops.getProperty( name );
+ private void resolveAllProperties(Properties fileprops) throws BuildException {
+ for (Enumeration e = fileprops.keys(); e.hasMoreElements(); ) {
+ String name = (String) e.nextElement();
+ String value = fileprops.getProperty(name);
 
          boolean resolved = false;
- while ( !resolved ) {
+ while (!resolved) {
             Vector fragments = new Vector();
             Vector propertyRefs = new Vector();
             /// this is the Ant 1.5 way of doing it. The Ant 1.6 PropertyHelper
             /// should be used -- eventually.
- ProjectHelper.parseP​ropertyString( value, fragments,
- propertyRefs );
+ ProjectHelper.parseP​ropertyString(value,​ fragments,
+ propertyRefs);
 
             resolved = true;
- if ( propertyRefs.size() != 0 ) {
+ if (propertyRefs.size() != 0) {
                StringBuffer sb = new StringBuffer();
                Enumeration i = fragments.elements();
                Enumeration j = propertyRefs.elements();
- while ( i.hasMoreElements() ) {
- String fragment = (String)i.nextElement();
- if ( fragment == null ) {
- String propertyName = (String)j.nextElement();
- if ( propertyName.equals( name ) ) {
- throw new BuildException( "Property " + name
+ while (i.hasMoreElements()) {
+ String fragment = (String) i.nextElement();
+ if (fragment == null) {
+ String propertyName = (String) j.nextElement();
+ if (propertyName.equals(name)) {
+ throw new BuildException("Property " + name
                                + " was circularly "
- + "defined." );
+ + "defined.");
                      }
- fragment = getProject().getProperty( propertyName );
- if ( fragment == null ) {
- if ( fileprops.containsKey( propertyName ) ) {
- fragment = fileprops.getProperty( propertyName );
+ fragment = getProject().getProp​erty(propertyName);
+ if (fragment == null) {
+ if (fileprops.containsK​ey(propertyName)) {
+ fragment = fileprops.getPropert​y(propertyName);
                            resolved = false;
                         }
                         else {
@@ -557,12 +690,74 @@
                         }
                      }
                   }
- sb.append( fragment );
+ sb.append(fragment);
                }
                value = sb.toString();
- fileprops.put( name, value );
+ fileprops.put(name, value);
+ }
+ }
+ }
+ }
+
+ public class Cookie {
+ private String name;
+ private String value;
+ private String domain;
+ private String path;
+
+ public Cookie(String raw) {
+ String[] args = raw.split("[;]");
+ for (int i = 0; i < args.length; i++) {
+ String part = args[i];
+ String[] parts = part.split("[=]");
+ parts[0] = parts[0].trim();
+ if (parts[0].equals("$Path") || parts[0].equals("Path"))
+ path = parts[1];
+ else if (parts[0].equals("$Version") || parts[0].equals("Version"))
+ path = parts[1];
+ else {
+ name = parts[0];
+ value = parts[1];
+ }
+ }
             }
+
+ public Cookie(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setDomain(String domain) {
+ this.domain = domain;
          }
+
+ public String getDomain() {
+ return domain;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("$Version=\"1\";");
+ sb.append(name).appe​nd("=").append(value​).append(";");
+ if (path != null)
+ sb.append("$Path=\​"").append(path).app​end("\";");
+ return sb.toString();
       }
    }
 }




--------------------​--------------------​--------------------​---------
To unsubscribe, e-mail: cvs-unsubscribe@ante​lope.tigris.org
For additional commands, e-mail: cvs-help at antelope dot tigris dot org

« Previous message in topic | 1 of 1 | Next message in topic »

Messages

Show all messages in topic

CVS update: /antelope/src/ise/antelope/tasks/ danson Dale Anson 2004-10-12 18:42:50 PDT
Messages per page: