Project

General

Profile

1
? lib/gsi
2
? lib/cog-url-ncsa.jar
3
? lib/cog-jglobus-ncsa.jar
4
? src/gsimap.properties
5
? src/edu/ucsb/nceas/metacat/AuthGsi.java
6
? src/edu/ucsb/nceas/metacat/AuthInfo.java
7
? src/edu/ucsb/nceas/metacat/GsiMapfile.java
8
? src/edu/ucsb/nceas/metacat/client/gsi
9
Index: build.properties
10
===================================================================
11
RCS file: /cvs/metacat/build.properties,v
12
retrieving revision 1.16
13
diff -r1.16 build.properties
14
85a86,100
15
> 
16
> # Authentication options -- written into metacat.properties
17
> #   can be "Gsi" or "Ldap"
18
> auth-method=Gsi
19
> #   can really only be "Ldap" for now
20
> auth-delegate=Ldap
21
> #   can be "true" or "false"
22
> auth-delegation-allowed=true
23
> #   can be "username+password" or "gss"
24
> auth-precedence=username+password
25
> 
26
> # Should logins from localhost with no password be trusted?  Useful
27
> # for the GT4 web service wrapper around metacat when it isn't using
28
> # GSI delegation.
29
> auth-trust-localhost=true
30
Index: build.xml
31
===================================================================
32
RCS file: /cvs/metacat/build.xml,v
33
retrieving revision 1.226
34
diff -r1.226 build.xml
35
273a274,278
36
>       <filter token="auth-method" value="${auth-method}"/>
37
>       <filter token="auth-delegate" value="${auth-delegate}"/>
38
>       <filter token="auth-delegation-allowed" value="${auth-delegation-allowed}"/>
39
>       <filter token="auth-precedence" value="${auth-precedence}"/>
40
>       <filter token="auth-trust-localhost" value="${auth-trust-localhost}"/>
41
Index: docs/user/metacatinstall.html
42
===================================================================
43
RCS file: /cvs/metacat/docs/user/metacatinstall.html,v
44
retrieving revision 1.20
45
diff -r1.20 metacatinstall.html
46
20a21,28
47
>   <style type="text/css" media="screen">
48
>   <!--
49
>     .tooltip { border-bottom:1px solid #00f }
50
>     .tooltip:hover { background: #fc9 }
51
>     .sample { border:1px solid black; padding:0.3em; }
52
>     .existing { color:#666 }
53
>   -->
54
>   </style>
55
618a627,917
56
> 
57
> <table class="tabledefault" width="100%">
58
> <td class="tablehead" colspan="2">
59
>   <p><a name="gsi"></a>GSI (Grid Security Infrastructure) Authentication</a></p>
60
> </td>
61
> <tr>
62
> <td>
63
>   <p class="header">Overview</p>
64
> 
65
>   <p>
66
>     As an alternative to username/password, Metacat can use Grid
67
>     Security Infrastructure (GSI) credentials for authentication, if
68
>     you are programming to the Metacat client API.  The advantages
69
>     are:
70
>   </p>
71
> 
72
>   <ul>
73
>     <li>
74
>       Use of security credentials enables sign-on with other grid
75
>       services.
76
>     </li>
77
>     <li>
78
>       Metacat's plaintext HTTP client-server connection is replaced
79
>       with encrypted HTTPS+GSI -- that is, SSL HTTP using grid
80
>       security credentials for the SSL connection.
81
>     </li>
82
>   </ul>
83
> 
84
> 
85
>   <p class="header">Grid Security Setup</p> 
86
> 
87
>   <ol>
88
>     <li>
89
>       <p>If you don't have any Grid infrastructure available already,
90
>       you can <a
91
>       href="http://grid.ncsa.uiuc.edu/myproxy/fromscratch.html">follow
92
>       these instructions</a> to get started from scratch.</p>
93
>     </li>
94
> 
95
>     <li>
96
>       <p>Establish host credentials for your Metacat server.  The
97
>       instructions above will suffice for experimentation, or you can
98
>       get host credentials from your own Certificate Authority.  You
99
>       can always replace them in the future.</p>
100
>     </li>
101
>   </ol>
102
> 
103
>   <p class="header">Tomcat Configuration</p> 
104
> 
105
>   <ol>
106
>     <li>
107
>       <a name="tomcat_jars"></a>
108
>       <p>Add JARs to Tomcat's <code>$CATALINA_HOME/common/lib</code>
109
>       directory.  You can find them in the Metacat distribution in
110
>       <code>metacat/lib/gsi</code>:</p>
111
> 
112
>       <blockquote>
113
>         <code>cog-jglobus-ncsa.jar, commons-pool-1.2.jar,
114
>         cryptix32.jar, cryptix-asn1.jar, cryptix.jar,
115
>         jce-jdk13-125.jar, jgss.jar, log4j-1.2.8.jar, puretls.jar,
116
>         xml-apis.jar</code>
117
>       </blockquote>
118
> 
119
>       <p>Note that <code>cog-jglobus-ncsa.jar</code> is a modified
120
>       version of <code>cog-jglobus.jar</code> which comes with the <a
121
>       href="http://www.globus.org/toolkit/">Globus Toolkit</a>.  It
122
>       includes a patch to enable GSI+HTTPS POST actions (only GET was
123
>       supported previously).  The patch has been committed to the CoG
124
>       source and will be included in a future a version of the Globus
125
>       Toolkit, but until then you will need this custom JAR.</p>
126
> 
127
>     </li>
128
> 
129
>     <li>
130
>       <p>Modify Tomcat's <code>server.xml</code> to listen for
131
>       HTTPS+GSI.  Note that you can use any available port for this
132
>       connector; this example uses 8443.</p>
133
> 
134
>       <p>Host credentials: The HTTPS connection will require host
135
>       credentials for the Metacat server; the example below assumes
136
>       that the host credentials are in
137
>       <code>/etc/grid-security</code>, which is the default location
138
>       for a <a href="http://www.globus.org/toolkit/">Globus
139
>       toolkit</a> installation.</p>
140
> 
141
>       <p>CA Cert Dir: Any Certificate Authorities (CAs) that you
142
>       depend on -- for example, the one that issued your host
143
>       credential -- should have their public keys and signing policies
144
>       stored in a location that is accessible to Tomcat
145
>       (<code>cacertdir</code>, below).  The filenames will be
146
>       something like <code>4a6cd8b1.0</code> and
147
>       <code>4a6cd8b1.signing_policy</code>.</p>
148
> 
149
>       <ul>
150
> 
151
>         <li>
152
>           <p>Add an <code>HTTPSConnector</code>, inside the
153
>           <code>&lt;Service name="Catalina"&gt;</code> section, near
154
>           the SSL HTTP/1.1 connector definition, which is commented
155
>           out by default:</p>
156
> 
157
> <pre class="sample">
158
> <span class="existing">&lt;!-- Define a SSL HTTP/1.1 Connector on port 8443 --&gt;
159
> &lt;!--
160
> &lt;Connector port="8443" maxHttpHeaderSize="8192"
161
>            maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
162
>            enableLookups="false" disableUploadTimeout="true"
163
>            acceptCount="100" scheme="https" secure="true"
164
>            clientAuth="false" sslProtocol="TLS" /&gt;
165
> --&gt;</span>
166
> 
167
> &lt;!-- Define an HTTPS+GSI (HTTPS with GSI credentials) Connector on port 8443 --&gt;
168
> &lt;Connector className="org.globus.tomcat.coyote.net.HTTPSConnector"
169
>            port="8443" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" 
170
>            autoFlush="true" disableUploadTimeout="true" scheme="https"
171
>            enableLookups="true" acceptCount="10" debug="0" 
172
>            cert="/etc/grid-security/hostcert.pem"
173
>            key="/etc/grid-security/hostkey.pem"
174
>            cacertdir="/etc/grid-security/certificates"/&gt;
175
> </pre>
176
>         </li>
177
>         <li>
178
>           <p>Add an <code>HTTPSValve</code>, inside the <code>&lt;Engine
179
>           name="Catalina" ...&gt;</code> section, near the
180
>           <code>RequestDumperValve</code> definition, which is
181
>           commented out by default:</p>
182
> 
183
> <pre class="sample">
184
> <span class="existing">&lt;!--
185
> &lt;Valve className="org.apache.catalina.valves.RequestDumperValve"/&gt;
186
> --&gt;</span>
187
> 
188
> &lt;!-- Globus valve for HTTPS+GSI --&gt;
189
> &lt;Valve className="org.globus.tomcat.coyote.valves.HTTPSValve"/&gt;
190
> </pre>
191
>         </li>
192
>       </ul>
193
>     </li>
194
> 
195
>     <li>
196
>       <p>Restart Tomcat -- it should now be listening for HTTPS+GSI
197
>       connections.  Watch for errors in its log file
198
>       (<code>$CATALINA_HOME/logs/catalina.out</code>).</p>
199
>     </li>
200
>   </ol>
201
> 
202
>   <p class="header">Metacat Client GSI Login</p> 
203
> 
204
>   <ol>
205
>     <li>
206
>       <p>You can now use GSI credentials to initiate a Metacat
207
>       session, replacing <code>Metacat.login(String username, String
208
>       password)</code> with <code>Metacat.login(GSSCredential
209
>       credential)</code>.  There are several ways to get a
210
>       <code>GSSCredential</code>; one easy method, if you have access
211
>       to a <a href="http://grid.ncsa.uiuc.edu/myproxy/">MyProxy</a>
212
>       server, is to use the <a href="http://www.cogkit.org/">CoG</a>
213
>       Java libraries to retrieve a proxy credential from MyProxy.</p>
214
> 
215
>       <p>Here is some sample Java code.  Note that it requires, in
216
>       addition to the JARs listed <a href="#tomcat_jars">above</a>,
217
>       <code>cog-url-ncsa.jar</code>, which can be found in the
218
>       <code>metacat/lib</code> directory.</p>
219
> 
220
>       <p>Note: for code comments, mouse over the <span class="tooltip"
221
>       title="like this one">marked</span> sections below.</p>
222
> 
223
> <pre class="sample">
224
> // 1. Get a GSI security credential
225
> org.globus.myproxy.MyProxy server = new MyProxy(<span class="tooltip" title="Hostname of MyProxy server">host</span>, <span class="tooltip" title="Port number of the MyProxy server -- default is 7512">7512</span>);
226
> org.ietf.jgss.<span class="tooltip" title="included in standard JRE/JDK libraries">GSSCredential</span> credential = server.get(<span class="tooltip" title="MyProxy username">username</span>, <span class="tooltip" title="MyProxy passphrase">passphrase</span>, <span class="tooltip" title="Credential lifetime in seconds">lifetime</span>);
227
> 
228
> // 2. Connect to Metacat via GSI+HTTPS
229
> String metacatUrl = "https://&lt;metacat server&gt;:8443/metacat/metacat/";
230
> edu.ucsb.nceas.metacat.client.Metacat client 
231
>     = edu.ucsb.nceas.metacat.client.MetacatFactory.createMetacatConnection(metacatUrl);
232
> String loginResult = client.login(credential);
233
> </pre>
234
> 
235
>       <p>The <code>String</code> returned by
236
>       <code>Metacat.login(GSSCredential)</code> will let you know
237
>       whether your attempt succeeded.</p>
238
>     </li>
239
> 
240
>     <li>
241
>       <p>In order to give GSI users privileges in Metacat, you must
242
>       Map GSI user IDs, or Distinguished Names (DNs), to Metacat user
243
>       IDs, which will generally be LDAP DNs.  You can do this in a map
244
>       file that starts out in
245
>       <code>metacat/src/gsimap.properties</code> and gets deployed to
246
>       Tomcat's <code>webapps/metacat/WEB-INF/</code> directory.  You can
247
>       modify it in either place, but it will be overwritten each time
248
>       you redeploy Metacat if you change it in Tomcat's installation
249
>       directory.</p>
250
>     </li>
251
>   </ol>
252
> 
253
>   <p class="header">A Client Inside of Tomcat</p> 
254
> 
255
>   <p>Detailed explanation: The sample code above will work in a simple
256
>   testing situation such as in an IDE's debugger, and it may work in a
257
>   desktop application, but it won't work inside Tomcat.  It has two
258
>   problems, both of which have to do with Java's protocol handling
259
>   facilities.  The first problem is a protocol handler collision --
260
>   Tomcat has already instantiated an HTTPS handler, and it is not the
261
>   one we need for GSI+HTTPS.  The second problem has to do with class
262
>   loading: our special HTTPS protocol handlers are not accessible to
263
>   Java's protocol handling code because they are not loaded by
264
>   Tomcat's root classloader.</p>
265
> 
266
>   <ol>
267
>     <li>
268
>       You will most likely need to install the Metacat server and the
269
>       Metacat client application in <i>separate</i> instances of
270
>       Tomcat in order for them to successfully connect.
271
>     </li>
272
> 
273
>     <li>
274
>       <p>Protocol Handler Collisions:</p>
275
> 
276
>       <p>Short answer: replace "<code>https</code>" with
277
>       "<code>httpg</code>".</p>
278
>       <blockquote><pre><code><i>https</i>://&lt;metacat server&gt;:8443/metacat/metacat/</code></pre></blockquote>
279
>       <p>becomes</p>
280
>       <blockquote><pre><i>httpg</i>://&lt;metacat server&gt;:8443/metacat/metacat/</pre></blockquote>
281
> 
282
>       <p>Long answer: The URL in the example above,
283
>       <code>https://&lt;metacat server&gt;:8443/metacat/metacat/</code>,
284
>       uses the <code>HTTPS</code> protocol.  However, actually
285
>       handling that connection requires a protocol handler that
286
>       understands GSI+HTTPS instead of plain HTTPS.  Fortunately,
287
>       <code>static</code> initialization code in
288
>       <code>MetacatGsiClient</code> specifies a non-default
289
>       <code>HTTPS</code> handler before the default handler is
290
>       instantiated by Java.</p>
291
> 
292
>       <p>Unfortunately, in Tomcat, an <code>HTTPS</code> handler has
293
>       already been instantiated by the time Metacat code runs, and we
294
>       don't have a chance to instantiate our special handler.
295
>       Besides, other applications also running in Tomcat may need to
296
>       use the default handler.</p>
297
> 
298
>       <p>Instead, we can define a new protocol.  It could be named
299
>       anything -- <code>HTTPGSI</code>, <code>METACAT_GSI</code>,
300
>       <code>GRID_HTTP</code>, etc.  Metacat defines a handler for a
301
>       protocol named <code>HTTPG</code>.  To see how it works, see the
302
>       static initialization code in
303
>       <code>edu.ucsb.nceas.metacat.client.MetacatGsiClient</code> and
304
>       the very simple class
305
>       <code>edu.ucsb.nceas.protocols.httpg.Handler</code>.</p>
306
>     </li>
307
>     <li>
308
>       <p>Tomcat Classloading: Since the Java classes that dynamically
309
>       load protocol handlers are in Tomcat's root classloader, the
310
>       protocol handlers themselves must be there also.</p>
311
> 
312
>       <ol style="list-style-type:lower-alpha">
313
>         <li>
314
>           Copy <code>metacat.jar</code>, <code>utilities.jar</code>,
315
>           and <code>cog-url-ncsa.jar</code> from Metacat's lib
316
>           directory to a place that is accessible by Tomcat, such as
317
>           <code>$CATALINA_HOME/common/lib</code>.
318
>         </li>
319
>         <li>
320
>           <p>Modify the definition of <code>CLASSPATH</code> in
321
>           Tomcat's startup script,
322
>           <code>$CATALINA_HOME/bin/catalina.sh</code> (In Windows,
323
>           <code>catalina.bat</code>, which has slightly different
324
>           syntax).</p>
325
> 
326
>           <p>Replace:</p>
327
> <pre class="sample">
328
> CLASSPATH="$CLASSPATH":"$CATALINA_HOME"/bin/bootstrap.jar:\
329
> "$CATALINA_HOME"/bin/commons-logging-api.jar
330
> </pre>
331
>           <p>With:</p>
332
> <pre class="sample">
333
> CLASSPATH="$CLASSPATH":"$CATALINA_HOME"/bin/bootstrap.jar:\
334
> "$CATALINA_HOME"/bin/commons-logging-api.jar:"$CATALINA_HOME"/common/lib/metacat.jar:\
335
> "$CATALINA_HOME"/common/lib/utilities.jar:"$CATALINA_HOME"/common/lib/cog-url-ncsa.jar
336
> </pre>
337
>         </li>
338
>       </ol>
339
> 
340
> 
341
>     </li>
342
>   </ol>
343
> </td>
344
> </tr>
345
> </table>
346
> 
347
Index: lib/metacat.properties
348
===================================================================
349
RCS file: /cvs/metacat/lib/metacat.properties,v
350
retrieving revision 1.100
351
diff -r1.100 metacat.properties
352
43,54d42
353
< moderators=@moderators@
354
< 
355
< allowedSubmitters=@allowedSubmitters@
356
< 
357
< deniedSubmitters=@deniedSubmitters@
358
< 
359
< timedreplication=@timedreplication@
360
< 
361
< firsttimedreplication=@firsttimedreplication@
362
< 
363
< timedreplicationinterval=@timedreplicationinterval@
364
< 
365
89,90d76
366
< indexed_paths=organizationName,originator/individualName/surName,originator/individualName/givenName,originator/organizationName,creator/individualName/surName,creator/individualName/givenName,creator/organizationName,dataset/title,keyword,northBoundingCoordinate,southBoundingCoordinate,westBoundingCoordinate,eastBoundingCoordinate,title,entityName,individualName/surName,abstract/para,surName,givenName,para,geographicDescription,literalLayout
367
< 
368
97c83,88
369
< authclass=edu.ucsb.nceas.metacat.AuthLdap
370
---
371
> authclass=edu.ucsb.nceas.metacat.Auth@auth-method@
372
> authDelegateClass=edu.ucsb.nceas.metacat.Auth@auth-delegate@
373
> authDelegationAllowed=@auth-delegation-allowed@
374
> authPrecedence=@auth-precedence@
375
> gsiMapClass=edu.ucsb.nceas.metacat.GsiMapfile
376
> trustLocalHost=@auth-trust-localhost@
377
99c90,91
378
< ldapurl=ldap://ldap.ecoinformatics.org:389/
379
---
380
> #ldapurl=ldap://ldap.ecoinformatics.org:389/
381
> ldapurl=ldap://ldap.lternet.edu/
382
101c93,94
383
< ldapsurl=ldap://ldap.ecoinformatics.org:389/
384
---
385
> #ldapsurl=ldap://ldap.ecoinformatics.org:389/
386
> ldapsurl=ldap://ldap.lternet.edu/
387
103c96,97
388
< ldapbase=dc=ecoinformatics,dc=org
389
---
390
> #ldapbase=dc=ecoinformatics,dc=org
391
> ldapbase=o=lter,dc=ecoinformatics,dc=org
392
Index: src/edu/ucsb/nceas/metacat/AuthInterface.java
393
===================================================================
394
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/AuthInterface.java,v
395
retrieving revision 1.7
396
diff -r1.7 AuthInterface.java
397
46,48c46,47
398
<    * @param user the name of the principal to authenticate
399
<    * @param password the password to use for authentication
400
<    * @returns boolean true if authentication successful, false otherwise
401
---
402
>    * @param info authentication information from the user
403
>    * @return true if authentication successful, false otherwise
404
50c49
405
<   public boolean authenticate(String user, String password)
406
---
407
>   public boolean authenticate(AuthInfo info)
408
56c55
409
<   public String[][] getUsers(String user, String password)
410
---
411
>   public String[][] getUsers(AuthInfo info)
412
62c61
413
<   public String[] getUsers(String user, String password, String group)
414
---
415
>   public String[] getUsers(AuthInfo info, String group)
416
68c67
417
<   public String[][] getGroups(String user, String password)
418
---
419
>   public String[][] getGroups(AuthInfo info)
420
74c73
421
<   public String[][] getGroups(String user, String password, String foruser)
422
---
423
>   public String[][] getGroups(AuthInfo info, String foruser)
424
80,81c79,80
425
<    * @param user the user for which the attribute list is requested
426
<    * @returns HashMap a map of attribute name to a Vector of values
427
---
428
>    * @param foruser the user for which the attribute list is requested
429
>    * @return a map of attribute name to a Vector of values
430
89,92c88,90
431
<    * @param user the user for which the attribute list is requested
432
<    * @param authuser the user for authenticating against the service
433
<    * @param password the password for authenticating against the service
434
<    * @returns HashMap a map of attribute name to a Vector of values
435
---
436
>    * @param info authentication information to use to access the directory
437
>    * @param foruser the user for which the attribute list is requested
438
>    * @return a map of attribute name to a Vector of values
439
94c92
440
<   public HashMap getAttributes(String user, String password, String foruser)
441
---
442
>   public HashMap getAttributes(AuthInfo info, String foruser)
443
100,101c98,99
444
<    * @param user the user which requests the information
445
<    * @param password the user's password
446
---
447
>    * @param info authentication information about the user who requests the
448
>    * information
449
103c101
450
<   public String getPrincipals(String user, String password)
451
---
452
>   public String getPrincipals(AuthInfo info)
453
Index: src/edu/ucsb/nceas/metacat/AuthLdap.java
454
===================================================================
455
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/AuthLdap.java,v
456
retrieving revision 1.55
457
diff -r1.55 AuthLdap.java
458
31a32,33
459
> import javax.naming.*;
460
> import javax.naming.directory.*;
461
33,49d34
462
< import javax.naming.AuthenticationException;
463
< import javax.naming.Context;
464
< import javax.naming.NamingEnumeration;
465
< import javax.naming.NamingException;
466
< import javax.naming.SizeLimitExceededException;
467
< import javax.naming.InitialContext;
468
< import javax.naming.directory.InvalidSearchFilterException;
469
< import javax.naming.directory.Attribute;
470
< import javax.naming.directory.Attributes;
471
< import javax.naming.directory.BasicAttribute;
472
< import javax.naming.directory.BasicAttributes;
473
< import javax.naming.directory.DirContext;
474
< import javax.naming.directory.InitialDirContext;
475
< import javax.naming.directory.SearchResult;
476
< import javax.naming.directory.SearchControls;
477
< import javax.naming.ReferralException;
478
< import javax.naming.ldap.*;
479
51,56c36
480
< import java.util.Iterator;
481
< import java.util.HashMap;
482
< import java.util.Hashtable;
483
< import java.util.Enumeration;
484
< import java.util.Set;
485
< import java.util.Vector;
486
---
487
> import java.util.*;
488
66d45
489
<   private MetaCatUtil util = new MetaCatUtil();
490
73,76c52
491
<   private Context rContext;
492
<   private String userName;
493
<   private String userPassword;
494
<   ReferralException refExc;
495
---
496
> 	ReferralException refExc;
497
94,96c70,71
498
<    * @param user the name of the principal to authenticate
499
<    * @param password the password to use for authentication
500
<    * @returns boolean true if authentication successful, false otherwise
501
---
502
>    * @param info authentication information from the user
503
>    * @return true if authentication successful, false otherwise
504
98c73
505
<   public boolean authenticate(String user, String password) throws
506
---
507
>   public boolean authenticate(AuthInfo info) throws
508
100,104c75,76
509
<     String ldapUrl = this.ldapUrl;
510
<     String ldapsUrl = this.ldapsUrl;
511
<     String ldapBase = this.ldapBase;
512
<     boolean authenticated = false;
513
<     String identifier = user;
514
---
515
> 	boolean authenticated = false;
516
>     String identifier = info.getUsername();
517
110c82
518
<       authenticated = ldapAuthenticate(identifier, password);
519
---
520
>       authenticated = ldapAuthenticate(identifier, info.getPassword());
521
119,120c91,92
522
<         String refUrl = "";
523
<         String refBase = "";
524
---
525
>         String refUrl;
526
>         String refBase;
527
132c104
528
<           authenticated = ldapAuthenticate(identifier, password,
529
---
530
>           authenticated = ldapAuthenticate(identifier, info.getPassword(),
531
138c110
532
<           authenticated = ldapAuthenticate(identifier, password);
533
---
534
>           authenticated = ldapAuthenticate(identifier, info.getPassword());
535
171c143
536
<       ConnectException, NamingException, NullPointerException {
537
---
538
> 	  NamingException, NullPointerException {
539
185c157
540
<       ConnectException, NamingException, NullPointerException {
541
---
542
>       NamingException, NullPointerException {
543
191,192c163,164
544
<       userName = identifier;
545
<       userPassword = password;
546
---
547
> //      userName = identifier;
548
> //      userPassword = password;
549
220,221d191
550
<         this.ldapUrl = ldapUrl;
551
<         this.ldapBase = ldapBase;
552
272c242
553
<    * @returns String the identifying name for the user,
554
---
555
>    * @return String the identifying name for the user,
556
423,425c393
557
<    * @param user the user for authenticating against the service
558
<    * @param password the password for authenticating against the service
559
<    * @returns string array of all of the user names
560
---
561
>    * @return string array of all of the user names
562
427c395
563
<   public String[][] getUsers(String user, String password) throws
564
---
565
>   public String[][] getUsers(AuthInfo info) throws
566
429c397
567
<     String[][] users = null;
568
---
569
>     String[][] users;
570
460c428
571
<       Attributes tempAttr = null;
572
---
573
>       Attributes tempAttr;
574
508c476
575
<         users[i][3] = (String) uorg.elementAt(i);
576
---
577
>         users[i][3] = (String) uou.elementAt(i);
578
529,530c497
579
<    * @param user the user for authenticating against the service
580
<    * @param password the password for authenticating against the service
581
---
582
>    * @param info represents the user making the request
583
532c499
584
<    * @returns string array of the user names belonging to the group
585
---
586
>    * @return string array of the user names belonging to the group
587
534c501
588
<   public String[] getUsers(String user, String password, String group) throws
589
---
590
>   public String[] getUsers(AuthInfo info, String group) throws
591
536c503
592
<     String[] users = null;
593
---
594
>     String[] users;
595
564d530
596
<             ;
597
596,598c562,563
598
<    * @param user the user for authenticating against the service
599
<    * @param password the password for authenticating against the service
600
<    * @returns string array of the group names
601
---
602
>    * @param info represents the user making the request
603
>    * @return string array of the group names
604
600c565
605
<   public String[][] getGroups(String user, String password) throws
606
---
607
>   public String[][] getGroups(AuthInfo info) throws
608
602c567
609
<     return getGroups(user, password, null);
610
---
611
>     return getGroups(info, null);
612
608,609c573
613
<    * @param user the user for authenticating against the service
614
<    * @param password the password for authenticating against the service
615
---
616
>    * @param info represents the user making the request
617
611c575
618
<    * @returns string array of the group names
619
---
620
>    * @return string array of the group names
621
613c577
622
<   public String[][] getGroups(String user, String password, String foruser) throws
623
---
624
>   public String[][] getGroups(AuthInfo info, String foruser) throws
625
617c581
626
<     Attributes tempAttr = null;
627
---
628
>     Attributes tempAttr;
629
620,621c584,585
630
<     userName = user;
631
<     userPassword = password;
632
---
633
> //    userName = user;
634
> //    userPassword = password;
635
640c604
636
<       String filter = null;
637
---
638
>       String filter;
639
708c672
640
<       String filter = null;
641
---
642
>       String filter;
643
768c732
644
<    * @returns HashMap a map of attribute name to a Vector of values
645
---
646
>    * @return HashMap a map of attribute name to a Vector of values
647
771c735
648
<     return getAttributes(null, null, foruser);
649
---
650
>     return getAttributes(null, foruser);
651
777,778c741
652
<    * @param user the user for authenticating against the service
653
<    * @param password the password for authenticating against the service
654
---
655
>    * @param info represents the user making the request
656
780c743
657
<    * @returns HashMap a map of attribute name to a Vector of values
658
---
659
>    * @return HashMap a map of attribute name to a Vector of values
660
782c745
661
<   public HashMap getAttributes(String user, String password, String foruser) throws
662
---
663
>   public HashMap getAttributes(AuthInfo info, String foruser) throws
664
785,787d747
665
<     String ldapUrl = this.ldapUrl;
666
<     String ldapBase = this.ldapBase;
667
<     String userident = foruser;
668
837,838c797
669
<   private Hashtable getSubtrees(String user, String password,
670
<                                 String ldapUrl, String ldapBase) throws
671
---
672
>   private Hashtable getSubtrees(String ldapUrl, String ldapBase) throws
673
886c845
674
<           String attrName = (String) attr.getID();
675
---
676
>           String attrName = attr.getID();
677
891c850
678
<             String refName = (String) attr.getID();
679
---
680
>             String refName = attr.getID();
681
946,947c905
682
<    * @param user the user which requests the information
683
<    * @param password the user's password
684
---
685
>    * @param info Auth Info representing the user who requests the information
686
949c907
687
<   public String getPrincipals(String user, String password) throws
688
---
689
>   public String getPrincipals(AuthInfo info) throws
690
952c910,911
691
<    
692
---
693
>     Vector usersIn = new Vector();
694
> 
695
960,961c919
696
<     Hashtable subtrees = getSubtrees(user, password, this.ldapUrl,
697
<                                      this.ldapBase);
698
---
699
>     Hashtable subtrees = getSubtrees(this.ldapUrl, this.ldapBase);
700
963c921
701
<     Enumeration keyEnum = subtrees.keys();
702
---
703
> 	  Enumeration keyEnum = subtrees.keys();
704
1002,1003c960,961
705
<       String[][] groups = getGroups(user, password);
706
<       String[][] users = getUsers(user, password);
707
---
708
>       String[][] groups = getGroups(info);
709
>       String[][] users = getUsers(info);
710
1012c970
711
<           String[] usersForGroup = getUsers(user, password, groups[i][0]);
712
---
713
>           String[] usersForGroup = getUsers(info, groups[i][0]);
714
1014c972,973
715
<             
716
---
717
>             usersIn.addElement(usersForGroup[j]);
718
> 
719
1042a1002
720
>         if (!usersIn.contains(users[j][0])) {
721
1053a1014
722
>         }
723
1056a1018,1022
724
>       if (!usersIn.isEmpty()) {
725
>         usersIn.removeAllElements();
726
>         usersIn.trimToSize();
727
>       }
728
> 
729
1087c1053
730
<     boolean isValid = false;
731
---
732
>     boolean isValid;
733
1090c1056,1057
734
<       isValid = authservice.authenticate(user, password);
735
---
736
> 		AuthInfo info = new AuthInfo(user, password);
737
> 	  isValid = authservice.authenticate(info);
738
1101c1068
739
<         HashMap userInfo = authservice.getAttributes(user, password, user);
740
---
741
>         HashMap userInfo = authservice.getAttributes(info, user);
742
1103c1070
743
<         Iterator attList = (Iterator) ( ( (Set) userInfo.keySet()).iterator());
744
---
745
>         Iterator attList = userInfo.keySet().iterator();
746
1118c1085
747
<         String[][] groups = authservice.getGroups(user, password);
748
---
749
>         String[][] groups = authservice.getGroups(info);
750
1129c1096
751
<         String[][] groups = authservice.getGroups(user, password, user);
752
---
753
>         String[][] groups = authservice.getGroups(info, user);
754
1141c1108
755
<         String[] users = authservice.getUsers(user, password, savedGroup);
756
---
757
>         String[] users = authservice.getUsers(info, savedGroup);
758
1151c1118
759
<         String[][] users = authservice.getUsers(user, password);
760
---
761
>         String[][] users = authservice.getUsers(info);
762
1160c1127
763
<         String out = authservice.getPrincipals(user, password);
764
---
765
>         String out = authservice.getPrincipals(info);
766
1186c1153
767
<     DirContext refDirContext = null;
768
---
769
>     DirContext refDirContext;
770
1188c1155
771
<     String referralInfo = null;
772
---
773
>     String referralInfo;
774
1202,1203c1169,1170
775
<         //MetaCatUtil.logMetacat.info("Processing referral (pr1.info): " + userName,35);
776
<         //MetaCatUtil.logMetacat.info("Processing referral (pr2)",35);
777
---
778
>         //MetaCatUtil.logMetacat.info("Processing referral (pr1.info): " + userName);
779
>         //MetaCatUtil.logMetacat.info("Processing referral (pr2)");
780
1205c1172
781
<         rContext = refExc.getReferralContext();
782
---
783
>         Context rContext = refExc.getReferralContext();
784
1251d1217
785
<       DirContext refDirContext = null;
786
1258,1259c1224
787
<           String refInfo = null;
788
<           refInfo = (String) refExc.getReferralInfo();
789
---
790
>           String refInfo = (String) refExc.getReferralInfo();
791
1262c1227
792
<                                      refInfo.toString());
793
---
794
>                                      refInfo);
795
Index: src/edu/ucsb/nceas/metacat/AuthSession.java
796
===================================================================
797
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/AuthSession.java,v
798
retrieving revision 1.18
799
diff -r1.18 AuthSession.java
800
30,31d29
801
< import java.net.ConnectException;
802
< import javax.servlet.http.HttpSession;
803
32a31,32
804
> import javax.servlet.http.HttpSession;
805
> import java.net.ConnectException;
806
41c41
807
<   private String authClass = null;
808
---
809
> 
810
52,54c52,86
811
<     MetaCatUtil util = new MetaCatUtil();
812
<     this.authClass = util.getOption("authclass");
813
<     this.authService = (AuthInterface)createObject(authClass);
814
---
815
>     String authClass = MetaCatUtil.getOption("authclass");
816
> 	this.authService = (AuthInterface)createObject(authClass);
817
> 
818
> 	if (authService instanceof AuthGsi) {
819
> 		// special config options for GSI authentication
820
> 		String authDelegateClass = MetaCatUtil.getOption("authDelegateClass");
821
> 		String gsiMapClass = MetaCatUtil.getOption("gsiMapClass");
822
> 		String authDelegationAllowed = MetaCatUtil.getOption("authDelegationAllowed");
823
> 		String authPrecedence = MetaCatUtil.getOption("authPrecedence");
824
> 
825
> 		AuthGsi gsi = (AuthGsi) authService;
826
> 		if (authDelegateClass != null) {
827
> 			AuthInterface delegate = (AuthInterface) createObject(authDelegateClass);
828
> 			gsi.setDelegate(delegate);
829
> 		}
830
> 		if (gsiMapClass != null) {
831
> 			GsiToUsernameMap map = (GsiToUsernameMap) createObject(gsiMapClass);
832
> 			gsi.setDnMap(map);
833
> 		}
834
> 		if (authDelegationAllowed != null) {
835
> 			boolean allowed = Boolean.valueOf(authDelegationAllowed).booleanValue();
836
> 			if (!allowed && !authDelegationAllowed.trim().toLowerCase().equals("false"))
837
> 				MetaCatUtil.logMetacat.warn("Config error: authDelegationAllowed "
838
> 					+ "must be \"true\" or \"false\" (found \""
839
> 					+ authDelegationAllowed + "\".");
840
> 			gsi.setAuthnDelegationAllowed(allowed);
841
> 		}
842
> 		if (authPrecedence != null) {
843
> 			try {
844
> 				gsi.setPrecedence(authPrecedence);
845
> 			} catch(IllegalArgumentException e) {
846
> 				System.err.println(e.getMessage());
847
> 			}
848
> 		}
849
> 	}
850
70,71c102
851
<    * @param username the username entered when login
852
<    * @param password the password entered when login
853
---
854
>    * @param info info from the user, such as username and password
855
73,77c104,107
856
<   public boolean authenticate(HttpServletRequest request,
857
<                               String username, String password)  {
858
<     String message = null;
859
<     try {
860
<       if ( authService.authenticate(username, password) ) {
861
---
862
>   public boolean authenticate(HttpServletRequest request, AuthInfo info)  {
863
>     String message;
864
> 	try {
865
> 	  if ( authService.authenticate(info) ) {
866
79c109
867
<         // getGroups returns groupname along with their description.
868
---
869
> 		// getGroups returns groupname along with their description.
870
82c112
871
<             authService.getGroups(username,password,username);
872
---
873
>             authService.getGroups(info,info.getUsername());
874
93c123
875
<         this.session = createSession(request, username, password, groups);
876
---
877
>         this.session = createSession(request, info, groups);
878
95c125
879
<         message = "Authentication successful for user: " + username;
880
---
881
>         message = "Authentication successful for user: " + info;
882
99c129
883
<         message = "Authentication failed for user: " + username;
884
---
885
> 		message = "Authentication failed for user: " + info;
886
104c134,135
887
<       message = "Connection to the authentication service failed in " +
888
---
889
> 	  ce.printStackTrace();
890
> 	  message = "Connection to the authentication service failed in " +
891
107c138,139
892
<       message = ise.getMessage();
893
---
894
> 	  ise.printStackTrace();
895
> 	  message = ise.getMessage();
896
114,116c146,147
897
<   /** Get new HttpSession and store username & password in it */
898
<   private HttpSession createSession(HttpServletRequest request,
899
<                                  String username, String password,
900
---
901
>   /** Get new HttpSession and store authentication info in it */
902
>   private HttpSession createSession(HttpServletRequest request, AuthInfo info,
903
129c160
904
<                                 session.getAttribute("username"));
905
---
906
>                                 session.getAttribute("auth"));
907
137,138c168
908
<     session.setAttribute("username", username);
909
<     session.setAttribute("password", password);
910
---
911
> 	session.setAttribute("auth", info);
912
145c175
913
<                                 session.getAttribute("username"));
914
---
915
>                                 session.getAttribute("auth"));
916
161,162c191
917
<    * @param user the user which requests the information
918
<    * @param password the user's password
919
---
920
>    * @param info represents the user who requests the information
921
164c193
922
<   public String getPrincipals(String user, String password)
923
---
924
>   public String getPrincipals(AuthInfo info)
925
167c196
926
<     return authService.getPrincipals(user, password);
927
---
928
>     return authService.getPrincipals(info);
929
210c239
930
<     Object object = null;
931
---
932
>     Object object;
933
Index: src/edu/ucsb/nceas/metacat/MetaCatServlet.java
934
===================================================================
935
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/MetaCatServlet.java,v
936
retrieving revision 1.226
937
diff -r1.226 MetaCatServlet.java
938
30,35c30
939
< import java.io.BufferedInputStream;
940
< import java.io.File;
941
< import java.io.FileInputStream;
942
< import java.io.IOException;
943
< import java.io.PrintWriter;
944
< import java.io.StringReader;
945
---
946
> import java.io.*;
947
37a33,34
948
> import java.net.URLEncoder;
949
> import java.net.URLDecoder;
950
44,48c41,42
951
< import java.util.Enumeration;
952
< import java.util.Hashtable;
953
< import java.util.Iterator;
954
< import java.util.PropertyResourceBundle;
955
< import java.util.Vector;
956
---
957
> import java.util.*;
958
> import java.util.regex.PatternSyntaxException;
959
52,55c46
960
< import javax.servlet.ServletConfig;
961
< import javax.servlet.ServletContext;
962
< import javax.servlet.ServletException;
963
< import javax.servlet.ServletOutputStream;
964
---
965
> import javax.servlet.*;
966
60a52,53
967
> import edu.ucsb.nceas.utilities.Options;
968
> 
969
61a55
970
> import org.ietf.jgss.GSSContext;
971
68,69d61
972
< import edu.ucsb.nceas.utilities.Options;
973
< 
974
164c156
975
<      
976
---
977
> 
978
166c158
979
< 	 
980
---
981
> 
982
181,182c173,174
983
<     	    LOG_CONFIG_NAME = dirPath + "/log4j.properties";
984
< 	    
985
---
986
>             LOG_CONFIG_NAME = dirPath + "/log4j.properties";
987
>         
988
213,214d204
989
<         } catch (ServletException ex) {
990
<             throw ex;
991
235d224
992
< 
993
237c226,230
994
<         handleGetOrPost(request, response);
995
---
996
>         try { handleGetOrPost(request, response); }
997
>         catch(RuntimeException e) {
998
>             e.printStackTrace();
999
>             throw new ServletException(e);
1000
>         }
1001
244d236
1002
< 
1003
246c238,242
1004
<         handleGetOrPost(request, response);
1005
---
1006
>         try { handleGetOrPost(request, response); }
1007
>         catch(RuntimeException e) {
1008
>             e.printStackTrace();
1009
>             throw new ServletException(e);
1010
>         }
1011
248a245,255
1012
>     /** Copied from org.globus.axis.gsi.GSIConstants, so that we can avoid
1013
>      *  a compile dependency. */
1014
>     private static final String
1015
>         GSI_CREDENTIALS = "org.globus.gsi.credentials",
1016
>         GSI_AUTHORIZATION = "org.globus.gsi.authorization",
1017
>         GSI_MODE = "org.globus.gsi.mode",
1018
>         GSI_AUTH_USERNAME = "org.globus.gsi.authorized.user.name",
1019
>         GSI_USER_DN = "org.globus.gsi.authorized.user.dn",
1020
>         GSI_ANONYMOUS = "org.globus.gsi.anonymous",
1021
>         GSI_CONTEXT = "org.globus.gsi.context";
1022
> 
1023
388d394
1024
< 
1025
403c409,410
1026
<         connPool.printMethodNameHavingBusyDBConnection();
1027
---
1028
>         if (connPool != null)
1029
>             connPool.printMethodNameHavingBusyDBConnection();
1030
415a423,438
1031
>             Enumeration headerNames = request.getHeaderNames();
1032
>             while (headerNames.hasMoreElements()) {
1033
>                 String headerName = (String) headerNames.nextElement();
1034
>             }
1035
> 
1036
>             // check whether incoming connection is via GSI-enabled HTTPS
1037
>             // these constants are available from GSIConstants, but not imported
1038
>             // here, to avoid dependencies
1039
>             GSSContext gsiContext = (GSSContext) request.getAttribute(GSI_CONTEXT);
1040
>             String gsiUserDN = (String) request.getAttribute(GSI_USER_DN);
1041
>             boolean gssConnection = gsiContext != null && gsiUserDN != null;
1042
>             if (gssConnection) {
1043
>                 params.put(GSI_CONTEXT, gsiContext);
1044
>                 params.put(GSI_USER_DN, gsiUserDN);
1045
>             }
1046
> 
1047
433a457,499
1048
>             // Get extra POST parameters because when the incoming request uses
1049
>             // chunked coding, they don't automatically get parsed.
1050
>             if ("application/x-www-form-urlencoded".equals(ctype)) {
1051
>                 try {
1052
>                     String post = readInputStreamAsString(request);
1053
>                     if (post != null && post.length() > 0) {
1054
>                         String[] posts = post.split("&");
1055
>                         for (int i = 0; i < posts.length; ++i) {
1056
>                             String[] a = posts[i].split("=");
1057
>                             for (int j = 0; j < a.length; ++j)
1058
>                                 a[j] = URLDecoder.decode(a[j]);
1059
>                             if (a.length >= 2) {
1060
>                                 addToMultimap(params, a[0], a[1]);
1061
>                             }
1062
>                         }
1063
>                     }
1064
>                 } catch(Exception e) {
1065
>                     String msg = "Exception reading remaining POST data: "
1066
>                         + e.getMessage();
1067
>                     if (MetaCatUtil.debugMessage(msg, 20))
1068
>                         e.printStackTrace();
1069
>                 }
1070
>             }
1071
> 
1072
>             String[] usernames = (String[]) params.get("username"),
1073
>                 passwords = (String[]) params.get("password");
1074
>             String username = (usernames != null && usernames.length > 0)
1075
>                 ? usernames[0] : null;
1076
>             String password = (passwords != null && passwords.length > 0)
1077
>                 ? passwords[0] : null;
1078
>             // if no other identifiers, set username to "public" (anonymous)
1079
>             if (username == null && gsiUserDN == null)
1080
>                 username = "public";
1081
>             AuthInfo authInfo = new AuthInfo
1082
>                 (username, password, gsiContext, gsiUserDN, request);
1083
> 
1084
>             for (Iterator i = params.keySet().iterator(); i.hasNext();) {
1085
>                 String key = (String) i.next();
1086
>                 Object val = params.get(key);
1087
>                 if (val == null) val = "null";
1088
>                 if (!(val instanceof Object[])) val = new Object[] { val };
1089
>             }
1090
> 
1091
456,457d521
1092
<             String username = null;
1093
<             String password = null;
1094
464c528
1095
<                 handleLoginAction(out, params, request, response);
1096
---
1097
>                 handleLoginAction(out, authInfo, params, request, response);
1098
476d539
1099
<                 boolean success = false;
1100
478,482c541,543
1101
<                 // pool
1102
<                 //size is greater than initial value, shrink the connection
1103
<                 // pool
1104
<                 //size to initial value
1105
<                 success = DBConnectionPool.shrinkConnectionPoolSize();
1106
---
1107
>                 //pool size is greater than initial value, shrink the
1108
>                 //connection pool size to initial value
1109
>                 boolean success = DBConnectionPool.shrinkConnectionPoolSize();
1110
496c557,573
1111
<                 if (sess.isNew() && !params.containsKey("sessionid")) {
1112
---
1113
>                 boolean newSession = sess.isNew() && !params.containsKey("sessionid");
1114
>                 if (authInfo.getGssContext() != null) {
1115
>                     // if using GSI for authentication, we lose our session
1116
>                     // each time, so we have to re-authenticate; fortunately
1117
>                     // we have enough information to do so
1118
>                     try {
1119
>                         AuthSession authSession = new AuthSession();
1120
>                         authSession.authenticate(request, authInfo);
1121
>                         // call it a continuing session
1122
>                         newSession = false;
1123
>                     } catch (Exception e) {
1124
>                         throw new ServletException
1125
>                             ("Unable to authenticate based on GSI credentials: "
1126
>                                 + e.getMessage(), e);
1127
>                     }
1128
>                 }
1129
>                 if (newSession) {
1130
499a577
1131
>                     authInfo = new AuthInfo("public", null);
1132
501c579
1133
<                     sess.setAttribute("username", username);
1134
---
1135
>                     sess.setAttribute("auth", authInfo);
1136
524c602
1137
<                              * sess.getAttribute("username") + " into session
1138
---
1139
>                              * sess.getAttribute("auth") + " into session
1140
535c613,614
1141
<                     username = (String) sess.getAttribute("username");
1142
---
1143
>                     authInfo = (AuthInfo) sess.getAttribute("auth");
1144
>                     username = authInfo.getUsername();
1145
538d616
1146
<                     password = (String) sess.getAttribute("password");
1147
543c621,623
1148
<                 if (username == null || (username.trim().equals(""))) {
1149
---
1150
>                 if ((username == null || (username.trim().equals("")))
1151
>                     && gsiContext == null )
1152
>                 {
1153
544a625,626
1154
>                     authInfo = new AuthInfo(username,  null);
1155
>                     sess.setAttribute("auth", authInfo);
1156
619c701
1157
<                 handleGetPrincipalsAction(out, username, password);
1158
---
1159
>                 handleGetPrincipalsAction(out, authInfo);
1160
646c728
1161
<             } else if (action.equals("login") || action.equals("logout")) {
1162
---
1163
>             } else if (action.equals("login") || action.equals("logout"), groupnames) {
1164
709a792,841
1165
>     /** Assume that <tt>map</tt>'s keys are objects and its values are arrays. */
1166
>     private void addToMultimap(Map params, String key, String value) {
1167
>         if (params.containsKey(key)) {
1168
>             String[] oldArray;
1169
>             Object old = params.get(key);
1170
>             if (old instanceof String[]) oldArray = (String[]) old;
1171
>             else {
1172
>                 oldArray = new String[1];
1173
>                 oldArray[0] = String.valueOf(old);
1174
>             }
1175
>             String[] newArray = new String[oldArray.length + 1];
1176
>             System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
1177
>             newArray[newArray.length - 1] = value;
1178
>             params.put(key, newArray);
1179
>         }
1180
>         else params.put(key, new String[] { value });
1181
>     }
1182
> 
1183
>     private static final int READ_CHUNK_SIZE = 1024;
1184
> 
1185
>     private String readInputStreamAsString(HttpServletRequest request)
1186
>         throws IOException
1187
>     {
1188
>         ServletInputStream in = request.getInputStream();
1189
>         List byteses = new ArrayList();
1190
>         int total = 0;
1191
>         while(true) {
1192
>             byte[] k = new byte[READ_CHUNK_SIZE];
1193
>             int n = in.read(k);
1194
>             if (n <= 0) break;
1195
>             else {
1196
>                 if (n < READ_CHUNK_SIZE) {
1197
>                     byte[] k2 = new byte[n];
1198
>                     System.arraycopy(k, 0, k2, 0, n);
1199
>                     k = k2;
1200
>                 }
1201
>                 total += n;
1202
>                 byteses.add(k);
1203
>             }
1204
>         }
1205
>         byte[] all = new byte[total];
1206
>         int start = 0;
1207
>         for (int i = 0; i < byteses.size(); i++) {
1208
>             byte[] k = (byte[]) byteses.get(i);
1209
>             System.arraycopy(k, 0, all, start, k.length);
1210
>             start += k.length;
1211
>         }
1212
>         return new String(all);
1213
>     }
1214
> 
1215
715c847
1216
<     private void handleLoginAction(PrintWriter out, Hashtable params,
1217
---
1218
>     private void handleLoginAction(PrintWriter out, AuthInfo info, Hashtable params,
1219
719c851
1220
<         AuthSession sess = null;
1221
---
1222
>         AuthSession sess;
1223
721c853
1224
<         if(params.get("username") == null){
1225
---
1226
>         if(info.getUsername() == null && info.getGssContext() == null){
1227
730c862,864
1228
<         if(params.get("password") == null){
1229
---
1230
>         if(info.getPassword() == null && info.getGssContext() == null
1231
>             && !info.isLocal())
1232
>         {
1233
739,741c873,874
1234
<         String un = ((String[]) params.get("username"))[0];
1235
<         MetaCatUtil.debugMessage("user " + un + " try to login", 20);
1236
<         String pw = ((String[]) params.get("password"))[0];
1237
---
1238
>         MetaCatUtil.debugMessage
1239
>             ("user " + info.toString(true) + " try to login", 20);
1240
756c889,890
1241
<         boolean isValid = sess.authenticate(request, un, pw);
1242
---
1243
> 
1244
>         boolean isValid = sess.authenticate(request, info);
1245
763c897
1246
<                     + "which has username" + session.getAttribute("username")
1247
---
1248
>                     + "which has username" + session.getAttribute("auth")
1249
807c941
1250
<                     + sess.getAttribute("username")
1251
---
1252
>                     + sess.getAttribute("auth")
1253
941,943c1075,1077
1254
<             		"attachment; filename=" 
1255
<             		+ docId + ".zip"); // Set the name of the zip file
1256
<             		
1257
---
1258
>                     "attachment; filename=" 
1259
>                     + docId + ".zip"); // Set the name of the zip file
1260
> 
1261
1357c1491
1262
<             
1263
---
1264
> 
1265
1642c1776
1266
<         
1267
---
1268
> 
1269
1644c1778
1270
<         	out.println("<?xml version=\"1.0\"?>");
1271
---
1272
>             out.println("<?xml version=\"1.0\"?>");
1273
2169,2170c2303
1274
<     private void handleGetPrincipalsAction(PrintWriter out, String user,
1275
<             String password)
1276
---
1277
>     private void handleGetPrincipalsAction(PrintWriter out, AuthInfo info)
1278
2174c2307
1279
<             String principals = auth.getPrincipals(user, password);
1280
---
1281
>             String principals = auth.getPrincipals(info);
1282
2478,2479c2611
1283
<         String username = null;
1284
<         String password = null;
1285
---
1286
>         AuthInfo auth = null;
1287
2485a2618
1288
>             // TODO: don't do this if GSI, since session will be new every time
1289
2487,2488c2620,2621
1290
<             username = "public";
1291
<             sess.setAttribute("username", username);
1292
---
1293
>             auth = new AuthInfo("public", null);
1294
>             sess.setAttribute("auth", auth);
1295
2490,2491c2623
1296
<             username = (String) sess.getAttribute("username");
1297
<             password = (String) sess.getAttribute("password");
1298
---
1299
>             auth = (AuthInfo) sess.getAttribute("auth");
1300
2512,2513c2644,2645
1301
<             if (username != null && !username.equals("public")) {
1302
<                 handleUploadAction(request, out, params, fileList, username,
1303
---
1304
>             if (auth != null && !"public".equals(auth.getUsername())) {
1305
>                 handleUploadAction(request, out, params, fileList, auth.getUsername(),
1306
2909c3041
1307
<     
1308
---
1309
> 
1310
Index: src/edu/ucsb/nceas/metacat/client/Metacat.java
1311
===================================================================
1312
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/client/Metacat.java,v
1313
retrieving revision 1.14
1314
diff -r1.14 Metacat.java
1315
26a27,28
1316
> import org.ietf.jgss.GSSCredential;
1317
> 
1318
54c56,88
1319
<     /**
1320
---
1321
> 	/**
1322
> 	 * <p>Log in to a Metacat server using a Grid Security Infrastructure (GSI)
1323
> 	 * credential to establish an HTTPS connection.  Instead of authenticating
1324
> 	 * the user via username and password, the user's identity will be
1325
> 	 * extracted from the credential's Distinguished Name (DN).</p>
1326
> 	 *
1327
> 	 * <p>Note that some installations will not have the necessary libraries to
1328
> 	 * run GSI, and therefore we need to be able to run the non-GSI Metacat
1329
> 	 * client even if those JARs are absent -- catching NoClassDefFoundError,
1330
> 	 * etc.</p>
1331
> 	 *
1332
> 	 * @return the response string from metacat in XML format
1333
> 	 * @throws MetacatAuthException when the client certificate is missing or
1334
> 	 * is not trusted or represents a user who is unknown or not authorized to
1335
> 	 * log in, or if the underlying connection is HTTP instead of HTTPS.
1336
> 	 * @throws UnsupportedOperationException if this client does not support
1337
> 	 * GSI-HTTPS.
1338
> 	 */
1339
> 	public String login(GSSCredential credential)
1340
> 			throws MetacatAuthException, MetacatInaccessibleException;
1341
> 
1342
> 	/**
1343
> 	 * Log in over a trusted connection (usually localhost HTTP) with just
1344
> 	 * a username to identify the user.  The server will only allow this login
1345
> 	 * method if it is configured to fully trust incoming connections from this
1346
> 	 * client.
1347
> 	 *
1348
> 	 * <p>This may be used, depending on the server's configuration, with
1349
> 	 * a PKI Distinguished Name (DN), or with an LDAP name.</p>
1350
> 	 */
1351
> 	public String login(String username) throws MetacatInaccessibleException, MetacatAuthException;
1352
> 
1353
> 	/**
1354
148d181
1355
<      * @param xmlDocument a Reader for accessing the document to be inserted
1356
238c271
1357
<      * @returns the sessionId as a String, or null if the session is invalid
1358
---
1359
>      * @return the sessionId as a String, or null if the session is invalid
1360
248c281
1361
<      * @param String the sessionId from a previously established session
1362
---
1363
>      * @param sessionId the session ID from a previously established session
1364
Index: src/edu/ucsb/nceas/metacat/client/MetacatClient.java
1365
===================================================================
1366
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/client/MetacatClient.java,v
1367
retrieving revision 1.18
1368
diff -r1.18 MetacatClient.java
1369
27,36d26
1370
< import java.io.BufferedReader;
1371
< import java.io.InputStream;
1372
< import java.io.InputStreamReader;
1373
< import java.io.PushbackReader;
1374
< import java.io.IOException;
1375
< import java.io.StringWriter;
1376
< import java.io.Reader;
1377
< import java.net.URL;
1378
< import java.util.Properties;
1379
< 
1380
39c29,34
1381
< import java.io.File;
1382
---
1383
> import edu.ucsb.nceas.metacat.client.gsi.MetacatGsiClient;
1384
> import org.ietf.jgss.GSSCredential;
1385
> 
1386
> import java.io.*;
1387
> import java.net.URL;
1388
> import java.util.Properties;
1389
49,50c44,45
1390
<     /** The URL string for the metacat server */
1391
<     private String metacatUrl;
1392
---
1393
> 	/** The URL string for the metacat server */
1394
> 	private String metacatUrl;
1395
52,53c47,48
1396
<     /** The session identifier for the session */
1397
<     private String sessionId;
1398
---
1399
> 	/** The session identifier for the session */
1400
> 	private String sessionId;
1401
55,802c50,839
1402
<     /**
1403
<      * Constructor to create a new instance. Protected because instances
1404
<      * should only be created by the factory MetacatFactory.
1405
<      */
1406
<     protected MetacatClient()
1407
<     {
1408
<         this.metacatUrl = null;
1409
<         this.sessionId = null;
1410
<     }
1411
< 
1412
<     /**
1413
<      *  Method used to log in to a metacat server. Implementations will need
1414
<      *  to cache a cookie value to make the session persistent.  Each time a
1415
<      *  call is made to one of the other methods (e.g., read), the cookie will
1416
<      *  need to be passed back to the metacat server along with the request.
1417
<      *
1418
<      *  @param username   the username of the user, like an LDAP DN
1419
<      *  @param password   the password for that user for authentication
1420
<      *  @return the response string from metacat in XML format
1421
<      *  @throws MetacatAuthException when the username/password could
1422
<      *                    not be authenticated
1423
<      */
1424
<     public String login(String username, String password)
1425
<            throws MetacatAuthException, MetacatInaccessibleException
1426
<     {
1427
<         Properties prop = new Properties();
1428
<         prop.put("action", "login");
1429
<         prop.put("qformat", "xml");
1430
<         prop.put("username", username);
1431
<         prop.put("password", password);
1432
< 
1433
<         String response = null;
1434
<         try {
1435
<             response = sendDataForString(prop, null, null, 0);
1436
<         } catch (Exception e) {
1437
<             throw new MetacatInaccessibleException(e.getMessage());
1438
<         }
1439
< 
1440
<         if (response.indexOf("<login>") == -1) {
1441
<             setSessionId("");
1442
<             throw new MetacatAuthException(response);
1443
<         } else {
1444
<             int start = response.indexOf("<sessionId>") + 11;
1445
<             int end = response.indexOf("</sessionId>");
1446
<             if ((start != -1) && (end != -1)) {
1447
<                 setSessionId(response.substring(start,end));
1448
<             }
1449
<         }
1450
<         return response;
1451
<     }
1452
< 
1453
<     /**
1454
<      *  Method used to log out a metacat server. The Metacat server will end
1455
<      *  the session when this call is invoked.
1456
<      *
1457
<      *  @return the response string from metacat in XML format
1458
<      *  @throws MetacatInaccessibleException when the metacat server can not be
1459
<      *                                    reached or does not respond
1460
<      */
1461
<     public String logout() throws MetacatInaccessibleException, MetacatException
1462
<     {
1463
<         Properties prop = new Properties();
1464
<         prop.put("action", "logout");
1465
<         prop.put("qformat", "xml");
1466
< 
1467
<         String response = null;
1468
<         try {
1469
<             response = sendDataForString(prop, null, null, 0);
1470
<         } catch (Exception e) {
1471
<             throw new MetacatInaccessibleException(e.getMessage());
1472
<         }
1473
< 
1474
<         if (response.indexOf("<logout>") == -1) {
1475
<             throw new MetacatException(response);
1476
<         }
1477
<         setSessionId("");
1478
<         return response;
1479
<     }
1480
< 
1481
<     /**
1482
<      * Read an XML document from the metacat server session, accessed by docid,
1483
<      * and returned as a Reader.
1484
<      *
1485
<      * @param docid the identifier of the document to be read
1486
<      * @return a Reader for accessing the document
1487
<      * @throws InsufficientKarmaException when the user has insufficent rights
1488
<      *                                    for the operation
1489
<      * @throws MetacatInaccessibleException when the metacat server can not be
1490
<      *                                    reached or does not respond
1491
<      * @throws MetacatException when the metacat server generates another error
1492
<      */
1493
<     public Reader read(String docid) throws InsufficientKarmaException,
1494
<         MetacatInaccessibleException, MetacatException
1495
<     {
1496
<         PushbackReader pbr = null;
1497
< 
1498
<         Properties prop = new Properties();
1499
<         prop.put("action", "read");
1500
<         prop.put("qformat", "xml");
1501
<         prop.put("docid", docid);
1502
< 
1503
<         InputStream response = null;
1504
<         try {
1505
<             response = sendData(prop, null, null, 0);
1506
<         } catch (Exception e) {
1507
<             throw new MetacatInaccessibleException(e.getMessage());
1508
<         }
1509
< 
1510
<         pbr = new PushbackReader(new InputStreamReader(response), 512);
1511
<         try {
1512
<             char[] characters = new char[512];
1513
<             int len = pbr.read(characters, 0, 512);
1514
<             StringWriter sw = new StringWriter();
1515
<             sw.write(characters, 0, len);
1516
<             String message = sw.toString();
1517
<             sw.close();
1518
<             pbr.unread(characters, 0, len);
1519
< 
1520
<             if (message.indexOf("<error>") != -1) {
1521
<                 if (message.indexOf("does not have permission") != -1) {
1522
<                     throw new InsufficientKarmaException(message);
1523
<                 } else {
1524
<                     throw new MetacatException(message);
1525
<                 }
1526
<             }
1527
<         } catch (IOException ioe) {
1528
<             throw new MetacatException(
1529
<                     "MetacatClient: Error converting Reader to String."
1530
<                     + ioe.getMessage());
1531
<         }
1532
< 
1533
<         return pbr;
1534
<     }
1535
< 
1536
< 
1537
<     /**
1538
<         * Read inline data from the metacat server session, accessed by
1539
<         * inlinedataid and returned as a Reader.
1540
<         *
1541
<         * @param inlinedataid the identifier of the data to be read
1542
<         * @return a Reader for accessing the document
1543
<         * @throws InsufficientKarmaException when the user has insufficent rights
1544
<         *                                    for the operation
1545
<         * @throws MetacatInaccessibleException when the metacat server can not be
1546
<         *                                    reached or does not respond
1547
<         * @throws MetacatException when the metacat server generates another error
1548
<         */
1549
<        public Reader readInlineData(String inlinedataid)
1550
<            throws InsufficientKarmaException,
1551
<            MetacatInaccessibleException, MetacatException
1552
<        {
1553
<            PushbackReader pbr = null;
1554
< 
1555
<            Properties prop = new Properties();
1556
<            prop.put("action", "readinlinedata");
1557
<            prop.put("inlinedataid", inlinedataid);
1558
< 
1559
<            InputStream response = null;
1560
<            try {
1561
<                response = sendData(prop, null, null, 0);
1562
<            } catch (Exception e) {
1563
<                throw new MetacatInaccessibleException(e.getMessage());
1564
<            }
1565
< 
1566
<            pbr = new PushbackReader(new InputStreamReader(response), 512);
1567
<            try {
1568
<                char[] characters = new char[512];
1569
<                int len = pbr.read(characters, 0, 512);
1570
<                StringWriter sw = new StringWriter();
1571
<                sw.write(characters, 0, len);
1572
<                String message = sw.toString();
1573
<                sw.close();
1574
<                pbr.unread(characters, 0, len);
1575
< 
1576
<                if (message.indexOf("<error>") != -1) {
1577
<                    if (message.indexOf("does not have permission") != -1) {
1578
<                        throw new InsufficientKarmaException(message);
1579
<                    } else {
1580
<                        throw new MetacatException(message);
1581
<                    }
1582
<                }
1583
<            } catch (IOException ioe) {
1584
<                throw new MetacatException(
1585
<                        "MetacatClient: Error converting Reader to String."
1586
<                        + ioe.getMessage());
1587
<            }
1588
< 
1589
<            return pbr;
1590
<        }
1591
< 
1592
<     /**
1593
<      * Query the metacat document store with the given metacat-compatible
1594
<      * query document, and return the result set as a Reader.
1595
<      *
1596
<      * @param xmlQuery a Reader for accessing the XML version of the query
1597
<      * @return a Reader for accessing the result set
1598
<      */
1599
<     public Reader query(Reader xmlQuery) throws MetacatInaccessibleException,
1600
<                                                 IOException
1601
<     {
1602
<         Reader reader = null;
1603
<         String query = null;
1604
<         try {
1605
<           query = IOUtil.getAsString(xmlQuery, true);
1606
<         } catch (IOException ioE) {
1607
<           throw ioE;
1608
<         }
1609
< 
1610
<         //set up properties
1611
<         Properties prop = new Properties();
1612
<         prop.put("action", "squery");
1613
<         prop.put("qformat", "xml");
1614
<         prop.put("query", query);
1615
< 
1616
<         InputStream response = null;
1617
<         try {
1618
<             response = sendData(prop, null, null, 0);
1619
<         } catch (Exception e) {
1620
<             throw new MetacatInaccessibleException(e.getMessage());
1621
<         }
1622
<         reader = new InputStreamReader(response);
1623
<         return reader;
1624
<     }
1625
< 
1626
<     /**
1627
<      * Insert an XML document into the repository.
1628
<      *
1629
<      * @param docid the docid to insert the document
1630
<      * @param xmlDocument a Reader for accessing the XML document to be inserted
1631
<      * @param schema a Reader for accessing the DTD or XML Schema for
1632
<      *               the document
1633
<      * @return the metacat response message
1634
<      * @throws InsufficientKarmaException when the user has insufficent rights
1635
<      *                                    for the operation
1636
<      * @throws MetacatInaccessibleException when the metacat server can not be
1637
<      *                                    reached or does not respond
1638
<      * @throws MetacatException when the metacat server generates another error
1639
<      * @throws IOException when there is an error reading the xml document
1640
<      */
1641
<     public String insert(String docid, Reader xmlDocument, Reader schema)
1642
<         throws InsufficientKarmaException, MetacatException, IOException,
1643
<         MetacatInaccessibleException
1644
<     {
1645
<         Reader reader = null;
1646
<         String doctext = null;
1647
<         String schematext = null;
1648
<         try {
1649
<           doctext = IOUtil.getAsString(xmlDocument, true);
1650
<           if (schema != null) {
1651
<               schematext = IOUtil.getAsString(schema, true);
1652
<           }
1653
<         } catch (IOException ioE) {
1654
<           throw ioE;
1655
<         }
1656
< 
1657
<         //set up properties
1658
<         Properties prop = new Properties();
1659
<         prop.put("action", "insert");
1660
<         prop.put("docid", docid);
1661
<         prop.put("doctext", doctext);
1662
<         if (schematext != null) {
1663
<             prop.put("dtdtext", schematext);
1664
<         }
1665
< 
1666
<         String response = null;
1667
<         try {
1668
<             response = sendDataForString(prop, null, null, 0);
1669
<         } catch (Exception e) {
1670
<             throw new MetacatInaccessibleException(e.getMessage());
1671
<         }
1672
< 
1673
<         // Check for an error condition
1674
<         if (response.indexOf("<error>") != -1) {
1675
<             if (response.indexOf("does not have permission") != -1) {
1676
<                 throw new InsufficientKarmaException(response);
1677
<             } else {
1678
<                 throw new MetacatException(response);
1679
<             }
1680
<         }
1681
< 
1682
<         return response;
1683
<     }
1684
< 
1685
<     /**
1686
<      * Update an XML document in the repository.
1687
<      *
1688
<      * @param docid the docid to update
1689
<      * @param xmlDocument a Reader for accessing the XML text to be updated
1690
<      * @param schema a Reader for accessing the DTD or XML Schema for
1691
<      *               the document
1692
<      * @return the metacat response message
1693
<      * @throws InsufficientKarmaException when the user has insufficent rights
1694
<      *                                    for the operation
1695
<      * @throws MetacatInaccessibleException when the metacat server can not be
1696
<      *                                    reached or does not respond
1697
<      * @throws MetacatException when the metacat server generates another error
1698
<      * @throws IOException when there is an error reading the xml document
1699
<      */
1700
<     public String update(String docid, Reader xmlDocument, Reader schema)
1701
<         throws InsufficientKarmaException, MetacatException, IOException,
1702
<         MetacatInaccessibleException
1703
<     {
1704
<         Reader reader = null;
1705
<         String doctext = null;
1706
<         String schematext = null;
1707
<         try {
1708
<           doctext = IOUtil.getAsString(xmlDocument, true);
1709
<           if (schema != null) {
1710
<               schematext = IOUtil.getAsString(schema, true);
1711
<           }
1712
<         } catch (IOException ioE) {
1713
<           throw ioE;
1714
<         }
1715
< 
1716
<         //set up properties
1717
<         Properties prop = new Properties();
1718
<         prop.put("action", "update");
1719
<         prop.put("docid", docid);
1720
<         prop.put("doctext", doctext);
1721
<         if (schematext != null) {
1722
<             prop.put("dtdtext", schematext);
1723
<         }
1724
< 
1725
<         String response = null;
1726
<         try {
1727
<             response = sendDataForString(prop, null, null, 0);
1728
<         } catch (Exception e) {
1729
<             throw new MetacatInaccessibleException(e.getMessage());
1730
<         }
1731
< 
1732
<         // Check for an error condition
1733
<         if (response.indexOf("<error>") != -1) {
1734
<             if (response.indexOf("does not have permission") != -1) {
1735
<                 throw new InsufficientKarmaException(response);
1736
<             } else {
1737
<                 throw new MetacatException(response);
1738
<             }
1739
<         }
1740
< 
1741
<         return response;
1742
<     }
1743
< 
1744
<     /**
1745
<        * Upload a data document into the repository.
1746
<        *
1747
<        * @param docid the docid to insert the document
1748
<        * @param document a Reader for accessing the document to be uploaded
1749
<        * @return the metacat response message
1750
<        * @throws InsufficientKarmaException when the user has insufficent rights
1751
<        *                                    for the operation
1752
<        * @throws MetacatInaccessibleException when the metacat server can not be
1753
<        *                                    reached or does not respond
1754
<        * @throws MetacatException when the metacat server generates another error
1755
<        * @throws IOException when there is an error reading the xml document
1756
<        */
1757
<       public String upload(String docid, File file)
1758
<           throws InsufficientKarmaException, MetacatException, IOException,
1759
<           MetacatInaccessibleException
1760
<       {
1761
< 
1762
<           URL url = new URL(metacatUrl.trim());
1763
<           HttpMessage msg = new HttpMessage(url);
1764
<           //set up properties
1765
<           Properties arg = new Properties();
1766
<           arg.put("action", "upload");
1767
<           arg.put("docid", docid);
1768
< 
1769
<           Properties filenames = new Properties();
1770
<           String filename = file.getAbsolutePath();
1771
<           filenames.put("datafile", filename);
1772
< 
1773
<           String response = null;
1774
<           try {
1775
<             response = sendDataForString(arg, filenames, null, 0);
1776
<           } catch (Exception e) {
1777
<             throw new MetacatInaccessibleException(e.getMessage());
1778
<           }
1779
< 
1780
<           // Check for an error condition
1781
<           if (response.indexOf("<error>") != -1) {
1782
<             if (response.indexOf("does not have permission") != -1) {
1783
<               throw new InsufficientKarmaException(response);
1784
<             } else {
1785
<               throw new MetacatException(response);
1786
<             }
1787
<           }
1788
< 
1789
<           return response;
1790
<       }
1791
< 
1792
<         /**
1793
<           * Upload a data document into the repository.
1794
<           *
1795
<           * @param docid the docid to insert the document
1796
<           * @param document a Reader for accessing the document to be uploaded
1797
<           * @return the metacat response message
1798
<           * @throws InsufficientKarmaException when the user has insufficent rights
1799
<           *                                    for the operation
1800
<           * @throws MetacatInaccessibleException when the metacat server can not be
1801
<           *                                    reached or does not respond
1802
<           * @throws MetacatException when the metacat server generates another error
1803
<           * @throws IOException when there is an error reading the xml document
1804
<           */
1805
< 
1806
< 
1807
<       public String upload(String docid, String filename, InputStream fileData,
1808
<                            int size)
1809
<           throws InsufficientKarmaException, MetacatException, IOException,
1810
<           MetacatInaccessibleException {
1811
< 
1812
<           URL url = new URL(metacatUrl.trim());
1813
<           HttpMessage msg = new HttpMessage(url);
1814
<           //set up properties
1815
<           Properties arg = new Properties();
1816
<           arg.put("action", "upload");
1817
<           arg.put("docid", docid);
1818
< 
1819
<           Properties filenames = new Properties();
1820
<           filenames.put("datafile", filename);
1821
< 
1822
<           String response = null;
1823
<           try {
1824
<             response = sendDataForString(arg, filenames, fileData, size);
1825
<           } catch (Exception e) {
1826
<             throw new MetacatInaccessibleException(e.getMessage());
1827
<           }
1828
< 
1829
<           // Check for an error condition
1830
<           if (response.indexOf("<error>") != -1) {
1831
<             if (response.indexOf("does not have permission") != -1) {
1832
<               throw new InsufficientKarmaException(response);
1833
<             } else {
1834
<               throw new MetacatException(response);
1835
<             }
1836
<           }
1837
< 
1838
<           return response;
1839
<       }
1840
< 
1841
<     /**
1842
<      * Delete an XML document in the repository.
1843
<      *
1844
<      * @param docid the docid to delete
1845
<      * @return the metacat response message
1846
<      * @throws InsufficientKarmaException when the user has insufficent rights
1847
<      *                                    for the operation
1848
<      * @throws MetacatInaccessibleException when the metacat server can not be
1849
<      *                                    reached or does not respond
1850
<      * @throws MetacatException when the metacat server generates another error
1851
<      */
1852
<     public String delete(String docid)
1853
<         throws InsufficientKarmaException, MetacatException,
1854
<         MetacatInaccessibleException
1855
<     {
1856
<         //set up properties
1857
<         Properties prop = new Properties();
1858
<         prop.put("action", "delete");
1859
<         prop.put("docid", docid);
1860
< 
1861
<         String response = null;
1862
<         try {
1863
<             response = sendDataForString(prop, null, null, 0);
1864
<         } catch (Exception e) {
1865
<             throw new MetacatInaccessibleException(e.getMessage());
1866
<         }
1867
< 
1868
<         // Check for an error condition
1869
<         if (response.indexOf("<error>") != -1) {
1870
<             if (response.indexOf("does not have permission") != -1) {
1871
<                 throw new InsufficientKarmaException(response);
1872
<             } else {
1873
<                 throw new MetacatException(response);
1874
<             }
1875
<         }
1876
<         return response;
1877
<     }
1878
< 
1879
< 
1880
<     /**
1881
<      * set the access on an XML document in the repository.
1882
<      *
1883
<      * @param _docid the docid of the document for which the access should be applied.
1884
<      *
1885
<      * @param _principal the document's principal
1886
<      *
1887
<      * @param _permission the access permission to be applied to the docid
1888
<      *  {e.g. read,write,all}
1889
<      *
1890
<      * @param _permType the permission type to be applied to the document
1891
<      *  {e.g. allow or deny}
1892
<      *
1893
<      * @param _permOrder the order that the document's permissions should be
1894
<      *  processed {e.g. denyFirst or allowFirst}
1895
<      *
1896
<      *
1897
<      * @return the metacat response message
1898
<      *
1899
<      * @throws InsufficientKarmaException when the user has insufficent rights
1900
<      *                                    for the operation
1901
<      * @throws MetacatInaccessibleException when the metacat server can not be
1902
<      *                                    reached or does not respond
1903
<      * @throws MetacatException when the metacat server generates another error
1904
<      */
1905
<     public String setAccess(String _docid, String _principal, String
1906
<                             _permission, String _permType, 
1907
<                             String _permOrder )
1908
<         throws InsufficientKarmaException, MetacatException,
1909
<         MetacatInaccessibleException
1910
<     {  
1911
<         //set up properties
1912
<         Properties prop = new Properties();
1913
<         prop.put("action", "setaccess");
1914
<         prop.put("docid", _docid);
1915
<         prop.put("principal", _principal);
1916
<         prop.put("permission", _permission);
1917
<         prop.put("permType", _permType);
1918
<         prop.put("permOrder", _permOrder);
1919
< 
1920
<         String response = null;
1921
<         try {
1922
<             response = sendDataForString(prop, null, null, 0);
1923
<         } catch (Exception e) {
1924
<             throw new MetacatInaccessibleException(e.getMessage());
1925
<         }
1926
< 
1927
<         // Check for an error condition
1928
<         if (response.indexOf("<error>") != -1) {
1929
<             if (response.indexOf("does not have permission") != -1) {
1930
<                 throw new InsufficientKarmaException(response);
1931
<             } else {
1932
<                 throw new MetacatException(response);
1933
<             }
1934
<         }
1935
<         return response;
1936
<     }
1937
< 
1938
<     /**
1939
<      * When the MetacatFactory creates an instance it needs to set the
1940
<      * MetacatUrl to which connections should be made.
1941
<      *
1942
<      * @param metacatUrl the URL for the metacat server
1943
<      */
1944
<     public void setMetacatUrl(String metacatUrl)
1945
<     {
1946
<         this.metacatUrl = metacatUrl;
1947
<     }
1948
< 
1949
<     /**
1950
<      * Get the session identifier for this session.  This is only valid if
1951
<      * the login methods has been called successfully for this Metacat object
1952
<      * beforehand.
1953
<      *
1954
<      * @returns the sessionId as a String, or null if the session is invalid
1955
<      */
1956
<     public String getSessionId()
1957
<     {
1958
<         return this.sessionId;
1959
<     }
1960
< 
1961
<     /**
1962
<      * Set the session identifier for this session.  This identifier was
1963
<      * previously established with a call to login.  To continue to use the
1964
<      * same session, set the session id before making a call to one of the
1965
<      * metacat access methods (e.g., read, query, insert, etc.).
1966
<      *
1967
<      * @param String the sessionId from a previously established session
1968
<      */
1969
<     public void setSessionId(String sessionId)
1970
<     {
1971
<         this.sessionId = sessionId;
1972
<     }
1973
<     
1974
<     /**
1975
<      * The method will return the lasted revision in metacat server 
1976
<      * for a given document id. If some error happent, this method will throw
1977
<      * a exception.   
1978
<      * @param docId String  the given docid you want to use. the docid it self
1979
<      *                      can have or haven't revision number
1980
<      * @throws MetacatException
1981
<      */
1982
<      public int getNewestDocRevision(String docId) throws MetacatException
1983
<      {
1984
<        int rev = 0;
1985
<        //set up properties
1986
<        Properties prop = new Properties();
1987
<        prop.put("action", "getrevisionanddoctype");
1988
<        prop.put("docid", docId);
1989
<        
1990
<        String response = null;
1991
<         try 
1992
<         {
1993
<             response = sendDataForString(prop, null, null, 0);
1994
<             String revStr = parserRevisionResponse(response);
1995
<             Integer revObj = new Integer(revStr);
1996
<             rev = revObj.intValue();
1997
<             // Check for an error condition
1998
<            if (response.indexOf("<error>") != -1) 
1999
<            {
2000
<               throw new MetacatException(response);
2001
<            }
2002
< 
2003
<         } 
2004
<         catch (Exception e) 
2005
<         {
2006
<             throw new MetacatException(e.getMessage());
2007
<         }
2008
<         return rev;
2009
<      }
2010
< 
2011
< 
2012
<     /************************************************************************
2013
<      * PRIVATE METHODS
2014
<      ************************************************************************/
2015
< 
2016
<     /**
2017
<      * Send a request to metacat.
2018
<      *
2019
<      * @param prop the properties to be URL encoded and sent
2020
<      * @param filename  the properties to be sent to Metacat
2021
<      *                  in case of upload, otherwise null
2022
<      * @param fileData  the inputStream for the file data to be sent to Metacat
2023
<      *                  in case of upload, otherwise null
2024
<      * @param size      the size of the data being sent to Metacat
2025
<      *                  in case of upload, otherwise 0
2026
<      */
2027
<     synchronized private InputStream sendDataOnce(Properties args,
2028
<                                                   Properties filename,
2029
<                                                   InputStream fileData,
2030
<                                                   int size)
2031
<         throws Exception
2032
<     {
2033
<         InputStream returnStream = null;
2034
<         URL url = new URL(metacatUrl);
2035
<         HttpMessage msg = new HttpMessage(url);
2036
<         msg.setCookie("JSESSIONID="+this.sessionId);
2037
<         if (filename == null){
2038
<             returnStream = msg.sendPostData(args);
2039
<         } else if (fileData == null){
2040
<             returnStream = msg.sendPostData(args, filename);
2041
<         } else if (size > 0) {
2042
<             returnStream = msg.sendPostData(args, filename, fileData, size);
2043
<         } else {
2044
<             throw new MetacatException("Invalid size specified for " +
2045
<                                        "the input stream being passed");
2046
<         }
2047
<         return returnStream;
2048
<     }
2049
< 
2050
<     /**
2051
<      * Send a request to Metacat
2052
<      *
2053
<      * @param args  the properties to be sent to Metacat
2054
<      * @param filename  the properties to be sent to Metacat
2055
<      *                  in case of upload, otherwise null
2056
<      * @param fileData  the inputStream for the file data to be sent to Metacat
2057
<      *                  in case of upload, otherwise null
2058
<      * @param size      the size of the data being sent to Metacat
2059
<      *                  in case of upload, otherwise 0
2060
<      * @return      InputStream as returned by Metacat
2061
<      */
2062
<     synchronized private InputStream sendData(Properties args,
2063
<                                               Properties filename,
2064
<                                               InputStream fileData,
2065
<                                               int size)
2066
<         throws Exception
2067
<     {
2068
<         InputStream returnStream = null;
2069
< 
2070
<         /*
2071
<             Note:  The reason that there are three try statements all executing
2072
<             the same code is that there is a problem with the initial connection
2073
<             using the HTTPClient protocol handler.  These try statements make
2074
<             sure that a connection is made because it gives each connection a
2075
<             2nd and 3rd chance to work before throwing an error.
2076
<             THIS IS A TOTAL HACK.  THIS NEEDS TO BE LOOKED INTO AFTER THE BETA1
2077
<             RELEASE OF MORPHO!!!  cwb (7/24/01)
2078
<           */
2079
<         try {
2080
<            return sendDataOnce(args, filename, fileData, size);
2081
<         } catch (Exception e) {
2082
<             try {
2083
<                 return sendDataOnce(args, filename, fileData, size);
2084
<             } catch (Exception e2) {
2085
<                 try {
2086
<                     return sendDataOnce(args, filename, fileData, size);
2087
<                 } catch (Exception e3) {
2088
<                     System.err.println(
2089
<                             "Failed to send data to metacat 3 times.");
2090
<                     throw e3;
2091
<                 }
2092
<             }
2093
<         }
2094
<     }
2095
< 
2096
<     /**
2097
<      * Send a request to Metacat
2098
<      *
2099
<      * @param args      the properties to be sent to Metacat
2100
<      * @param filename  the properties to be sent to Metacat
2101
<      *                  in case of upload, otherwise null
2102
<      * @param fileData  the inputStream for the file data to be sent to Metacat
2103
<      *                  in case of upload, otherwise null
2104
<      * @param size      the size of the data being sent to Metacat
2105
<      *                  in case of upload, otherwise 0
2106
<      * @return          a string as returned by Metacat
2107
<      */
2108
<     synchronized private String sendDataForString(Properties args,
2109
<                                                   Properties filename,
2110
<                                                   InputStream fileData,
2111
<                                                   int size)
2112
<         throws Exception
2113
<     {
2114
<         String response = null;
2115
< 
2116
<         try {
2117
<             InputStreamReader returnStream =
2118
<                     new InputStreamReader(sendData(args, filename,
2119
<                                                    fileData, size));
2120
<             StringWriter sw = new StringWriter();
2121
<             int len;
2122
<             char[] characters = new char[512];
2123
<             while ((len = returnStream.read(characters, 0, 512)) != -1) {
2124
<                 sw.write(characters, 0, len);
2125
<             }
2126
<             returnStream.close();
2127
<             response = sw.toString();
2128
<             sw.close();
2129
<         } catch (Exception e) {
2130
<             throw e;
2131
<         }
2132
<         return response;
2133
<     }
2134
<     
2135
<     /*
2136
<      * "getversionanddoctype" action will return a string from metacat server.
2137
<      * The string format is "revision;doctype"(This is bad idea, we should use xml)
2138
<      * This method will get revision string from the response string
2139
<      */
2140
<     private String parserRevisionResponse(String response) throws Exception
2141
<     {
2142
<       String revision = null;
2143
<       if (response != null)
2144
<       {
2145
<         int firstSemiCol = response.indexOf(";");
2146
<         revision = response.substring(0, firstSemiCol);
2147
<       }
2148
<       return revision;
2149
<     }
2150
---
2151
> 	/**
2152
> 	 * Constructor to create a new instance. Protected because instances
2153
> 	 * should only be created by the factory MetacatFactory.
2154
> 	 */
2155
> 	protected MetacatClient()
2156
> 	{
2157
> 		this.metacatUrl = null;
2158
> 		this.sessionId = null;
2159
> 	}
2160
> 
2161
> 	/**
2162
> 	 *  Method used to log in to a metacat server. Implementations will need
2163
> 	 *  to cache a cookie value to make the session persistent.  Each time a
2164
> 	 *  call is made to one of the other methods (e.g., read), the cookie will
2165
> 	 *  need to be passed back to the metacat server along with the request.
2166
> 	 *
2167
> 	 *  @param username   the username of the user, like an LDAP DN
2168
> 	 *  @param password   the password for that user for authentication
2169
> 	 *  @return the response string from metacat in XML format
2170
> 	 *  @throws MetacatAuthException when the username/password could
2171
> 	 *                    not be authenticated
2172
> 	 */
2173
> 	public String login(String username, String password)
2174
> 		   throws MetacatAuthException, MetacatInaccessibleException
2175
> 	{
2176
> 		Properties prop = new Properties();
2177
> 		prop.put("action", "login");
2178
> 		prop.put("qformat", "xml");
2179
> 		if (username != null) prop.put("username", username);
2180
> 		if (password != null) prop.put("password", password);
2181
> 
2182
> 		String response = null;
2183
> 		try {
2184
> 			response = sendDataForString(prop, null, null, 0);
2185
> 		} catch (Exception e) {
2186
> 			throw new MetacatInaccessibleException(e);
2187
> 		}
2188
> 
2189
> 		if (response.indexOf("<login>") == -1) {
2190
> 			setSessionId("");
2191
> 			throw new MetacatAuthException(response);
2192
> 		} else {
2193
> 			int start = response.indexOf("<sessionId>") + 11;
2194
> 			int end = response.indexOf("</sessionId>");
2195
> 			if ((start != -1) && (end != -1)) {
2196
> 				setSessionId(response.substring(start,end));
2197
> 			}
2198
> 		}
2199
> 		return response;
2200
> 	}
2201
> 
2202
> 	/**
2203
> 	 * Not implemented -- use {@link MetacatGsiClient} instead.
2204
> 	 * @throws UnsupportedOperationException every time
2205
> 	 */
2206
> 	public String login(GSSCredential credential)
2207
> 			throws MetacatAuthException, MetacatInaccessibleException
2208
> 	{
2209
> 		// be careful not to do any class-loading here, since some clients will
2210
> 		// not have the JARs needed to run the GSI-enabled Metacat client.
2211
> 		throw new UnsupportedOperationException
2212
> 				("Not implemented -- use MetacatGsiClient instead.");
2213
> 	}
2214
> 
2215
> 	/**
2216
> 	 * Log in over a trusted connection (usually localhost HTTP) with just
2217
> 	 * a username to identify the user.  The server will only allow this login
2218
> 	 * method if it is configured to fully trust incoming connections from this
2219
> 	 * client.
2220
> 	 *
2221
> 	 * <p>This may be used, depending on the server's configuration, with
2222
> 	 * a PKI Distinguished Name (DN), or with an LDAP name.</p>
2223
> 	 */
2224
> 	public String login(String username)
2225
> 		throws MetacatInaccessibleException, MetacatAuthException
2226
> 	{
2227
> 		return login(username, null);
2228
> 	}
2229
> 
2230
> 	/**
2231
> 	 *  Method used to log out a metacat server. The Metacat server will end
2232
> 	 *  the session when this call is invoked.
2233
> 	 *
2234
> 	 *  @return the response string from metacat in XML format
2235
> 	 *  @throws MetacatInaccessibleException when the metacat server can not be
2236
> 	 *                                    reached or does not respond
2237
> 	 */
2238
> 	public String logout() throws MetacatInaccessibleException, MetacatException
2239
> 	{
2240
> 		Properties prop = new Properties();
2241
> 		prop.put("action", "logout");
2242
> 		prop.put("qformat", "xml");
2243
> 
2244
> 		String response = null;
2245
> 		try {
2246
> 			response = sendDataForString(prop, null, null, 0);
2247
> 		} catch (Exception e) {
2248
> 			throw new MetacatInaccessibleException(e);
2249
> 		}
2250
> 
2251
> 		if (response.indexOf("<logout>") == -1) {
2252
> 			throw new MetacatException(response);
2253
> 		}
2254
> 		setSessionId("");
2255
> 		return response;
2256
> 	}
2257
> 
2258
> 	/**
2259
> 	 * Read an XML document from the metacat server session, accessed by docid,
2260
> 	 * and returned as a Reader.
2261
> 	 *
2262
> 	 * @param docid the identifier of the document to be read
2263
> 	 * @return a Reader for accessing the document
2264
> 	 * @throws InsufficientKarmaException when the user has insufficent rights
2265
> 	 *                                    for the operation
2266
> 	 * @throws MetacatInaccessibleException when the metacat server can not be
2267
> 	 *                                    reached or does not respond
2268
> 	 * @throws MetacatException when the metacat server generates another error
2269
> 	 */
2270
> 	public Reader read(String docid) throws InsufficientKarmaException,
2271
> 		MetacatInaccessibleException, MetacatException
2272
> 	{
2273
> 		PushbackReader pbr = null;
2274
> 
2275
> 		Properties prop = new Properties();
2276
> 		prop.put("action", "read");
2277
> 		prop.put("qformat", "xml");
2278
> 		prop.put("docid", docid);
2279
> 
2280
> 		InputStream response = null;
2281
> 		try {
2282
> 			response = sendData(prop, null, null, 0);
2283
> 		} catch (Exception e) {
2284
> 			throw new MetacatInaccessibleException(e);
2285
> 		}
2286
> 
2287
> 		pbr = new PushbackReader(new InputStreamReader(response), 512);
2288
> 		try {
2289
> 			char[] characters = new char[512];
2290
> 			int len = pbr.read(characters, 0, 512);
2291
> 			StringWriter sw = new StringWriter();
2292
> 			sw.write(characters, 0, len);
2293
> 			String message = sw.toString();
2294
> 			sw.close();
2295
> 			pbr.unread(characters, 0, len);
2296
> 
2297
> 			if (message.indexOf("<error>") != -1) {
2298
> 				if (message.indexOf("does not have permission") != -1) {
2299
> 					throw new InsufficientKarmaException(message);
2300
> 				} else {
2301
> 					throw new MetacatException(message);
2302
> 				}
2303
> 			}
2304
> 		} catch (IOException ioe) {
2305
> 			throw new MetacatException(
2306
> 					"MetacatClient: Error converting Reader to String: "
2307
> 					+ ioe.getMessage(), ioe);
2308
> 		}
2309
> 
2310
> 		return pbr;
2311
> 	}
2312
> 
2313
> 
2314
> 	/**
2315
> 		* Read inline data from the metacat server session, accessed by
2316
> 		* inlinedataid and returned as a Reader.
2317
> 		*
2318
> 		* @param inlinedataid the identifier of the data to be read
2319
> 		* @return a Reader for accessing the document
2320
> 		* @throws InsufficientKarmaException when the user has insufficent rights
2321
> 		*                                    for the operation
2322
> 		* @throws MetacatInaccessibleException when the metacat server can not be
2323
> 		*                                    reached or does not respond
2324
> 		* @throws MetacatException when the metacat server generates another error
2325
> 		*/
2326
> 	   public Reader readInlineData(String inlinedataid)
2327
> 		   throws InsufficientKarmaException,
2328
> 		   MetacatInaccessibleException, MetacatException
2329
> 	   {
2330
> 		   PushbackReader pbr = null;
2331
> 
2332
> 		   Properties prop = new Properties();
2333
> 		   prop.put("action", "readinlinedata");
2334
> 		   prop.put("inlinedataid", inlinedataid);
2335
> 
2336
> 		   InputStream response = null;
2337
> 		   try {
2338
> 			   response = sendData(prop, null, null, 0);
2339
> 		   } catch (Exception e) {
2340
> 			   throw new MetacatInaccessibleException(e);
2341
> 		   }
2342
> 
2343
> 		   pbr = new PushbackReader(new InputStreamReader(response), 512);
2344
> 		   try {
2345
> 			   char[] characters = new char[512];
2346
> 			   int len = pbr.read(characters, 0, 512);
2347
> 			   StringWriter sw = new StringWriter();
2348
> 			   sw.write(characters, 0, len);
2349
> 			   String message = sw.toString();
2350
> 			   sw.close();
2351
> 			   pbr.unread(characters, 0, len);
2352
> 
2353
> 			   if (message.indexOf("<error>") != -1) {
2354
> 				   if (message.indexOf("does not have permission") != -1) {
2355
> 					   throw new InsufficientKarmaException(message);
2356
> 				   } else {
2357
> 					   throw new MetacatException(message);
2358
> 				   }
2359
> 			   }
2360
> 		   } catch (IOException ioe) {
2361
> 			   throw new MetacatException(
2362
> 					   "MetacatClient: Error converting Reader to String: "
2363
> 					   + ioe.getMessage(), ioe);
2364
> 		   }
2365
> 
2366
> 		   return pbr;
2367
> 	   }
2368
> 
2369
> 	/**
2370
> 	 * Query the metacat document store with the given metacat-compatible
2371
> 	 * query document, and return the result set as a Reader.
2372
> 	 *
2373
> 	 * @param xmlQuery a Reader for accessing the XML version of the query
2374
> 	 * @return a Reader for accessing the result set
2375
> 	 */
2376
> 	public Reader query(Reader xmlQuery) throws MetacatInaccessibleException,
2377
> 												IOException
2378
> 	{
2379
> 		Reader reader = null;
2380
> 		String query = null;
2381
> 		try {
2382
> 		  query = IOUtil.getAsString(xmlQuery, true);
2383
> 		} catch (IOException ioE) {
2384
> 		  throw ioE;
2385
> 		}
2386
> 
2387
> 		//set up properties
2388
> 		Properties prop = new Properties();
2389
> 		prop.put("action", "squery");
2390
> 		prop.put("qformat", "xml");
2391
> 		prop.put("query", query);
2392
> 
2393
> 		InputStream response = null;
2394
> 		try {
2395
> 			response = sendData(prop, null, null, 0);
2396
> 		} catch (Exception e) {
2397
> 			throw new MetacatInaccessibleException(e);
2398
> 		}
2399
> 		reader = new InputStreamReader(response);
2400
> 		return reader;
2401
> 	}
2402
> 
2403
> 	/**
2404
> 	 * Insert an XML document into the repository.
2405
> 	 *
2406
> 	 * @param docid the docid to insert the document
2407
> 	 * @param xmlDocument a Reader for accessing the XML document to be inserted
2408
> 	 * @param schema a Reader for accessing the DTD or XML Schema for
2409
> 	 *               the document
2410
> 	 * @return the metacat response message
2411
> 	 * @throws InsufficientKarmaException when the user has insufficent rights
2412
> 	 *                                    for the operation
2413
> 	 * @throws MetacatInaccessibleException when the metacat server can not be
2414
> 	 *                                    reached or does not respond
2415
> 	 * @throws MetacatException when the metacat server generates another error
2416
> 	 * @throws IOException when there is an error reading the xml document
2417
> 	 */
2418
> 	public String insert(String docid, Reader xmlDocument, Reader schema)
2419
> 		throws InsufficientKarmaException, MetacatException, IOException,
2420
> 		MetacatInaccessibleException
2421
> 	{
2422
> 		Reader reader = null;
2423
> 		String doctext = null;
2424
> 		String schematext = null;
2425
> 		try {
2426
> 		  doctext = IOUtil.getAsString(xmlDocument, true);
2427
> 		  if (schema != null) {
2428
> 			  schematext = IOUtil.getAsString(schema, true);
2429
> 		  }
2430
> 		} catch (IOException ioE) {
2431
> 		  throw ioE;
2432
> 		}
2433
> 
2434
> 		//set up properties
2435
> 		Properties prop = new Properties();
2436
> 		prop.put("action", "insert");
2437
> 		prop.put("docid", docid);
2438
> 		prop.put("doctext", doctext);
2439
> 		if (schematext != null) {
2440
> 			prop.put("dtdtext", schematext);
2441
> 		}
2442
> 
2443
> 		String response = null;
2444
> 		try {
2445
> 			response = sendDataForString(prop, null, null, 0);
2446
> 		} catch (Exception e) {
2447
> 			throw new MetacatInaccessibleException(e);
2448
> 		}
2449
> 
2450
> 		// Check for an error condition
2451
> 		if (response.indexOf("<error>") != -1) {
2452
> 			if (response.indexOf("does not have permission") != -1) {
2453
> 				throw new InsufficientKarmaException(response);
2454
> 			} else {
2455
> 				throw new MetacatException(response);
2456
> 			}
2457
> 		}
2458
> 
2459
> 		return response;
2460
> 	}
2461
> 
2462
> 	/**
2463
> 	 * Update an XML document in the repository.
2464
> 	 *
2465
> 	 * @param docid the docid to update
2466
> 	 * @param xmlDocument a Reader for accessing the XML text to be updated
2467
> 	 * @param schema a Reader for accessing the DTD or XML Schema for
2468
> 	 *               the document
2469
> 	 * @return the metacat response message
2470
> 	 * @throws InsufficientKarmaException when the user has insufficent rights
2471
> 	 *                                    for the operation
2472
> 	 * @throws MetacatInaccessibleException when the metacat server can not be
2473
> 	 *                                    reached or does not respond
2474
> 	 * @throws MetacatException when the metacat server generates another error
2475
> 	 * @throws IOException when there is an error reading the xml document
2476
> 	 */
2477
> 	public String update(String docid, Reader xmlDocument, Reader schema)
2478
> 		throws InsufficientKarmaException, MetacatException, IOException,
2479
> 		MetacatInaccessibleException
2480
> 	{
2481
> 		Reader reader = null;
2482
> 		String doctext = null;
2483
> 		String schematext = null;
2484
> 		try {
2485
> 		  doctext = IOUtil.getAsString(xmlDocument, true);
2486
> 		  if (schema != null) {
2487
> 			  schematext = IOUtil.getAsString(schema, true);
2488
> 		  }
2489
> 		} catch (IOException ioE) {
2490
> 		  throw ioE;
2491
> 		}
2492
> 
2493
> 		//set up properties
2494
> 		Properties prop = new Properties();
2495
> 		prop.put("action", "update");
2496
> 		prop.put("docid", docid);
2497
> 		prop.put("doctext", doctext);
2498
> 		if (schematext != null) {
2499
> 			prop.put("dtdtext", schematext);
2500
> 		}
2501
> 
2502
> 		String response = null;
2503
> 		try {
2504
> 			response = sendDataForString(prop, null, null, 0);
2505
> 		} catch (Exception e) {
2506
> 			throw new MetacatInaccessibleException(e);
2507
> 		}
2508
> 
2509
> 		// Check for an error condition
2510
> 		if (response.indexOf("<error>") != -1) {
2511
> 			if (response.indexOf("does not have permission") != -1) {
2512
> 				throw new InsufficientKarmaException(response);
2513
> 			} else {
2514
> 				throw new MetacatException(response);
2515
> 			}
2516
> 		}
2517
> 
2518
> 		return response;
2519
> 	}
2520
> 
2521
> 	/**
2522
> 	   * Upload a data document into the repository.
2523
> 	   *
2524
> 	   * @param docid the docid to insert the document
2525
> 	   * @param document a Reader for accessing the document to be uploaded
2526
> 	   * @return the metacat response message
2527
> 	   * @throws InsufficientKarmaException when the user has insufficent rights
2528
> 	   *                                    for the operation
2529
> 	   * @throws MetacatInaccessibleException when the metacat server can not be
2530
> 	   *                                    reached or does not respond
2531
> 	   * @throws MetacatException when the metacat server generates another error
2532
> 	   * @throws IOException when there is an error reading the xml document
2533
> 	   */
2534
> 	  public String upload(String docid, File file)
2535
> 		  throws InsufficientKarmaException, MetacatException, IOException,
2536
> 		  MetacatInaccessibleException
2537
> 	  {
2538
> 
2539
> 		  //set up properties
2540
> 		  Properties arg = new Properties();
2541
> 		  arg.put("action", "upload");
2542
> 		  arg.put("docid", docid);
2543
> 
2544
> 		  Properties filenames = new Properties();
2545
> 		  String filename = file.getAbsolutePath();
2546
> 		  filenames.put("datafile", filename);
2547
> 
2548
> 		  String response = null;
2549
> 		  try {
2550
> 			response = sendDataForString(arg, filenames, null, 0);
2551
> 		  } catch (Exception e) {
2552
> 			throw new MetacatInaccessibleException(e);
2553
> 		  }
2554
> 
2555
> 		  // Check for an error condition
2556
> 		  if (response.indexOf("<error>") != -1) {
2557
> 			if (response.indexOf("does not have permission") != -1) {
2558
> 			  throw new InsufficientKarmaException(response);
2559
> 			} else {
2560
> 			  throw new MetacatException(response);
2561
> 			}
2562
> 		  }
2563
> 
2564
> 		  return response;
2565
> 	  }
2566
> 
2567
> 		/**
2568
> 		  * Upload a data document into the repository.
2569
> 		  *
2570
> 		  * @param docid the docid to insert the document
2571
> 		  * @param document a Reader for accessing the document to be uploaded
2572
> 		  * @return the metacat response message
2573
> 		  * @throws InsufficientKarmaException when the user has insufficent rights
2574
> 		  *                                    for the operation
2575
> 		  * @throws MetacatInaccessibleException when the metacat server can not be
2576
> 		  *                                    reached or does not respond
2577
> 		  * @throws MetacatException when the metacat server generates another error
2578
> 		  * @throws IOException when there is an error reading the xml document
2579
> 		  */
2580
> 
2581
> 
2582
> 	  public String upload(String docid, String filename, InputStream fileData,
2583
> 						   int size)
2584
> 		  throws InsufficientKarmaException, MetacatException, IOException,
2585
> 		  MetacatInaccessibleException {
2586
> 
2587
> 		  //set up properties
2588
> 		  Properties arg = new Properties();
2589
> 		  arg.put("action", "upload");
2590
> 		  arg.put("docid", docid);
2591
> 
2592
> 		  Properties filenames = new Properties();
2593
> 		  filenames.put("datafile", filename);
2594
> 
2595
> 		  String response;
2596
> 		  try {
2597
> 			response = sendDataForString(arg, filenames, fileData, size);
2598
> 		  } catch (Exception e) {
2599
> 			throw new MetacatInaccessibleException(e);
2600
> 		  }
2601
> 
2602
> 		  // Check for an error condition
2603
> 		  if (response.indexOf("<error>") != -1) {
2604
> 			if (response.indexOf("does not have permission") != -1) {
2605
> 			  throw new InsufficientKarmaException(response);
2606
> 			} else {
2607
> 			  throw new MetacatException(response);
2608
> 			}
2609
> 		  }
2610
> 
2611
> 		  return response;
2612
> 	  }
2613
> 
2614
> 	/**
2615
> 	 * Delete an XML document in the repository.
2616
> 	 *
2617
> 	 * @param docid the docid to delete
2618
> 	 * @return the metacat response message
2619
> 	 * @throws InsufficientKarmaException when the user has insufficent rights
2620
> 	 *                                    for the operation
2621
> 	 * @throws MetacatInaccessibleException when the metacat server can not be
2622
> 	 *                                    reached or does not respond
2623
> 	 * @throws MetacatException when the metacat server generates another error
2624
> 	 */
2625
> 	public String delete(String docid)
2626
> 		throws InsufficientKarmaException, MetacatException,
2627
> 		MetacatInaccessibleException
2628
> 	{
2629
> 		//set up properties
2630
> 		Properties prop = new Properties();
2631
> 		prop.put("action", "delete");
2632
> 		prop.put("docid", docid);
2633
> 
2634
> 		String response = null;
2635
> 		try {
2636
> 			response = sendDataForString(prop, null, null, 0);
2637
> 		} catch (Exception e) {
2638
> 			throw new MetacatInaccessibleException(e);
2639
> 		}
2640
> 
2641
> 		// Check for an error condition
2642
> 		if (response.indexOf("<error>") != -1) {
2643
> 			if (response.indexOf("does not have permission") != -1) {
2644
> 				throw new InsufficientKarmaException(response);
2645
> 			} else {
2646
> 				throw new MetacatException(response);
2647
> 			}
2648
> 		}
2649
> 		return response;
2650
> 	}
2651
> 
2652
> 
2653
> 	/**
2654
> 	 * set the access on an XML document in the repository.
2655
> 	 *
2656
> 	 * @param _docid the docid of the document for which the access should be applied.
2657
> 	 *
2658
> 	 * @param _principal the document's principal
2659
> 	 *
2660
> 	 * @param _permission the access permission to be applied to the docid
2661
> 	 *  {e.g. read,write,all}
2662
> 	 *
2663
> 	 * @param _permType the permission type to be applied to the document
2664
> 	 *  {e.g. allow or deny}
2665
> 	 *
2666
> 	 * @param _permOrder the order that the document's permissions should be
2667
> 	 *  processed {e.g. denyFirst or allowFirst}
2668
> 	 *
2669
> 	 *
2670
> 	 * @return the metacat response message
2671
> 	 *
2672
> 	 * @throws InsufficientKarmaException when the user has insufficent rights
2673
> 	 *                                    for the operation
2674
> 	 * @throws MetacatInaccessibleException when the metacat server can not be
2675
> 	 *                                    reached or does not respond
2676
> 	 * @throws MetacatException when the metacat server generates another error
2677
> 	 */
2678
> 	public String setAccess(String _docid, String _principal, String
2679
> 							_permission, String _permType,
2680
> 										 String _permOrder )
2681
> 		throws InsufficientKarmaException, MetacatException,
2682
> 		MetacatInaccessibleException
2683
> 	{
2684
> 		//set up properties
2685
> 		Properties prop = new Properties();
2686
> 		prop.put("action", "setaccess");
2687
> 		prop.put("docid", _docid);
2688
> 		prop.put("principal", _principal);
2689
> 		prop.put("permission", _permission);
2690
> 		prop.put("permType", _permType);
2691
> 		prop.put("permOrder", _permOrder);
2692
> 
2693
> 		String response = null;
2694
> 		try {
2695
> 			response = sendDataForString(prop, null, null, 0);
2696
> 		} catch (Exception e) {
2697
> 			throw new MetacatInaccessibleException(e);
2698
> 		}
2699
> 
2700
> 		// Check for an error condition
2701
> 		if (response.indexOf("<error>") != -1) {
2702
> 			if (response.indexOf("does not have permission") != -1) {
2703
> 				throw new InsufficientKarmaException(response);
2704
> 			} else {
2705
> 				throw new MetacatException(response);
2706
> 			}
2707
> 		}
2708
> 		return response;
2709
> 	}
2710
> 
2711
> 	/**
2712
> 	 * When the MetacatFactory creates an instance it needs to set the
2713
> 	 * MetacatUrl to which connections should be made.
2714
> 	 *
2715
> 	 * @param metacatUrl the URL for the metacat server
2716
> 	 */
2717
> 	public void setMetacatUrl(String metacatUrl)
2718
> 	{
2719
> 		this.metacatUrl = metacatUrl;
2720
> 	}
2721
> 
2722
> 	/**
2723
> 	 * The value set via {@link #setMetacatUrl(String)}.
2724
> 	 */
2725
> 	public String getMetacatUrl()
2726
> 	{
2727
> 		return metacatUrl;
2728
> 	}
2729
> 
2730
> 	/**
2731
> 	 * Get the session identifier for this session.  This is only valid if
2732
> 	 * the login methods has been called successfully for this Metacat object
2733
> 	 * beforehand.
2734
> 	 *
2735
> 	 * @return the sessionId as a String, or null if the session is invalid
2736
> 	 */
2737
> 	public String getSessionId()
2738
> 	{
2739
> 		return this.sessionId;
2740
> 	}
2741
> 
2742
> 	/**
2743
> 	 * Set the session identifier for this session.  This identifier was
2744
> 	 * previously established with a call to login.  To continue to use the
2745
> 	 * same session, set the session id before making a call to one of the
2746
> 	 * metacat access methods (e.g., read, query, insert, etc.).
2747
> 	 *
2748
> 	 * @param sessionId the sessionId from a previously established session
2749
> 	 */
2750
> 	public void setSessionId(String sessionId)
2751
> 	{
2752
> 		this.sessionId = sessionId;
2753
> 	}
2754
> 
2755
> 	/**
2756
> 	 * The method will return the lasted revision in metacat server
2757
> 	 * for a given document id. If some error happent, this method will throw
2758
> 	 * a exception.
2759
> 	 * @param docId String  the given docid you want to use. the docid it self
2760
> 	 *                      can have or haven't revision number
2761
> 	 * @throws MetacatException
2762
> 	 */
2763
> 	 public int getNewestDocRevision(String docId) throws MetacatException
2764
> 	 {
2765
> 	   int rev = 0;
2766
> 	   //set up properties
2767
> 	   Properties prop = new Properties();
2768
> 	   prop.put("action", "getrevisionanddoctype");
2769
> 	   prop.put("docid", docId);
2770
> 
2771
> 	   String response = null;
2772
> 		try
2773
> 		{
2774
> 			response = sendDataForString(prop, null, null, 0);
2775
> 			String revStr = parserRevisionResponse(response);
2776
> 			Integer revObj = new Integer(revStr);
2777
> 			rev = revObj.intValue();
2778
> 			// Check for an error condition
2779
> 		   if (response.indexOf("<error>") != -1)
2780
> 		   {
2781
> 			  throw new MetacatException(response);
2782
> 		   }
2783
> 
2784
> 		}
2785
> 		catch (Exception e)
2786
> 		{
2787
> 			throw new MetacatException(e);
2788
> 		}
2789
> 		return rev;
2790
> 	 }
2791
> 
2792
> 
2793
> 	/************************************************************************
2794
> 	 * PRIVATE METHODS
2795
> 	 ************************************************************************/
2796
> 
2797
> 	/**
2798
> 	 * Send a request to metacat.
2799
> 	 *
2800
> 	 * @param args      the properties to be URL encoded and sent
2801
> 	 * @param filename  the properties to be sent to Metacat
2802
> 	 *                  in case of upload, otherwise null
2803
> 	 * @param fileData  the inputStream for the file data to be sent to Metacat
2804
> 	 *                  in case of upload, otherwise null
2805
> 	 * @param size      the size of the data being sent to Metacat
2806
> 	 *                  in case of upload, otherwise 0
2807
> 	 */
2808
> 	synchronized protected InputStream sendDataOnce(Properties args,
2809
> 													Properties filename,
2810
> 													InputStream fileData,
2811
> 													int size)
2812
> 		throws Exception
2813
> 	{
2814
> 		HttpMessage msg = createHttpMessage();
2815
> 		msg.setCookie("JSESSIONID="+this.sessionId);
2816
> 		return xmit(msg, args, filename, fileData, size);
2817
> 	}
2818
> 
2819
> 	/** Create an HttpMessage that can send messages to the server.
2820
> 	 *  Designed to be overrideable in case a subclass connects to a server
2821
> 	 *  differently. */
2822
> 	protected HttpMessage createHttpMessage()
2823
> 		throws IOException, MetacatInaccessibleException, MetacatAuthException
2824
> 	{
2825
> 		URL url = new URL(metacatUrl.trim());
2826
> 		return new HttpMessage(url);
2827
> 	}
2828
> 
2829
> 	/** Helper function to {@link #sendDataOnce}. */
2830
> 	protected static InputStream xmit
2831
> 		(HttpMessage msg, Properties args, Properties filename,
2832
> 		 InputStream fileData, int size)
2833
> 		throws MetacatException, IOException
2834
> 	{
2835
> 		if (filename == null){
2836
> 			return msg.sendPostData(args);
2837
> 		} else if (fileData == null){
2838
> 			return msg.sendPostData(args, filename);
2839
> 		} else if (size > 0) {
2840
> 			return msg.sendPostData(args, filename, fileData, size);
2841
> 		} else {
2842
> 			throw new MetacatException("Invalid size specified for " +
2843
> 									   "the input stream being passed");
2844
> 		}
2845
> 	}
2846
> 
2847
> 	/**
2848
> 	 * Send a request to Metacat
2849
> 	 *
2850
> 	 * @param args  the properties to be sent to Metacat
2851
> 	 * @param filename  the properties to be sent to Metacat
2852
> 	 *                  in case of upload, otherwise null
2853
> 	 * @param fileData  the inputStream for the file data to be sent to Metacat
2854
> 	 *                  in case of upload, otherwise null
2855
> 	 * @param size      the size of the data being sent to Metacat
2856
> 	 *                  in case of upload, otherwise 0
2857
> 	 * @return      InputStream as returned by Metacat
2858
> 	 */
2859
> 	synchronized private InputStream sendData(Properties args,
2860
> 											  Properties filename,
2861
> 											  InputStream fileData,
2862
> 											  int size)
2863
> 		throws Exception
2864
> 	{
2865
> 		InputStream returnStream = null;
2866
> 
2867
> 		/*
2868
> 					Note:  The reason that there are three try statements all executing
2869
> 					the same code is that there is a problem with the initial connection
2870
> 					using the HTTPClient protocol handler.  These try statements make
2871
> 					sure that a connection is made because it gives each connection a
2872
> 					2nd and 3rd chance to work before throwing an error.
2873
> 					THIS IS A TOTAL HACK.  THIS NEEDS TO BE LOOKED INTO AFTER THE BETA1
2874
> 					RELEASE OF MORPHO!!!  cwb (7/24/01)
2875
> 				  */
2876
> 		try {
2877
> 		   return sendDataOnce(args, filename, fileData, size);
2878
> 		} catch (Exception e) {
2879
> 			try {
2880
> 				return sendDataOnce(args, filename, fileData, size);
2881
> 			} catch (Exception e2) {
2882
> 				try {
2883
> 					return sendDataOnce(args, filename, fileData, size);
2884
> 				} catch (Exception e3) {
2885
> 					System.err.println(
2886
> 							"Failed to send data to metacat 3 times.");
2887
> 					throw e3;
2888
> 				}
2889
> 			}
2890
> 		}
2891
> 	}
2892
> 
2893
> 	/**
2894
> 	 * Send a request to Metacat
2895
> 	 *
2896
> 	 * @param args      the properties to be sent to Metacat
2897
> 	 * @param filename  the properties to be sent to Metacat
2898
> 	 *                  in case of upload, otherwise null
2899
> 	 * @param fileData  the inputStream for the file data to be sent to Metacat
2900
> 	 *                  in case of upload, otherwise null
2901
> 	 * @param size      the size of the data being sent to Metacat
2902
> 	 *                  in case of upload, otherwise 0
2903
> 	 * @return          a string as returned by Metacat
2904
> 	 */
2905
> 	synchronized protected String sendDataForString(Properties args,
2906
> 													Properties filename,
2907
> 													InputStream fileData,
2908
> 													int size)
2909
> 		throws Exception
2910
> 	{
2911
> 		InputStreamReader returnStream =
2912
> 				new InputStreamReader(sendData(args, filename,
2913
> 											   fileData, size));
2914
> 		StringWriter sw = new StringWriter();
2915
> 		int len;
2916
> 		char[] characters = new char[512];
2917
> 		while ((len = returnStream.read(characters, 0, 512)) != -1) {
2918
> 			sw.write(characters, 0, len);
2919
> 		}
2920
> 		returnStream.close();
2921
> 		String response = sw.toString();
2922
> 		sw.close();
2923
> 		return response;
2924
> 	}
2925
> 
2926
> 	/*
2927
> 		 * "getversionanddoctype" action will return a string from metacat server.
2928
> 		 * The string format is "revision;doctype"(This is bad idea, we should use xml)
2929
> 		 * This method will get revision string from the response string
2930
> 		 */
2931
> 	private String parserRevisionResponse(String response) throws Exception
2932
> 	{
2933
> 	  String revision = null;
2934
> 	  if (response != null)
2935
> 	  {
2936
> 		int firstSemiCol = response.indexOf(";");
2937
> 		revision = response.substring(0, firstSemiCol);
2938
> 	  }
2939
> 	  return revision;
2940
> 	}
2941
Index: src/edu/ucsb/nceas/metacat/client/MetacatException.java
2942
===================================================================
2943
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/client/MetacatException.java,v
2944
retrieving revision 1.1
2945
diff -r1.1 MetacatException.java
2946
39a40,47
2947
> 
2948
> 	public MetacatException(Throwable cause) {
2949
> 		super(cause);
2950
> 	}
2951
> 
2952
> 	public MetacatException(String message, Throwable cause) {
2953
> 		super(message, cause);
2954
> 	}
2955
Index: src/edu/ucsb/nceas/metacat/client/MetacatFactory.java
2956
===================================================================
2957
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/client/MetacatFactory.java,v
2958
retrieving revision 1.1
2959
diff -r1.1 MetacatFactory.java
2960
27c27,31
2961
< import java.io.Reader;
2962
---
2963
> import java.net.URL;
2964
> import java.net.MalformedURLException;
2965
> import java.util.Map;
2966
> import java.util.HashMap;
2967
> import java.util.Collections;
2968
35,36c39,84
2969
<     private static final String metacatClientClass = 
2970
<          "edu.ucsb.nceas.metacat.client.MetacatClient";
2971
---
2972
> 	/** Register Metacat client classes by protocol. */
2973
> 	private static final Map PROTOCOL_CLIENT_CLASS_MAP;
2974
> 	static {
2975
> 		Map protoMap = new HashMap();
2976
> 		protoMap.put("http", "edu.ucsb.nceas.metacat.client.MetacatClient");
2977
> //		protoMap.put("https", "edu.ucsb.nceas.metacat.client.MetacatClient");
2978
> 		protoMap.put("https", "edu.ucsb.nceas.metacat.client.gsi.MetacatGsiClient");
2979
> 		// httpg requires a special class that requires GSI libraries
2980
> 		protoMap.put("httpg", "edu.ucsb.nceas.metacat.client.gsi.MetacatGsiClient");
2981
> 		PROTOCOL_CLIENT_CLASS_MAP = Collections.unmodifiableMap(protoMap);
2982
> 	}
2983
> 
2984
> 	/**
2985
> 	 *  Create a new instance of a Metacat object of raccessing a server.
2986
> 	 *
2987
> 	 *  @param metacatUrl the url location of the metacat server
2988
> 	 *  @throws MetacatInaccessibleException when the metacat server can not
2989
> 	 *                    be reached
2990
> 	 */
2991
> 	public static Metacat createMetacatConnection(String metacatUrl)
2992
> 		   throws MetacatInaccessibleException
2993
> 	{
2994
> 		Metacat m;
2995
> 		try {
2996
> 			URL url = new URL(metacatUrl);
2997
> 			String clientClass = (String)
2998
> 				PROTOCOL_CLIENT_CLASS_MAP.get(url.getProtocol().toLowerCase());
2999
> 			if (clientClass == null)
3000
> 				clientClass = (String) PROTOCOL_CLIENT_CLASS_MAP.get("http");
3001
> 			Class c = Class.forName(clientClass);
3002
> 			m = (Metacat)c.newInstance();
3003
> 		} catch (InstantiationException e) {
3004
> 			throw new MetacatInaccessibleException(e);
3005
> 		} catch (IllegalAccessException e) {
3006
> 			throw new MetacatInaccessibleException(e);
3007
> 		} catch (ClassNotFoundException e) {
3008
> 			throw new MetacatInaccessibleException
3009
> 				("Unable to instantiate metacat client for server URL \""
3010
> 					+ metacatUrl + "\".", e);
3011
> 		} catch (NoClassDefFoundError e) {
3012
> 			throw new MetacatInaccessibleException
3013
> 				("Unable to instantiate metacat client for server URL \""
3014
> 					+ metacatUrl + "\".", e);
3015
> 		} catch (MalformedURLException e) {
3016
> 			throw new MetacatInaccessibleException(e);
3017
> 		}
3018
38,58c86
3019
<     /**
3020
<      *  Create a new instance of a Metacat object of raccessing a server.
3021
<      *
3022
<      *  @param metacatUrl the url location of the metacat server
3023
<      *  @throws MetacatInaccessibleException when the metacat server can not
3024
<      *                    be reached
3025
<      */
3026
<     public static Metacat createMetacatConnection(String metacatUrl) 
3027
<            throws MetacatInaccessibleException
3028
<     {
3029
<         Metacat m = null;
3030
<         try {
3031
<             Class c = Class.forName(metacatClientClass);
3032
<             m = (Metacat)c.newInstance();
3033
<         } catch (InstantiationException e) {
3034
<             throw new MetacatInaccessibleException(e.getMessage());
3035
<         } catch (IllegalAccessException e) {
3036
<             throw new MetacatInaccessibleException(e.getMessage());
3037
<         } catch (ClassNotFoundException e) {
3038
<             throw new MetacatInaccessibleException(e.getMessage());
3039
<         }
3040
---
3041
> 		m.setMetacatUrl(metacatUrl);
3042
60,63c88,89
3043
<         m.setMetacatUrl(metacatUrl);
3044
< 
3045
<         return m;
3046
<     }
3047
---
3048
> 		return m;
3049
> 	}
3050
Index: src/edu/ucsb/nceas/metacat/client/MetacatInaccessibleException.java
3051
===================================================================
3052
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/client/MetacatInaccessibleException.java,v
3053
retrieving revision 1.1
3054
diff -r1.1 MetacatInaccessibleException.java
3055
40a41,48
3056
> 
3057
> 	public MetacatInaccessibleException(Throwable cause) {
3058
> 		super(cause);
3059
> 	}
3060
> 
3061
> 	public MetacatInaccessibleException(String message, Throwable cause) {
3062
> 		super(message, cause);
3063
> 	}
3064
Index: src/edu/ucsb/nceas/metacat/harvesterClient/HarvesterRegistration.java
3065
===================================================================
3066
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/harvesterClient/HarvesterRegistration.java,v
3067
retrieving revision 1.13
3068
diff -r1.13 HarvesterRegistration.java
3069
28a29,30
3070
> import edu.ucsb.nceas.metacat.AuthInfo;
3071
> 
3072
362c364
3073
<     String ldapDN;
3074
---
3075
> 	String ldapDN;
3076
379,380c381,383
3077
<     ldapDN = (String) httpSession.getAttribute("username");
3078
<     ldapPwd = (String) httpSession.getAttribute("password");
3079
---
3080
> 	AuthInfo auth = (AuthInfo) httpSession.getAttribute("auth");
3081
> 	ldapDN = auth.getUsername();
3082
>     ldapPwd = auth.getPassword();
3083
531,532c534,536
3084
<     ldapDN = (String) httpSession.getAttribute("username");
3085
<     ldapPwd = (String) httpSession.getAttribute("password");
3086
---
3087
> 	AuthInfo auth = (AuthInfo) httpSession.getAttribute("auth");
3088
> 	ldapDN = auth.getUsername();
3089
>     ldapPwd = auth.getPassword();
3090
Index: src/edu/ucsb/nceas/metacat/harvesterClient/HarvesterRegistrationLogin.java
3091
===================================================================
3092
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/harvesterClient/HarvesterRegistrationLogin.java,v
3093
retrieving revision 1.7
3094
diff -r1.7 HarvesterRegistrationLogin.java
3095
33a34
3096
> import edu.ucsb.nceas.metacat.AuthInfo;
3097
42c43
3098
<     final String LDAP_DOMAIN = ",dc=ecoinformatics,dc=org";
3099
---
3100
> 	final String LDAP_DOMAIN = ",dc=ecoinformatics,dc=org";
3101
44,129c45,130
3102
<     /**
3103
<      *  Handle "GET" method requests from HTTP clients
3104
<      *
3105
<      *  @param  req   The request
3106
<      *  @param  res   The response
3107
<      *  @throws ServletException, java.io.IOException
3108
<      */
3109
<     public void doGet(HttpServletRequest req, HttpServletResponse res)
3110
<                 throws ServletException, java.io.IOException {
3111
<         handleGetOrPost(req, res);
3112
<     }
3113
< 
3114
< 
3115
<     /**
3116
<      *  Handle "POST" method requests from HTTP clients
3117
<      *
3118
<      *  @param  req   The request
3119
<      *  @param  res  The response
3120
<      *  @throws ServletException, java.io.IOException
3121
<      */
3122
<     public void doPost(HttpServletRequest req, HttpServletResponse res)
3123
<                 throws ServletException, java.io.IOException {
3124
<         handleGetOrPost(req, res);
3125
<     }
3126
< 
3127
< 
3128
<     /**
3129
<      *  Handle "GET" or "POST" method requests from HTTP clients
3130
<      *
3131
<      *  @param  req   The request
3132
<      *  @param  res  The response
3133
<      *  @throws ServletException, java.io.IOException
3134
<      */
3135
<     private void handleGetOrPost(HttpServletRequest req,
3136
<                                  HttpServletResponse res)
3137
<                  throws ServletException, java.io.IOException {
3138
<         AuthSession authSession;
3139
<         String authSessionMessage;
3140
<         HttpSession httpSession;
3141
<         boolean isValid;
3142
<         String o = req.getParameter("o");
3143
<         String organization;
3144
<         String passwd = req.getParameter("passwd");
3145
<         PrintWriter out = res.getWriter();
3146
<         String uid = req.getParameter("uid");
3147
<         String user;
3148
< 
3149
<         if ((uid == null) || (uid.equals(""))) {
3150
<           out.println("Invalid login: no Username specified.");
3151
<           return;
3152
<         }
3153
<         else if ((o == null) || (o.equals(""))) {
3154
<           out.println("Invalid login: no Organization selected.");
3155
<           return;
3156
<         }
3157
<         else if ((passwd == null) || (passwd.equals(""))) {
3158
<           out.println("Invalid login: no Password specified.");
3159
<           return;
3160
<         }
3161
<         else {
3162
<           user = "uid=" + uid + ",o=" + o + LDAP_DOMAIN;
3163
<         }
3164
< 
3165
<         res.setContentType("text/plain");
3166
<         
3167
<         try {
3168
<           authSession = new AuthSession();
3169
<           isValid = authSession.authenticate(req, user, passwd);
3170
<           authSessionMessage = authSession.getMessage();
3171
<           System.out.println("authSession.authenticate(): "+authSessionMessage);
3172
<           out.println("authSession.authenticate(): " + authSessionMessage);
3173
< 
3174
<           if (isValid) {
3175
<             httpSession = req.getSession(true);
3176
<             httpSession.setAttribute("username", user);
3177
<             httpSession.setAttribute("password", passwd);
3178
<             res.sendRedirect("harvesterRegistration");
3179
<           }
3180
<           else {
3181
<             out.println("Invalid login");
3182
<           }
3183
<         } 
3184
<         catch (Exception e) {
3185
<           System.out.println("Error in AuthSession()" + e.getMessage());
3186
<         }
3187
<     }
3188
---
3189
> 	/**
3190
> 	 *  Handle "GET" method requests from HTTP clients
3191
> 	 *
3192
> 	 *  @param  req   The request
3193
> 	 *  @param  res   The response
3194
> 	 *  @throws ServletException, java.io.IOException
3195
> 	 */
3196
> 	public void doGet(HttpServletRequest req, HttpServletResponse res)
3197
> 				throws ServletException, java.io.IOException {
3198
> 		handleGetOrPost(req, res);
3199
> 	}
3200
> 
3201
> 
3202
> 	/**
3203
> 	 *  Handle "POST" method requests from HTTP clients
3204
> 	 *
3205
> 	 *  @param  req   The request
3206
> 	 *  @param  res  The response
3207
> 	 *  @throws ServletException, java.io.IOException
3208
> 	 */
3209
> 	public void doPost(HttpServletRequest req, HttpServletResponse res)
3210
> 				throws ServletException, java.io.IOException {
3211
> 		handleGetOrPost(req, res);
3212
> 	}
3213
> 
3214
> 
3215
> 	/**
3216
> 	 *  Handle "GET" or "POST" method requests from HTTP clients
3217
> 	 *
3218
> 	 *  @param  req   The request
3219
> 	 *  @param  res  The response
3220
> 	 *  @throws ServletException, java.io.IOException
3221
> 	 */
3222
> 	private void handleGetOrPost(HttpServletRequest req,
3223
> 								 HttpServletResponse res)
3224
> 				 throws ServletException, java.io.IOException {
3225
> 		AuthSession authSession;
3226
> 		String authSessionMessage;
3227
> 		HttpSession httpSession;
3228
> 		boolean isValid;
3229
> 		String o = req.getParameter("o");
3230
> 		String organization;
3231
> 		String passwd = req.getParameter("passwd");
3232
> 		PrintWriter out = res.getWriter();
3233
> 		String uid = req.getParameter("uid");
3234
> 		String user;
3235
> 
3236
> 		if ((uid == null) || (uid.equals(""))) {
3237
> 		  out.println("Invalid login: no Username specified.");
3238
> 		  return;
3239
> 		}
3240
> 		else if ((o == null) || (o.equals(""))) {
3241
> 		  out.println("Invalid login: no Organization selected.");
3242
> 		  return;
3243
> 		}
3244
> 		else if ((passwd == null) || (passwd.equals(""))) {
3245
> 		  out.println("Invalid login: no Password specified.");
3246
> 		  return;
3247
> 		}
3248
> 		else {
3249
> 		  user = "uid=" + uid + ",o=" + o + LDAP_DOMAIN;
3250
> 		}
3251
> 
3252
> 		res.setContentType("text/plain");
3253
> 
3254
> 		try {
3255
> 		  authSession = new AuthSession();
3256
> 		  AuthInfo auth = new AuthInfo(user, passwd);
3257
> 		  isValid = authSession.authenticate(req, auth);
3258
> 		  authSessionMessage = authSession.getMessage();
3259
> 		  System.out.println("authSession.authenticate(): "+authSessionMessage);
3260
> 		  out.println("authSession.authenticate(): " + authSessionMessage);
3261
> 
3262
> 		  if (isValid) {
3263
> 			httpSession = req.getSession(true);
3264
> 			httpSession.setAttribute("auth", auth);
3265
> 			res.sendRedirect("harvesterRegistration");
3266
> 		  }
3267
> 		  else {
3268
> 			out.println("Invalid login");
3269
> 		  }
3270
> 		}
3271
> 		catch (Exception e) {
3272
> 		  System.out.println("Error in AuthSession()" + e.getMessage());
3273
> 		}
3274
> 	}
3275
Index: src/edu/ucsb/nceas/metacat/harvesterClient/LoginServlet.java
3276
===================================================================
3277
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/harvesterClient/LoginServlet.java,v
3278
retrieving revision 1.6
3279
diff -r1.6 LoginServlet.java
3280
38a39
3281
> import edu.ucsb.nceas.metacat.AuthInfo;
3282
46,47c47,48
3283
<     // Close all connections
3284
<     System.out.println("Destroying LoginServlet");
3285
---
3286
> 	// Close all connections
3287
> 	System.out.println("Destroying LoginServlet");
3288
58,60c59,61
3289
<           throws ServletException, java.io.IOException {
3290
<     // Process the data and send back the response
3291
<     handleGetOrPost(request, response);
3292
---
3293
> 		  throws ServletException, java.io.IOException {
3294
> 	// Process the data and send back the response
3295
> 	handleGetOrPost(request, response);
3296
71,73c72,74
3297
<           throws ServletException, java.io.IOException {
3298
<     // Process the data and send back the response
3299
<     handleGetOrPost(request, response);
3300
---
3301
> 		  throws ServletException, java.io.IOException {
3302
> 	// Process the data and send back the response
3303
> 	handleGetOrPost(request, response);
3304
84,115c85,116
3305
<                                HttpServletResponse response)
3306
<           throws ServletException, java.io.IOException {
3307
<     AuthSession authSession = null;
3308
<     HttpSession httpSession;
3309
<     boolean isValid;
3310
<     PrintWriter out = response.getWriter();
3311
<     String passwd = request.getParameter("passwd");
3312
<     String user = request.getParameter("user");
3313
< 
3314
<     response.setContentType("text/plain");
3315
< 
3316
<     try {
3317
<       authSession = new AuthSession();
3318
<     } 
3319
<     catch (Exception e) {
3320
<       out.println("Error creating AuthSession: " + e.getMessage());
3321
<       return;
3322
<     }
3323
< 
3324
<     isValid = authSession.authenticate(request, user, passwd);
3325
<     
3326
<     if (isValid) {
3327
<       System.out.println(authSession.getMessage());
3328
<       httpSession = request.getSession(true);
3329
<       httpSession.setAttribute("username", user);
3330
<       httpSession.setAttribute("password", passwd);
3331
<       response.sendRedirect("../style/skins/dev/harvesterUpload.html");
3332
<     }
3333
<     else {
3334
<       out.println("Error authenticating Metacat login: " + 
3335
<                   authSession.getMessage());
3336
<     }
3337
---
3338
> 							   HttpServletResponse response)
3339
> 		  throws ServletException, java.io.IOException {
3340
> 	AuthSession authSession = null;
3341
> 	HttpSession httpSession;
3342
> 	boolean isValid;
3343
> 	PrintWriter out = response.getWriter();
3344
> 	String passwd = request.getParameter("passwd");
3345
> 	String user = request.getParameter("user");
3346
> 	AuthInfo auth = new AuthInfo(user, passwd);
3347
> 
3348
> 	response.setContentType("text/plain");
3349
> 
3350
> 	try {
3351
> 	  authSession = new AuthSession();
3352
> 	}
3353
> 	catch (Exception e) {
3354
> 	  out.println("Error creating AuthSession: " + e.getMessage());
3355
> 	  return;
3356
> 	}
3357
> 
3358
> 	isValid = authSession.authenticate(request, auth);
3359
> 
3360
> 	if (isValid) {
3361
> 	  System.out.println(authSession.getMessage());
3362
> 	  httpSession = request.getSession(true);
3363
> 	  httpSession.setAttribute("auth", auth);
3364
> 	  response.sendRedirect("../style/skins/dev/harvesterUpload.html");
3365
> 	}
3366
> 	else {
3367
> 	  out.println("Error authenticating Metacat login: " +
3368
> 				  authSession.getMessage());
3369
> 	}
3370
Index: src/edu/ucsb/nceas/metacat/harvesterClient/MetUpload.java
3371
===================================================================
3372
RCS file: /cvs/metacat/src/edu/ucsb/nceas/metacat/harvesterClient/MetUpload.java,v
3373
retrieving revision 1.8
3374
diff -r1.8 MetUpload.java
3375
44a45
3376
> import edu.ucsb.nceas.metacat.AuthInfo;
3377
84c85
3378
<     String          password = (String) sess.getAttribute("password");
3379
---
3380
> 	AuthInfo        auth = (AuthInfo) sess.getAttribute("auth");
3381
87,88c88
3382
<     String          username = (String) sess.getAttribute("username");
3383
<     
3384
---
3385
> 
3386
124c124
3387
<       upload(out, docid, sr, username, password);
3388
---
3389
>       upload(out, docid, sr, auth);
3390
127c127
3391
<       delete(out, docid, username, password);
3392
---
3393
>       delete(out, docid, auth);
3394
137,138c137
3395
<    * @param username   the Metacat username
3396
<    * @param password   the Metacat password
3397
---
3398
>    * @param auth       the Metacat username and password
3399
142,143c141
3400
<                       String username,
3401
<                       String password
3402
---
3403
> 					  AuthInfo auth
3404
155c153
3405
<       metacat.login(username, password);
3406
---
3407
>       metacat.login(auth.getUsername(), auth.getPassword());
3408
220,221c218
3409
<    * @param username   the Metacat username
3410
<    * @param password   the Metacat password
3411
---
3412
>    * @param auth       the Metacat username and password
3413
226,227c223
3414
<                       String username,
3415
<                       String password
3416
---
3417
> 					  AuthInfo auth
3418
247c243
3419
<       metacat.login(username, password);
3420
---
3421
>       metacat.login(auth.getUsername(), auth.getPassword());
(3-3/5)