Project

General

Profile

« Previous | Next » 

Revision 1822

Added by Matt Jones about 21 years ago

Modified metacat to now provide the session identifier in the response
xml message when a login is called. This has not been fully tested.
I removed the HttpMessage class from metacat in favor of using the version
of that class that is found in the utilities module. This may cause some
unforeseen problems. We'll see.

View differences:

src/edu/ucsb/nceas/metacat/HttpMessage.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: Used for Java applet/application communication
4
 *             with servlet. Based on code given in the book
5
 *             "Java Servlet Programming" by Hunter & crawford
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Dan Higgins modified for metacat by Chad Berkley
9
 *    Release: @release@
10
 *
11
 *   '$Author$'
12
 *     '$Date$'
13
 * '$Revision$'
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 2 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 */
29

  
30
package edu.ucsb.nceas.metacat;
31

  
32
import java.io.*;
33
import java.net.*;
34
import java.util.*;
35

  
36
/**
37
 * Send a message to an HTTP server using either a GET or POST operation
38
 */
39
public class HttpMessage {
40
    public String contype;
41
    URL servlet = null;
42
    String argString = null;
43
    static String cookie = null;
44
    public HttpMessage(URL servlet) {
45
        this.servlet = servlet;
46
    }
47
    
48
    /**
49
     * return the cookie that this message object contains
50
     */
51
    public static String getCookie()
52
    {
53
      return cookie;
54
    }
55
    
56
    /**
57
     * Performs a GET request to the previously given servlet
58
     * with no query string
59
    */
60
    public InputStream sendGetMessage() throws IOException {
61
        return sendGetMessage(null);
62
    }
63
    
64
    /**
65
     * Performs a GET request to the previously given servlet
66
     *Builds a query string from the supplied Properties list.
67
     */
68
    public InputStream sendGetMessage(Properties args) throws IOException {
69
        argString = ""; //default
70
        
71
        if (args != null) {
72
            argString = "?" + toEncodedString(args);
73
        }
74
        URL url = new URL(servlet.toExternalForm() + argString);
75
        
76
        // turn off caching
77
        URLConnection con = url.openConnection();
78
        con.setUseCaches(false);
79
        contype = con.getContentType();
80
        
81
        return con.getInputStream();
82
    }
83
    
84
    /**
85
     * Performs a POST request to the previously given servlet
86
     * with no query string
87
     */
88
    public InputStream sendPostMessage() throws IOException {
89
        return sendPostMessage(null);
90
    }
91
    
92
    /**
93
     * Builds post data from the supplied properties list
94
     */
95
    public InputStream sendPostMessage(Properties args) throws IOException {
96
        argString = ""; //default
97
        if (args != null) {
98
            argString = toEncodedString(args); 
99
        }
100
        URLConnection con = servlet.openConnection();
101
        if (cookie!=null) {
102
            int k = cookie.indexOf(";");
103
            if (k>0) {
104
                cookie = cookie.substring(0, k);
105
            }
106
            //System.out.println("Cookie = " + cookie);
107
            con.setRequestProperty("Cookie", cookie); 
108
            con.setRequestProperty("User-Agent", "MORPHO");  // add 10/26/00 by DFH so Metacat can determine where request come from
109
        }
110
        //prepare for both input and output
111
        con.setDoInput(true);
112
        con.setDoOutput(true);
113
        //turn off caching
114
        con.setUseCaches(false);
115
        
116
        //work around a Netscape bug
117
        //con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
118
        //Write the arguments as post data
119
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
120
        out.writeBytes(argString);
121
        out.flush();
122
        contype = con.getContentType();
123
        String temp = con.getHeaderField("Set-Cookie");
124
        if (temp!=null) {
125
            cookie = temp;
126
        }
127
        //System.out.println(cookie);
128
        out.close();
129
        
130
        return con.getInputStream();
131
    }
132

  
133
    /**
134
     * Returns the urls argument strings
135
     */
136
    public String getArgString() {
137
        String argString1 = argString;
138
        if (!argString1.startsWith("?")) {
139
            argString1 = "?"+argString1;}
140
        return argString1;
141
    }
142
    
143
    /**
144
     * Converts a Properties list to a URL-encoded query string
145
     */
146
    private String toEncodedString(Properties args) {
147
        StringBuffer buf = new StringBuffer();
148
        Enumeration names = args.propertyNames();
149
        while (names.hasMoreElements()) {
150
            String name = (String)names.nextElement();
151
            String value = args.getProperty(name);
152
            buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
153
            if (names.hasMoreElements()) buf.append("&");
154
        }
155
        return buf.toString();
156
    }
157
  
158
  /**
159
   * return the cookie that this message object contains
160
   */
161
  public static void setCookie(String newCookie)
162
  {
163
    cookie = newCookie;
164
  }
165
}
166 0

  
test/edu/ucsb/nceas/metacattest/MetaCatServletTest.java
28 28
package edu.ucsb.nceas.metacattest;
29 29

  
30 30
import edu.ucsb.nceas.metacat.*;
31
import edu.ucsb.nceas.utilities.HttpMessage;
31 32
//import edu.ucsb.nceas.morpho.framework.*;
32 33
import junit.framework.Test;
33 34
import junit.framework.TestCase;
test/edu/ucsb/nceas/metacattest/client/MetacatClientTest.java
26 26
package edu.ucsb.nceas.metacattest.client;
27 27

  
28 28
import edu.ucsb.nceas.metacat.client.*;
29
import edu.ucsb.nceas.utilities.HttpMessage;
29 30
import edu.ucsb.nceas.utilities.IOUtil;
30 31

  
31 32
import java.io.FileReader;
......
52 53
public class MetacatClientTest extends TestCase
53 54
{
54 55
    private String metacatUrl = 
55
         "http://dev.nceas.ucsb.edu:8091/tao/servlet/metacat";
56
         "http://dev.nceas.ucsb.edu/tao/servlet/metacat";
56 57
        //"http://knb.ecoinformatics.org/knb/servlet/metacat";
57 58
    private String wrongMetacatUrl=
58 59
                    "http://somepalce.somewhere.com/some/servlet/metacat";
......
95 96
        try {
96 97
            m = MetacatFactory.createMetacatConnection(metacatUrl);
97 98
        } catch (MetacatInaccessibleException mie) {
99
            System.err.println("Metacat is: " + metacatUrl);
98 100
            fail("Metacat connection failed." + mie.getMessage());
99 101
        }
100 102
    }
......
122 124
        suite.addTest(new MetacatClientTest("query"));
123 125
        suite.addTest(new MetacatClientTest("invalidUpdate"));
124 126
        suite.addTest(new MetacatClientTest("update"));
125
         suite.addTest(new MetacatClientTest("invalidDelete"));
127
        suite.addTest(new MetacatClientTest("invalidDelete"));
126 128
        suite.addTest(new MetacatClientTest("delete"));
127 129
        suite.addTest(new MetacatClientTest("inaccessiblemetacat"));
128 130
        return suite;
......
144 146
    {
145 147
        // Try a valid login
146 148
        try {
147
            m.login(username, password);
149
            String response = m.login(username, password);
150
            System.err.println("Login response: " + response);
151
            assertTrue(response != null);
152
            assertTrue(response.indexOf("<login>") != -1);
153
            String sessionId = m.getSessionId();
154
            System.err.println("Session ID: " + m.getSessionId());
155
            //assertTrue(sessionId != null);
156
            //assertTrue(response.indexOf(m.getSessionId()) != -1);
148 157
        } catch (MetacatAuthException mae) {
149 158
            fail("Authorization failed:\n" + mae.getMessage());
150 159
        } catch (MetacatInaccessibleException mie) {
......
180 189
            m.logout();
181 190
            String response = m.insert(identifier, 
182 191
                    new StringReader(testdocument), null);
183
            System.out.println("response in logout: "+response);
192
            System.err.println("Response in logout: "+response);
184 193
            assertTrue(response.indexOf("<success>") == -1);
185 194
        } catch (MetacatAuthException mae) {
186 195
            fail("Authorization failed:\n" + mae.getMessage());
src/edu/ucsb/nceas/metacat/AuthSession.java
73 73
          groups = new String[0];
74 74
        }
75 75
        this.session = getSession(request, username, password, groups);
76
        String sessionId = session.getId();
76 77
        message = "Authentication successful for user: " + username;
77
        this.statusMessage = formatOutput("login", message);
78
        this.statusMessage = formatOutput("login", message, sessionId);
78 79
        return true;
79 80
      } else {  
80 81
        message = "Authentication failed for user: " + username;
......
145 146
   * @param tag the root element tag for the message (error or success)
146 147
   * @param message the message content of the root element
147 148
   */
148
  private String formatOutput(String tag, String message) {
149
    
149
  private String formatOutput(String tag, String message) 
150
  {
151
      return formatOutput(tag, message, null);
152
  }
153

  
154
  /* 
155
   * format the output in xml for processing from client applications
156
   *
157
   * @param tag the root element tag for the message (error or success)
158
   * @param message the message content of the root element
159
   * @param sessionId the session identifier for a successful login
160
   */
161
  private String formatOutput(String tag, String message, String sessionId) 
162
  {
150 163
    StringBuffer out = new StringBuffer();
151 164
      
152 165
    out.append("<?xml version=\"1.0\"?>\n");
153 166
    out.append("<" + tag + ">");
154 167
    out.append("\n  <message>" + message + "</message>\n");
168
    if (sessionId != null) {
169
        out.append("\n  <sessionId>" + message + "</sessionId>\n");
170
    }
155 171
    out.append("</" + tag + ">");
156 172
    
157 173
    return out.toString();
src/edu/ucsb/nceas/metacat/RemoteDocument.java
27 27

  
28 28
package edu.ucsb.nceas.metacat;
29 29

  
30
import edu.ucsb.nceas.utilities.HttpMessage;
30 31
import javax.servlet.ServletOutputStream;
31 32
import java.io.*;
32 33
import java.net.*;
src/edu/ucsb/nceas/metacat/client/MetacatClient.java
48 48
    /** The URL string for the metacat server */
49 49
    private String metacatUrl;
50 50

  
51
    /** The session identifier for the session */
52
    private String sessionId;
53

  
51 54
    /**
52 55
     * Constructor to create a new instance. Protected because instances
53 56
     * should only be created by the factory MetacatFactory.
54 57
     */
55 58
    protected MetacatClient()
56 59
    {
60
        this.metacatUrl = null;
61
        this.sessionId = null;
57 62
    }
58 63

  
59 64
    /**
......
64 69
     *
65 70
     *  @param username   the username of the user, like an LDAP DN
66 71
     *  @param password   the password for that user for authentication
72
     *  @return the response string from metacat in XML format
67 73
     *  @throws MetacatAuthException when the username/password could
68 74
     *                    not be authenticated
69 75
     */
70
    public void login(String username, String password) 
76
    public String login(String username, String password) 
71 77
           throws MetacatAuthException, MetacatInaccessibleException
72 78
    {
73 79
        Properties prop = new Properties();
......
86 92
        if (response.indexOf("<login>") == -1) {
87 93
            HttpMessage.setCookie(null);
88 94
            throw new MetacatAuthException(response);
95
        } else {
96
            int start = response.indexOf("<sessionId>");
97
            int end = response.indexOf("</sessionId>");
98
            if ((start != -1) && (end != -1)) {
99
                sessionId = response.substring(start,end);
100
            }
89 101
        }
102
        return response;
90 103
    }
91 104

  
92 105
    /**
93
     *  Method used to log out a metacat server. When Metacat server will end
94
     *  the session when this call is invoken.
106
     *  Method used to log out a metacat server. The Metacat server will end
107
     *  the session when this call is invoked.
95 108
     *
109
     *  @return the response string from metacat in XML format
96 110
     *  @throws MetacatInaccessibleException when the metacat server can not be
97 111
     *                                    reached or does not respond
98 112
     */
99
    public void logout() throws MetacatInaccessibleException, MetacatException
113
    public String logout() throws MetacatInaccessibleException, MetacatException
100 114
    {
101 115
        Properties prop = new Properties();
102 116
        prop.put("action", "logout");
......
112 126
        if (response.indexOf("<logout>") == -1) {
113 127
            throw new MetacatException(response);
114 128
        }
129
        this.sessionId = null;
130
        return response;
115 131
    }
116 132
    
117
    
118 133
    /**
119 134
     * Read an XML document from the metacat server session, accessed by docid,
120 135
     * and returned as a Reader.
......
372 387
        this.metacatUrl = metacatUrl;
373 388
    }
374 389

  
390
    /**
391
     * Get the session identifier for this session.  This is only valid if
392
     * the login methods has been called successfully for this Metacat object
393
     * beforehand.
394
     *
395
     * @returns the sessionId as a String, or null if the session is invalid
396
     */
397
    public String getSessionId()
398
    {
399
        return this.sessionId;
400
    }
401

  
375 402
    /************************************************************************
376 403
     * PRIVATE METHODS
377 404
     ************************************************************************/
src/edu/ucsb/nceas/metacat/client/Metacat.java
42 42
     *
43 43
     *  @param username   the username of the user, like an LDAP DN
44 44
     *  @param password   the password for that user for authentication
45
     *  @return the response string from metacat in XML format
45 46
     *  @throws MetacatAuthException when the username/password could
46 47
     *                    not be authenticated
47 48
     */
48
    public void login(String username, String password) 
49
    public String login(String username, String password) 
49 50
           throws MetacatAuthException, MetacatInaccessibleException;
50 51
    
51 52
    /**
52
     *  Method used to log out a metacat server. When Metacat server will end
53
     *  the session when this call is invoken.
53
     *  Method used to log out a metacat server. The Metacat server will end
54
     *  the session when this call is invoked.
54 55
     *
56
     *  @return the response string from metacat in XML format
55 57
     *  @throws MetacatInaccessibleException when the metacat server can not be
56 58
     *                                    reached or does not respond
57 59
     */
58
    public void logout() throws MetacatInaccessibleException, MetacatException;
60
    public String logout() throws MetacatInaccessibleException, 
61
        MetacatException;
59 62

  
60 63
    /**
61 64
     * Read an XML document from the metacat server session, accessed by docid,
......
142 145
     * @param metacatUrl the URL for the metacat server
143 146
     */
144 147
    public void setMetacatUrl(String metacatUrl);
148

  
149
    /**
150
     * Get the session identifier for this session.
151
     *
152
     * @returns the sessionId as a String, or null if the session is invalid
153
     */
154
    public String getSessionId();
145 155
}
build.xml
87 87
      <property name="mcanotherpassword" value=""/>
88 88

  
89 89
      <!-- Tomcat version, if you use tomcat 3, please fill it "tomcat3". If you using tomcat4, please fill it "tomcat4"-->
90
      <property name="tomcatversion" value="tomcat4"/>
90
      <property name="tomcatversion" value="tomcat3"/>
91 91

  
92
      <property name="server" value="pine.nceas.ucsb.edu:8443"/>
93
      <property name="systemidserver" value="http://pine.nceas.ucsb.edu:8080" />
92
      <property name="server" value="dev.nceas.ucsb.edu"/>
93
      <property name="systemidserver" value="http://dev.nceas.ucsb.edu" />
94 94
      <property name="datafilepath" value="/usr/local/devtools/jakarta-tomcat/data/tao/data" />
95 95
      <property name="inlinedatafilepath" value="/usr/local/devtools/jakarta-tomcat/data/tao/inlinedata" />
96 96
      <property name="debuglevel" value="55" />
......
108 108
      <!-- Make sure these paths match the location of the jar files
109 109
           on your system, the defaults should usually work -->
110 110
      <property name="jsdk"
111
                value="${tomcat}/common/lib/servlet.jar" />
111
                value="${tomcat}/lib/common/servlet.jar" />
112 112
      <property name="xmlp"
113 113
                value="lib/xercesImpl.jar" />
114 114
      <property name="srb"
......
241 241
      </copy>
242 242
   </target>
243 243

  
244
   <target name="compile" depends="prepare">
244
   <target name="compile" depends="prepare,utilities">
245 245
       <javac srcdir="${build.src}"
246 246
              destdir="${build.dest}"
247 247
              classpath="${cpath}"
......
445 445
     
446 446
   </target>
447 447
   
448
   <target name="testprep" depends="install">
448
   <target name="testprep" depends="jar,clientjar">
449 449
      <mkdir dir="${build.tests}"/>
450 450
      <copy todir="${build.tests}" filtering="yes">
451 451
        <fileset dir="${testdir}">
452 452
          <include name="edu/**"/>
453 453
        </fileset>
454 454
      </copy>
455
   </target>
456

  
457
   <target name="test" depends="testprep">
458 455
      <!-- copy and compile the tests into a jar file -->
459 456
      <javac srcdir="${build.tests}"
460 457
             destdir="${build.tests}"
461
             classpath="${cpath}:${build.dir}/${name}.jar"
458
             classpath="${cpath}:${build.dir}/${name}.jar:${build.dir}/${name}-client.jar"
462 459
             debug="on"
463 460
       includes="**/*.java" />
464 461

  
465 462
      <jar jarfile="${build.dir}/${name}-junittests.jar"
466 463
        basedir="${build.tests}"
467 464
                includes="**/*.class" />
465
   </target>
468 466

  
467
   <target name="test" depends="testprep">
468

  
469 469
      <!-- use the ant "junit" task to run JUnit tests. -->
470 470
      <junit printsummary="yes" haltonfailure="no" fork="yes"
471 471
             haltonerror="no">
......
485 485
   </target>
486 486

  
487 487
    <target name="runonetest" depends="testprep">
488
      <!-- copy and compile the tests into a jar file -->
489
      <!--<property name="testtorun" value="SubTreeTest"/> -->
490 488
      <echo>testtorun: ${testtorun}</echo>
491
      <javac srcdir="${build.tests}"
492
             destdir="${build.tests}"
493
             classpath="${cpath}:${build.dir}/${name}.jar"
494
             debug="on"
495
       includes="**/*.java" />
496 489

  
497
      <jar jarfile="${build.dir}/${name}-junittests.jar"
498
        basedir="${build.tests}"
499
                includes="**/*.class" />
500

  
501 490
      <!-- use the ant "junit" task to run JUnit tests. -->
502 491
      <junit printsummary="yes" haltonfailure="no" fork="yes"
503 492
             haltonerror="no">
......
566 555

  
567 556
   <target name="clean" depends="init">
568 557
       <delete dir="${build.dir}" />
558
       <delete file="lib/httpclient.jar" />
559
       <delete file="lib/utilities.jar" />
569 560
   </target>
570 561

  
571 562
   <target name="jdoc" depends="prepare">

Also available in: Unified diff