KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > webdav > cmd > Client


1 /*
2  * $Header: /home/cvs/jakarta-slide/webdavclient/commandline/src/java/org/apache/webdav/cmd/Client.java,v 1.21.2.2 2004/10/02 17:39:11 luetzkendorf Exp $
3  * $Revision: 1.21.2.2 $
4  * $Date: 2004/10/02 17:39:11 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2002 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23
24 package org.apache.webdav.cmd;
25
26 import antlr.RecognitionException;
27 import antlr.TokenStreamException;
28 import java.io.BufferedReader;
29 import java.io.DataInputStream;
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.PrintStream;
37 import java.text.SimpleDateFormat;
38 import java.util.Date;
39 import java.util.Enumeration;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
42 import org.apache.commons.httpclient.HttpException;
43 import org.apache.commons.httpclient.HttpStatus;
44 import org.apache.commons.httpclient.HttpURL;
45 import org.apache.commons.httpclient.HttpsURL;
46 import org.apache.commons.httpclient.URIException;
47 import org.apache.commons.httpclient.util.URIUtil;
48 import org.apache.webdav.lib.Ace;
49 import org.apache.webdav.lib.Lock;
50 import org.apache.webdav.lib.Privilege;
51 import org.apache.webdav.lib.Property;
52 import org.apache.webdav.lib.PropertyName;
53 import org.apache.webdav.lib.ResponseEntity;
54 import org.apache.webdav.lib.WebdavResource;
55 import org.apache.webdav.lib.methods.DepthSupport;
56 import org.apache.webdav.lib.methods.LockMethod;
57 import org.apache.webdav.lib.properties.AclProperty;
58 import org.apache.webdav.lib.properties.LockDiscoveryProperty;
59 import org.apache.webdav.lib.properties.PrincipalCollectionSetProperty;
60 import org.apache.webdav.lib.properties.ResourceTypeProperty;
61 import org.apache.webdav.lib.util.QName;
62
63
64 /**
65  * The Slide client, the command line version for WebDAV client.
66  *
67  */

68 final class Client {
69
70
71     private Spool spool;
72     private InputStream in;
73     private PrintStream out;
74     private boolean displayPrompt = true;
75
76     /** The path for the display information. */
77     private String path = "";
78
79     /** The command prompt for the display information. */
80     private String commandPrompt = null;
81
82     /** The http URL on the client connection. */
83     private HttpURL httpURL;
84
85     /** The debug level. */
86     private int debugLevel = DEBUG_OFF;
87
88     /** The WebDAV resource. */
89     private WebdavResource webdavResource = null;
90
91     /** The current path on the local system. */
92     private File dir = new File(".");
93
94     /////////////////////////////////////////////////////////////////
95

96     Client(InputStream in, PrintStream out)
97     {
98         this.spool = new Spool(in,out);
99         this.in = in;
100         this.out = new PrintStream(spool.getOutputStream());
101         updatePrompt(getPath());
102     }
103
104     void run()
105     {
106        while(true) {
107           try {
108              InputStream in=spool.getInputStream();
109              ClientLexer lexer = new ClientLexer(new DataInputStream(in));
110              ClientParser parser = new ClientParser(lexer);
111              parser.setClient(this);
112              parser.commands();
113           }
114           catch(TokenStreamException ex) {
115              handleException(ex);
116           }
117           catch(RecognitionException ex) {
118              handleException(ex);
119           }
120        }
121        // TODO test EOF ???
122
}
123
124     ///////////////////////////////////////////////////////////////////
125
// Helper funtions for the parser and error handlers
126
///////////////////////////////////////////////////////////////////
127

128     void printInvalidCommand(String command)
129     {
130         out.println("Error: invalid command: " + command);
131     }
132
133     void printUsage(String command)
134     {
135         out.println("Syntax error. \"help\" for more info");
136 // out.println("Usage: " + command + " ...");
137
// out.println
138
// ("[Help] open " +
139
// "http://hostname[:port][/path]");
140
// out.println("Syntax: grant <namespace> <permission> on <path> to <principal>");
141
// out.println("Syntax: revoke <namespace> <permission> on <path> from <principal>");
142
// out.println("Syntax: deny <namespace> <permission> on <path> to <principal>");
143
// out.println("Syntax: lock <path>");
144
// out.println("Syntax: unlock <path>");
145
// out.println("Syntax: vc/VersionControl <path>");
146
// else out.println("Syntax: eReport path");
147
// else out.println("Syntax: lReport <property> \n History URLs are needed");
148

149     }
150
151     void prompt()
152     {
153         if (displayPrompt)
154             out.print(getPrompt());
155     }
156
157    void print(String line) {
158       out.println(line);
159    }
160
161     private void handleException(Exception ex)
162     {
163         if (ex instanceof HttpException) {
164             if (((HttpException) ex).getReasonCode() == HttpStatus.SC_METHOD_NOT_ALLOWED) {
165                 out.println("Warning: Not WebDAV-enabled?");
166             }
167             else if (((HttpException) ex).getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
168                 out.println("Warning: Unauthorized");
169             }
170             else {
171                 out.println("Warning: " + ex.getMessage());
172             }
173         }
174         else if (ex instanceof IOException) {
175             out.println("Error: " + ex.getMessage());
176         }
177         else {
178             out.println("Fatal Error: " + ex.getMessage());
179             ex.printStackTrace(out);
180             out.println("Please, email to slide-user@jakarta.apache.org");
181             System.exit(-1);
182         }
183     }
184
185     /////////////////////////////////////////////////////////////////
186
// Commands available on the command line
187
/////////////////////////////////////////////////////////////////
188

189     void setEchoEnabled(boolean isEnabled)
190     {
191         spool.setEcho(isEnabled);
192         setDisplayPrompt(isEnabled);
193
194         // if this is an interactive client keep the prompt
195
if (this.in==System.in)
196             setDisplayPrompt(true);
197     }
198
199     void executeScript(String scriptname)
200     {
201         try {
202             FileInputStream script = new FileInputStream(scriptname);
203             Client scriptClient = new Client(script,out);
204             scriptClient.setDisplayPrompt(false);
205             out.println("Executing script: " + scriptname);
206             scriptClient.run();
207             out.println("Script " + scriptname + " complete.");
208             script.close();
209         }
210         catch (FileNotFoundException ex) {
211             out.println("Error: Script " + scriptname + " not found.");
212         }
213         catch (IOException ex) {
214             out.println("Error: " + ex.toString() + " during execution of " + scriptname);
215         }
216     }
217
218     void enableSpoolToFile(String filename)
219     {
220         out.println("Spool to file: " + filename);
221         try {
222             spool.enable(filename);
223         }
224         catch (FileNotFoundException ex) {
225             out.println("Error: Could not spool to file: " + filename);
226             disableSpoolToFile();
227         }
228     }
229
230     void disableSpoolToFile()
231     {
232         spool.disable();
233         out.println("Spooling disabled");
234     }
235
236
237     /** Debug level for all debug messages */
238     final static int DEBUG_ON = Integer.MAX_VALUE;
239
240     /** Debug level for no debug messages */
241     final static int DEBUG_OFF = 0;
242
243     /**
244      * Set the debug level
245      */

246     void setDebug(int level)
247     {
248         this.debugLevel=level;
249         if (webdavResource != null) webdavResource.setDebug(debugLevel);
250
251         switch (level) {
252             case DEBUG_ON: out.println("The debug flag is on."); break;
253             case DEBUG_OFF: out.println("The debug flag is off."); break;
254             default: out.println("The debug level is " + level); break;
255         }
256     }
257
258     void connect(String uri)
259     {
260                 
261         if (!uri.endsWith("/") && !uri.endsWith("\\")) {
262             // append / to the path
263
uri+="/";
264         }
265
266         out.println("connect " + uri);
267
268         try {
269             // Set up for processing WebDAV resources
270
httpURL = uriToHttpURL(uri);
271             if (webdavResource == null) {
272                 webdavResource = new WebdavResource(httpURL);
273                 webdavResource.setDebug(debugLevel);
274                 
275                 // is not a collection?
276
if (!((ResourceTypeProperty)webdavResource.getResourceType()).isCollection()) {
277                     webdavResource = null;
278                     httpURL = null;
279                     out.println("Error: " + uri + " is not a collection! Use open/connect only for collections!");
280                 }
281                 
282             } else {
283                 webdavResource.close();
284                 webdavResource.setHttpURL(httpURL);
285             }
286             setPath(webdavResource.getPath());
287         }
288         catch (HttpException we) {
289             out.print("HttpException.getReasonCode(): "+ we.getReasonCode());
290             if (we.getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
291                 try {
292                     out.print("UserName: ");
293                     BufferedReader in =
294                         new BufferedReader(new InputStreamReader(System.in));
295                     String userName = in.readLine();
296                     if ((userName==null) || (userName.length()==0)) {
297                         disconnect();
298                         return;
299                     }
300                     userName = userName.trim();
301                     System.out.print("Password: ");
302                     String password = in.readLine();
303                     if (password != null)
304                         password= password.trim();
305                     try {
306                         if (webdavResource != null)
307                             webdavResource.close();
308                     } catch (IOException e) {
309                     } finally {
310                         httpURL = null;
311                         webdavResource = null;
312                     }
313                     httpURL = uriToHttpURL(uri);
314                     // It should be used like this way.
315
httpURL.setUserinfo(userName, password);
316                     webdavResource = new WebdavResource(httpURL);
317                     webdavResource.setDebug(debugLevel);
318                     setPath(webdavResource.getPath());
319
320
321                     if (!((ResourceTypeProperty)webdavResource.getResourceType()).isCollection()) {
322                         webdavResource = null;
323                         httpURL = null;
324                         out.println("Error: " + uri + " is not a collection! Use open/connect only for collections!");
325                     }
326                 }
327                 catch (Exception ex) {
328                     handleException(ex);
329                     httpURL = null;
330                     webdavResource = null;
331                 }
332             }
333             else {
334                 handleException(we);
335                 httpURL = null;
336                 webdavResource = null;
337             }
338         }
339         catch (Exception ex) {
340             handleException(ex);
341             webdavResource = null;
342             httpURL = null;
343         }
344         updatePrompt(getPath());
345     }
346
347     void disconnect()
348     {
349         out.println("disconnect");
350         try {
351             webdavResource.close();
352         } catch (IOException e) {
353         } finally {
354             // Make sure the connection closed.
355
httpURL = null;
356             webdavResource = null;
357         }
358         updatePrompt(getPath());
359     }
360
361     void options(String path)
362     {
363         out.println("options " + path);
364
365         String param = path;
366         try {
367             boolean succeeded = false;
368             if (param != null) {
369                 if (!param.startsWith("/")) {
370                     httpURL = uriToHttpURL(param);
371                     Enumeration enum = null;
372                     try {
373                         // OPTIONS business logic
374
enum =
375                             webdavResource.optionsMethod(httpURL);
376                         while (enum.hasMoreElements()) {
377                             out.print(enum.nextElement());
378                             if (enum.hasMoreElements()) {
379                                 out.print(", ");
380                             } else {
381                                 out.println();
382                             }
383                         }
384                     } catch (HttpException we) {
385                         if (we.getReasonCode() ==
386                             HttpStatus.SC_UNAUTHORIZED) {
387                             BufferedReader in =
388                                 new BufferedReader(new InputStreamReader(System.in));
389                             out.print("UserName: ");
390                             String userName = in.readLine();
391                             if (userName != null &&
392                                 userName.length() > 0) {
393                                 userName = userName.trim();
394                                 out.print("Password: ");
395                                 String password = in.readLine();
396                                 if (password != null)
397                                     password= password.trim();
398                                 try {
399                                     // OPTIONS business logic
400
httpURL.setUserinfo(userName,
401                                         password);
402                                     enum = webdavResource.
403                                         optionsMethod(httpURL);
404                                     while (
405                                         enum.hasMoreElements()) {
406                                         out.print
407                                             (enum.nextElement());
408                                         if (enum.
409                                             hasMoreElements()) {
410                                             out.print
411                                                 (", ");
412                                         } else {
413                                             out.println();
414                                         }
415                                     }
416                                 } catch (Exception e) {
417                                     out.println("Error: "
418                                         + e.getMessage());
419                                 }
420                             }
421                         } else {
422                             out.println("Error: " +
423                                     we.getMessage());
424                         }
425                     } catch (IOException e) {
426                         out.println(
427                             "Error: Check! " + e.getMessage());
428                     }
429                     httpURL = null;
430                     return;
431                 } else
432                 if (webdavResource != null) {
433                     succeeded =
434                         webdavResource.optionsMethod(param);
435                 } else {
436                     out.println("Not connected yet.");
437                 }
438             } else
439             if (webdavResource != null) {
440                 succeeded = webdavResource.optionsMethod("*");
441             } else {
442                 out.println("Not connected yet.");
443             }
444
445             if (succeeded) {
446                 out.print
447                     ("Allowed methods by http OPTIONS: ");
448                 Enumeration allowed =
449                     webdavResource.getAllowedMethods();
450                 while (allowed.hasMoreElements()) {
451                     out.print(allowed.nextElement());
452                     if (allowed.hasMoreElements())
453                         out.print(", ");
454                  }
455                 Enumeration davCapabilities =
456                     webdavResource.getDavCapabilities();
457                 if (davCapabilities.hasMoreElements())
458                     out.print("\nDAV: ");
459                 while (davCapabilities.hasMoreElements()) {
460                     out.print
461                         (davCapabilities.nextElement());
462                     if (davCapabilities.hasMoreElements())
463                         out.print(", ");
464                 }
465                 out.println();
466             }
467         }
468         catch (Exception ex) {
469             handleException(ex);
470         }
471     }
472
473     void help(String topic)
474     {
475         if (topic==null) {
476             printSlideClientUsage();
477         }
478         else {
479             out.println("No help available on " + topic);
480         }
481     }
482
483     void lpwd()
484     {
485         try {
486             out.println(dir.getCanonicalPath());
487         }
488         catch (IOException ex) {
489             out.println("Warning: Not found the path");
490         }
491     }
492     
493     private File getFileByPath(String path) {
494         
495         if (path != null) {
496              // set a new file if '\' or '/' at the begin of path
497
// or ':' at the 2nd position of path exists.
498
// if not: take the old parent entry of file and add a '/' to path.
499
return(path.startsWith("/") ||
500                     path.startsWith("\\") ||
501                   ((path.length() > 1) && (path.charAt(1) == ':')) ) ?
502                     new File(path) :
503                     new File(dir, "/"+path);
504          } else {
505              return dir;
506          }
507   
508     }
509
510
511     void lcd(String path)
512     {
513         File anotherDir = getFileByPath(path);
514                    
515         if (anotherDir.isDirectory()) {
516             dir = anotherDir;
517         } else {
518             out.println("Warning: path not found!");
519         }
520         
521         updatePrompt(getPath());
522
523     }
524     
525    
526
527     void lls(String options, String path)
528     {
529         // set default option.
530
char option = 'F';
531         if ((options!=null) && (options.indexOf('l') > 0))
532             option = 'l';
533     
534         File temp = getFileByPath(path);
535         
536
537        if (!temp.exists() || !temp.isDirectory()) {
538            out.println("Warning: path not found!");
539            return;
540         }
541
542         String[] list = temp.list();
543         // TODO: consider of options like '-a' for all and so on.
544
switch (option) {
545         case 'l':
546             for (int i = 0; i < list.length; i++) {
547                 String s = list[i];
548                 File file = new File(temp, s);
549                 for (int j = 0; j < 4; j++) {
550                     switch (j) {
551                         case 0:
552                             // Print the filename.
553
out.print(s);
554                             for (int k = list[i].length();
555                                 k < 35; k++)
556                                 out.print(" ");
557                             break;
558                         case 1:
559                             s = Long.toString(file.length());
560                             for (int k = 10 - s.length();
561                                 k > 0 ; k--)
562                                 out.print(" ");
563                             // don't cut the size.
564
out.print(s + " ");
565                             break;
566                         case 2:
567                             // cut the description.
568
s = file.isDirectory() ?
569                                 "DIR" : "";
570                             out.print(" " +
571                                 ((s.length() > 5) ?
572                                 s.substring(0, 5) : s));
573                             for (int k = s.length(); k < 5; k++)
574                                 out.print(" ");
575                             break;
576                         case 3:
577                             s = new SimpleDateFormat().format(
578                                 new Date(file.lastModified()));
579                             out.print(" " + s);
580                         default:
581                     }
582                 }
583                 // Start with a new line.
584
out.println();
585             }
586             break;
587         case 'F':
588             int i = 0;
589             for (; i < list.length; i++) {
590                 out.print(list[i] + " ");
591                 for (int j = list[i].length();
592                     j < 25; j++) {
593                     out.print(" ");
594                 }
595                 if (i % 3 == 2)
596                    out.println();
597             }
598             if (list.length > 0 && i % 3 != 0) {
599                 out.println();
600             }
601             break;
602         default:
603         } // end of switch
604

605     }
606
607     void pwc()
608     {
609         out.println(getPath());
610     }
611
612     void cd(String path)
613     {
614         String currentPath = webdavResource.getPath();
615         
616         try {
617             String cdPath = checkUri(path + "/");
618             webdavResource.setPath(cdPath);
619             
620             if (webdavResource.exists()) {
621                 if (webdavResource.isCollection()) {
622                     setPath(webdavResource.getPath());
623                 } else {
624                     out.println("Warning: Not a collection");
625                     webdavResource.setPath(currentPath);
626                 }
627             } else {
628                 out.println("Warning: Not found the path");
629                 webdavResource.setPath(currentPath);
630             }
631         }
632         catch (Exception ex) {
633             handleException(ex);
634             try {
635                 webdavResource.setPath(currentPath);
636             } catch (Exception e) {
637                 handleException(e);
638             }
639
640         }
641
642         updatePrompt(getPath());
643     }
644
645     void ls(String options, String path)
646     {
647         // set default option.
648
char option = 'F';
649         if ((options!=null) && (options.indexOf('l') > 0))
650             option = 'l';
651
652         try {
653             // Check that the path is ok.
654
if (path != null) {
655                 path = checkUri(path + "/");
656                 webdavResource.setPath(path);
657             } else {
658                 path = checkUri("./");
659                 webdavResource.setPath(path);
660             }
661             switch (option) {
662                 
663             case 'l':
664
665                 Vector basiclist = webdavResource.listBasic();
666                 for (int i = 0; i < basiclist.size(); i++) {
667                     String[] longFormat =
668                         (String []) basiclist.elementAt(i);
669                         
670                         // name -> position 4
671
String s = longFormat[4];
672                         int len = s.length();
673                         out.print(s);
674                         for (int k = len; k < 20; k++)
675                             out.print(" ");
676                         
677
678                         // size -> position 1
679
s = longFormat[1];
680                         len = s.length();
681                         for (int k = 10 - len;
682                             k > 0 ; k--)
683                             out.print(" ");
684                         // don't cut the size.
685
out.print(s + " ");
686                                 
687                                 
688                         // description -> position 2
689
// cut the description.
690
s = longFormat[2];
691                         len = s.length();
692
693                         out.print(" " +
694                             ((len > 20) ?
695                             s.substring(0, 20) : s));
696                         for (int k = len; k < 20; k++)
697                             out.print(" ");
698                             
699                         // date -> position 3
700
s = longFormat[3];
701                         len = s.length();
702                         out.println(" " + s);
703                     }
704                     
705                     
706                 
707                 break;
708                 
709                 
710             case 'F':
711                 String[] list = webdavResource.list();
712                 if (list != null) {
713                     int i = 0;
714                     for (; i < list.length; i++) {
715                         out.print(list[i] + " ");
716                         for (int j = list[i].length(); j < 25; j++) {
717                             out.print(" ");
718                         }
719                         if (i % 3 == 2)
720                            out.println();
721                     }
722                     if (list.length > 0 && i % 3 != 0)
723                         out.println();
724                 }
725                 break;
726             default:
727             } // end of switch
728
}
729         catch (Exception ex) {
730             handleException(ex);
731         }
732     }
733
734     void propfind(String path, Vector properties)
735     {
736         try {
737             path = checkUri(path);
738             out.print("Getting properties '" + path + "': ");
739
740             Enumeration propertyValues =
741                 webdavResource.propfindMethod(path, properties);
742             if (propertyValues.hasMoreElements()){
743                 while (propertyValues.hasMoreElements()){
744                     out.println(propertyValues.nextElement());
745                 }
746             }
747             else {
748                 out.println("failed.");
749                 out.println(webdavResource.getStatusMessage());
750             }
751         }
752         catch (Exception ex) {
753             handleException(ex);
754         }
755     }
756
757     void status()
758     {
759       out.println(webdavResource.getStatusMessage());
760     }
761
762     void propfindall(String path)
763     {
764         try {
765             path=checkUri(path);
766             out.print("Getting properties '" + path + "': ");
767             Enumeration responses = webdavResource.propfindMethod(path, DepthSupport.DEPTH_0);
768             if (!responses.hasMoreElements()) {
769                 out.println("failed (no response received).");
770                 out.println(webdavResource.getStatusMessage());
771                 return;
772             }
773             else {
774                 out.println();
775             }
776             ResponseEntity response = (ResponseEntity) responses.nextElement();
777             Enumeration properties = response.getProperties();
778             while (properties.hasMoreElements()){
779                 Property property = (Property)properties.nextElement();
780                 out.println(" " + property.getName() + " : " + property.getPropertyAsString());
781             }
782         }
783         catch (Exception ex) {
784             handleException(ex);
785         }
786     }
787
788     void proppatch(String path, String prop, String value)
789     {
790         String name=prop;
791         try {
792             path=checkUri(path);
793             out.print("Putting property(" + name + ", " + value +
794                 ") to '" + path + "': ");
795             if (webdavResource.proppatchMethod(
796                 path, new PropertyName("DAV:",name), value, true)) {
797                 out.println("succeeded.");
798             } else {
799                 out.println("failed.");
800                 out.println(webdavResource.getStatusMessage());
801             }
802         }
803         catch (Exception ex) {
804             handleException(ex);
805         }
806     }
807     
808     String getLocalTragetFileName(String path, String filename) {
809         
810         String srcFileName = null;
811         String tarFileName = null;
812  
813
814         // get traget filename from last portion of path
815
StringTokenizer st = new StringTokenizer(path, "/\\");
816         while (st.hasMoreTokens()) {
817             srcFileName = st.nextToken();
818         }
819                 
820         File targetFile = getFileByPath((filename != null) ? filename : srcFileName);
821         
822         try {
823             if (targetFile.isDirectory()) {
824                 tarFileName = targetFile.getCanonicalPath() + "/"+ srcFileName;
825             } else {
826                 tarFileName = targetFile.getCanonicalPath();
827             }
828         } catch (IOException e) {
829             System.err.println(e.toString());
830             return null;
831         }
832
833         return tarFileName;
834     }
835
836     void get(String path, String filename)
837     {
838         
839         filename = getLocalTragetFileName( path, filename);
840         
841         try {
842             // The resource on the remote.
843
String src = checkUri(path);
844             // The file on the local.
845
String dest = (filename!=null)
846                 ? filename
847                 : URIUtil.getName(src.endsWith("/")
848                                   ? src.substring(0, src.length() - 1)
849                                   : src);
850
851             out.println("get " + src + " " + dest);
852
853             // For the overwrite operation;
854
String y = "y";
855             File file = new File(dest);
856             // Checking the local file.
857
if (file.exists()) {
858
859                 // FIXME: interactive ?
860
out.print("Aleady exists. " +
861                     "Do you want to overwrite it(y/n)? ");
862                 BufferedReader in =
863                     new BufferedReader(new InputStreamReader(System.in));
864                 y = in.readLine();
865             }
866             if (y.trim().equalsIgnoreCase("y") ||
867                 (y != null && y.length() == 0)) {
868                 out.print("Downloading '" + src +
869                     "' to '" + dest + "': ");
870                 if (webdavResource.getMethod(src, file)) {
871                     out.println("succeeded.");
872                 } else {
873                     out.println("failed.");
874                     out.println(webdavResource.getStatusMessage());
875                 }
876             }
877         }
878         catch (Exception ex) {
879             handleException(ex);
880         }
881     }
882     
883     String getRemoteTragetFileName(String filename, String path) {
884         
885         String srcPathName = null;
886         String target = null;
887        
888  
889
890         // get traget filename from last portion of filename
891
StringTokenizer st = new StringTokenizer(filename, "/\\");
892         while (st.hasMoreTokens()) {
893             srcPathName = st.nextToken();
894         }
895         
896         
897         try {
898                 
899             if (path != null) {
900                 target = checkUri(path);
901                 
902                 // check is path a collection ?
903
String currentPath = webdavResource.getPath();
904                 
905                 webdavResource.setPath(target);
906                 
907                 if (webdavResource.exists()) {
908                     if (webdavResource.isCollection()) {
909                         target += "/" + srcPathName;
910                     }
911                 }
912                 
913                 webdavResource.setPath(currentPath);
914                 
915             } else {
916                 target = checkUri(getPath() + "/" + srcPathName);
917             }
918                 
919                             
920         } catch (Exception ex) {
921         }
922         
923         return target;
924                
925
926     }
927     
928     
929
930
931     void put(String filename, String path)
932     {
933         String y = "y";
934
935         try {
936             String src = filename;
937             String dest = getRemoteTragetFileName( filename, path);
938             
939             String currentPath = webdavResource.getPath();
940             
941             try {
942                 webdavResource.setPath(dest);
943                 if (webdavResource.exists()) {
944                     out.print("Aleady exists. " +
945                               "Do you want to overwrite it(y/n)? ");
946                     BufferedReader in =
947                           new BufferedReader(new InputStreamReader(System.in));
948                     y = in.readLine();
949                 }
950                 webdavResource.setPath(currentPath);
951             } catch (Exception ex) {
952             }
953             
954             if (y.trim().equalsIgnoreCase("y") ||
955                   (y != null && y.length() == 0)) {
956  
957             
958                 File file = getFileByPath(src);
959                 
960                 if (file.exists()) {
961                     out.print("Uploading '" + file.getCanonicalPath() + "' to '" + dest + "' ");
962                     
963                     if (webdavResource.putMethod(dest, file)) {
964                         out.println("succeeded.");
965                     }
966                     else {
967                         out.println("failed.");
968                         out.println(webdavResource.getStatusMessage());
969                     }
970                 }
971                 else {
972                     out.println("Warning: File not exists");
973                 }
974             }
975         }
976         catch (Exception ex) {
977             handleException(ex);
978         }
979     }
980
981     // TODO multi
982
void delete(String path)
983     {
984         try {
985             path = checkUri(path);
986             out.print("Deleting '" + path + "': ");
987             if (webdavResource.deleteMethod(path)) {
988                 out.println("succeeded.");
989             } else {
990                 out.println("failed.");
991                 out.println(webdavResource.getStatusMessage());
992             }
993         }
994         catch (Exception ex) {
995             handleException(ex);
996         }
997     }
998
999     // TODO multi
1000
void mkcol(String path)
1001    {
1002        try {
1003            path = checkUri(path);
1004            out.print("Making '" + path + "' collection: ");
1005            if (webdavResource.mkcolMethod(path)) {
1006                out.println("succeeded.");
1007            } else {
1008                out.println("failed.");
1009                out.println(webdavResource.getStatusMessage());
1010            }
1011        }
1012        catch (Exception ex) {
1013            handleException(ex);
1014        }
1015    }
1016
1017    void copy(String src, String dst)
1018    {
1019        try {
1020            src = checkUri(src);
1021            dst = checkUri(dst);
1022            out.print("Copying '" + src + "' to '" + dst + "': ");
1023            if (webdavResource.copyMethod(src, dst)) {
1024                out.println("succeeded.");
1025            } else {
1026                out.println("failed.");
1027                out.println(webdavResource.getStatusMessage());
1028            }
1029        }
1030        catch (Exception ex) {
1031            handleException(ex);
1032        }
1033    }
1034
1035    void move(String src, String dst)
1036    {
1037        try {
1038            src = checkUri(src);
1039            dst = checkUri(dst);
1040            out.print("Moving '" + src + "' to '" + dst + "': ");
1041            if (webdavResource.moveMethod(src, dst)) {
1042                out.println("succeeded.");
1043            } else {
1044                out.println("failed.");
1045                out.println(webdavResource.getStatusMessage());
1046            }
1047        }
1048        catch (Exception ex) {
1049            handleException(ex);
1050        }
1051    }
1052
1053    void locks(String path)
1054    {
1055        try {
1056            path=checkUri(path);
1057            LockDiscoveryProperty lockDiscoveryProperty=webdavResource.lockDiscoveryPropertyFindMethod(path);
1058            if (lockDiscoveryProperty==null) {
1059                out.println("Server did not return a LockDiscoveryProperty.");
1060                out.println(webdavResource.getStatusMessage());
1061                return;
1062            }
1063            Lock[] locks=lockDiscoveryProperty.getActiveLocks();
1064            showLocks(path,locks);
1065        }
1066        catch (Exception ex) {
1067            handleException(ex);
1068        }
1069    }
1070
1071    void lock(String path, String timeout, String scope, String owner)
1072    {
1073       try {
1074            // Test the parameter
1075
//
1076
// Timeout
1077
int to=0;
1078            if ((timeout != null) && (timeout.toLowerCase().substring(0,5).equals("-tinf")) ) { //infinite
1079
to = LockMethod.TIMEOUT_INFINITY;
1080            } else {
1081                to = (timeout == null)? 120 : Integer.parseInt(timeout.substring(2));
1082            }
1083            
1084            
1085            // scope
1086
short scopeType = ((scope != null) && (scope.substring(2).toLowerCase().equals("shared")) ) ?
1087                LockMethod.SCOPE_SHARED : LockMethod.SCOPE_EXCLUSIVE;
1088           
1089            // owner
1090
owner = (owner != null) ? (owner.substring(2)) : owner;
1091 
1092            path = checkUri(path);
1093            out.print("Locking '" + path + "' ");
1094            out.print( (owner != null) ? "owner:'"+ owner + "' " : "");
1095            out.print("scope:" +scopeType+" timeout:"+to+ " :");
1096            if (webdavResource.lockMethod(path, owner, to, scopeType)) {
1097                out.println("succeeded.");
1098            } else {
1099                out.println("failed.");
1100                out.println(webdavResource.getStatusMessage());
1101            }
1102        }
1103        catch (Exception ex) {
1104            handleException(ex);
1105        }
1106    }
1107
1108    
1109    void unlock(String path, String owner)
1110    {
1111        try {
1112            // Test the parameter
1113
//
1114
// owner
1115
owner = (owner != null) ? (owner.substring(2)) : owner;
1116            
1117            path = checkUri(path);
1118            out.print("Unlocking '" + path + "'");
1119            out.print((owner!=null)? (" owner:"+owner+": ") : (": "));
1120            if (webdavResource.unlockMethod(path, owner)) {
1121                out.println("succeeded.");
1122            } else {
1123                out.println("failed.");
1124                out.println(webdavResource.getStatusMessage());
1125            }
1126        }
1127        catch (Exception ex) {
1128            handleException(ex);
1129        }
1130    }
1131
1132
1133    void grant(String permission,String path, String principal)
1134    {
1135        grant(new QName("DAV:",permission),path,principal);
1136
1137        // FIME lookup permission ?
1138
// if (namespace==null) {
1139
// namespace=resolveNamespace(permission);
1140
// if (namespace==null) {
1141
// out.println("Could not resolve namespace for permission " + permission);
1142
// continue;
1143
// }
1144
// }
1145
}
1146
1147    void grant(QName permission,String path, String principal)
1148    {
1149        try {
1150            principal=checkPrincipal(principal,webdavResource,path);
1151            grant(webdavResource, permission, path, principal);
1152        }
1153        catch (Exception ex) {
1154            handleException(ex);
1155        }
1156    }
1157
1158    void deny(String permission,String path, String principal)
1159    {
1160        deny(new QName("DAV:",permission),path,principal);
1161    }
1162
1163    void deny(QName permission,String path, String principal)
1164    {
1165        try {
1166            principal=checkPrincipal(principal,webdavResource,path);
1167            deny(webdavResource, permission, path, principal);
1168        }
1169        catch (Exception ex) {
1170            handleException(ex);
1171        }
1172    }
1173
1174    void revoke(String permission,String path, String principal)
1175    {
1176        revoke(new QName("DAV:",permission),path,principal);
1177    }
1178
1179    void revoke(QName permission,String path, String principal)
1180    {
1181        try {
1182            principal=checkPrincipal(principal,webdavResource,path);
1183            revoke(webdavResource, permission, path, principal);
1184        }
1185        catch (Exception ex) {
1186            handleException(ex);
1187        }
1188    }
1189
1190    void acl(String path)
1191    {
1192        try
1193        {
1194            AclProperty acl=null;
1195            if (path!=null) {
1196                path=checkUri(path);
1197            }
1198            else {
1199                path=webdavResource.getPath();
1200            }
1201            acl = webdavResource.aclfindMethod(path);
1202
1203            if (acl==null)
1204            {
1205                out.println("Error: PropFind didn't return an AclProperty!");
1206                return;
1207            }
1208            out.println();
1209            showAces(path, acl.getAces());
1210        }
1211        catch (Exception ex)
1212        {
1213            handleException(ex);
1214        }
1215    }
1216
1217    void principalcollectionset(String path)
1218    {
1219        try
1220        {
1221            PrincipalCollectionSetProperty set=null;
1222            if (path!=null) {
1223                path=checkUri(path);
1224            }
1225            else {
1226                path=webdavResource.getPath();
1227            }
1228            set = webdavResource.principalCollectionSetFindMethod(path);
1229
1230            if (set==null)
1231            {
1232                out.println("Error: PropFind didn't return an PrincipalCollectionSetProperty!");
1233                return;
1234            }
1235            String[] hrefs=set.getHrefs();
1236            if (hrefs==null) {
1237                out.println("No PrincipalCollectionSet for " + path);
1238            }
1239            out.println();
1240            out.println("PrincipalCollectionSet for " + path + ":");
1241            for (int i=0 ; i<hrefs.length ; i++)
1242                out.println(" " + hrefs[i]);
1243            out.println();
1244        }
1245        catch (Exception ex)
1246        {
1247        }
1248    }
1249
1250    ///////////////////////////////////////////////////////////////////
1251

1252    void checkin(String path)
1253    {
1254        try {
1255            path = checkUri(path);
1256            out.print("checking in '" + path + "': ");
1257            if (webdavResource.checkinMethod(path)) {
1258                out.println("succeeded.");
1259            } else {
1260                out.println("failed.");
1261                out.println(webdavResource.getStatusMessage());
1262            }
1263        }
1264        catch (Exception ex) {
1265            handleException(ex);
1266        }
1267    }
1268
1269    void checkout(String path)
1270    {
1271        try {
1272            path = checkUri(path);
1273            out.print("checking out '" + path + "': ");
1274            if (webdavResource.checkoutMethod(path)) {
1275                out.println("succeeded.");
1276            } else {
1277                out.println("failed.");
1278                out.println(webdavResource.getStatusMessage());
1279            }
1280        }
1281        catch (Exception ex) {
1282            handleException(ex);
1283        }
1284    }
1285
1286    void uncheckout(String path)
1287    {
1288        try {
1289            path = checkUri(path);
1290            out.print("unchecking out '" + path + "': ");
1291            if (webdavResource.uncheckoutMethod(path)) {
1292                out.println("succeeded.");
1293            } else {
1294                out.println("failed.");
1295                out.println(webdavResource.getStatusMessage());
1296            }
1297        }
1298        catch (Exception ex) {
1299            handleException(ex);
1300        }
1301    }
1302
1303
1304    void versioncontrol(String path)
1305    {
1306        try {
1307            path = checkUri(path);
1308            out.print("setting up VersionControl '" + path + "': ");
1309            if (webdavResource.versionControlMethod(path)) {
1310                out.println("succeeded.");
1311            } else {
1312                out.println("failed.");
1313                out.println(webdavResource.getStatusMessage());
1314            }
1315        }
1316        catch (Exception ex) {
1317            handleException(ex);
1318        }
1319    }
1320
1321    void versioncontrol(String target, String path)
1322    {
1323        try {
1324            path = checkUri(path);
1325            out.print("creating versioncontroled Resource '" + target + "' based on '" + path + "' : ");
1326            if (webdavResource.versionControlMethod(path, target)) {
1327                out.println("succeeded.");
1328            } else {
1329                out.println("failed.");
1330                out.println(webdavResource.getStatusMessage());
1331            }
1332        }
1333        catch (Exception ex) {
1334            handleException(ex);
1335        }
1336    }
1337
1338    void report(String path, Vector properties)
1339    {
1340        Enumeration propertyValues;
1341        try {
1342            path = checkUri(path);
1343            out.println("Getting version-tree Report of '" + path + "':");
1344
1345            if ((properties!=null) && (properties.size()>0)) {
1346                propertyValues =
1347                    webdavResource.reportMethod(uriToHttpURL(path), properties, 1);
1348            }
1349            else {
1350                propertyValues =
1351                    webdavResource.reportMethod(uriToHttpURL(path), 1);
1352            }
1353
1354            if (propertyValues.hasMoreElements()){
1355                while (propertyValues.hasMoreElements()){
1356                    out.println(propertyValues.nextElement().toString());
1357                }
1358            }
1359            else {
1360                out.println("failed.");
1361                out.println(webdavResource.getStatusMessage());
1362            }
1363        }
1364        catch (Exception ex) {
1365            handleException(ex);
1366        }
1367    }
1368
1369    void ereport(String path, String srcFilename)
1370    {
1371        try {
1372            String sQuery ="";
1373            if (srcFilename==null) {
1374                sQuery = "<D:expand-property xmlns:D='DAV:'><D:property name='version-history'><D:property name='version-set'><D:property name='successor-set'><D:property name='comment'/></D:property></D:property></D:property></D:expand-property>";
1375            }
1376            else {
1377                File file = new File(dir.getCanonicalPath(), srcFilename);
1378                if (!file.exists()) {
1379                    out.println("report src file not found");
1380                    return;
1381                }
1382                InputStream isQuery = new FileInputStream(file);
1383                BufferedReader reader = new BufferedReader(new InputStreamReader(isQuery));
1384
1385                while (reader.ready()) {
1386                    sQuery += reader.readLine();
1387                }
1388                reader.close();
1389
1390                sQuery.replace('\t',' ');
1391                out.println (sQuery);
1392            }
1393
1394            path = checkUri(path);
1395            out.println("expand-property Report of '" + path + "':");
1396
1397            Enumeration propertyValues =
1398                webdavResource.reportMethod(uriToHttpURL(path), sQuery, 1);
1399            if (propertyValues.hasMoreElements()){
1400                while (propertyValues.hasMoreElements()){
1401                    out.println(displayXML(propertyValues.nextElement().toString(), 0));
1402                }
1403            }
1404            else {
1405                out.println("failed.");
1406                out.println(webdavResource.getStatusMessage());
1407            }
1408        }
1409        catch (Exception ex) {
1410            handleException(ex);
1411        }
1412    }
1413
1414    /**
1415     * lreport path properties on historyUris
1416     */

1417    void lreport(String path, Vector properties, Vector historyUris)
1418    {
1419        try {
1420            path = checkUri(path);
1421            out.println("Getting version-tree Report of '" + path + "':");
1422
1423            Enumeration propertyValues =
1424                webdavResource.reportMethod(uriToHttpURL(path), properties, historyUris, 1);
1425            if (propertyValues.hasMoreElements()) {
1426                while (propertyValues.hasMoreElements()) {
1427                    out.println(propertyValues.nextElement().toString());
1428                }
1429            }
1430            else {
1431                out.println("failed.");
1432                out.println(webdavResource.getStatusMessage());
1433            }
1434        }
1435        catch (Exception ex) {
1436            handleException(ex);
1437        }
1438    }
1439
1440    void mkws(String path)
1441    {
1442        try {
1443            path = checkUri(path);
1444            out.print("Making '" + path + "' workspace: ");
1445            if (webdavResource.mkWorkspaceMethod(path)) {
1446                out.println("succeeded.");
1447            }
1448            else {
1449                out.println("failed.");
1450                out.println(webdavResource.getStatusMessage());
1451            }
1452        }
1453        catch (Exception ex) {
1454            handleException(ex);
1455        }
1456    }
1457
1458
1459    /**
1460     * Update
1461     *
1462     * @param path
1463     * @param version
1464     */

1465    void update(String path, String version){
1466        try {
1467            path = checkUri(path);
1468            out.print("Updateing resource " + path + ": ");
1469            if (webdavResource.updateMethod(path, version)) {
1470                out.println("succeeded.");
1471            } else {
1472                out.println("failed!");
1473                out.println(webdavResource.getStatusMessage());
1474            }
1475        } catch (Exception ex) {
1476            handleException(ex);
1477        }
1478    }
1479
1480    void beginTransaction(String timeout, String owner)
1481    {
1482        try {
1483            checkUri(null);
1484
1485            // Test the parameter
1486
//
1487
// Timeout
1488
int to=0;
1489            if ((timeout != null) && (timeout.toLowerCase().substring(0,5).equals("-tinf")) ) { //infinite
1490
to = LockMethod.TIMEOUT_INFINITY;
1491            } else {
1492                to = (timeout == null)? 120 : Integer.parseInt(timeout.substring(2));
1493            }
1494            
1495            // owner
1496
owner = (owner != null) ? (owner.substring(2)) : owner;
1497 
1498            out.print("Starting transaction ");
1499            if (webdavResource.startTransaction(owner, to)) {
1500                out.println("succeeded.");
1501                out.println("Handle: '"+webdavResource.getTransactionHandle()+"'");
1502            } else {
1503                out.println("failed.");
1504                out.println(webdavResource.getStatusMessage());
1505            }
1506        }
1507        catch (Exception ex) {
1508            handleException(ex);
1509        }
1510    }
1511
1512    void commitTransaction()
1513    {
1514        try {
1515            checkUri(null);
1516
1517            out.print("Committing transaction: '" + webdavResource.getTransactionHandle() + "' ");
1518            if (webdavResource.commitTransaction()) {
1519                out.println("succeeded.");
1520            } else {
1521                out.println("failed.");
1522                out.println(webdavResource.getStatusMessage());
1523            }
1524        }
1525        catch (Exception ex) {
1526            handleException(ex);
1527        }
1528    }
1529    
1530    void abortTransaction()
1531    {
1532        try {
1533            checkUri(null);
1534
1535            out.print("Rolling back transaction: '" +webdavResource.getTransactionHandle()+ "' ");
1536            if (webdavResource.abortTransaction()) {
1537                out.println("succeeded.");
1538            } else {
1539                out.println("failed.");
1540                out.println(webdavResource.getStatusMessage());
1541            }
1542        }
1543        catch (Exception ex) {
1544            handleException(ex);
1545        }
1546    }
1547    
1548    ///////////////////////////////////////////////////////////////////
1549
// Support methods
1550
///////////////////////////////////////////////////////////////////
1551

1552    private void setDisplayPrompt(boolean displayPrompt)
1553    {
1554        this.displayPrompt = displayPrompt;
1555    }
1556
1557    /**
1558     * Determine which URI to use at the prompt.
1559     *
1560     * @param uri the path to be set.
1561     * @return the absolute path.
1562     */

1563    private String checkUri(String uri) throws IOException
1564    {
1565
1566        if (webdavResource == null) {
1567            throw new IOException("Not connected yet.");
1568        }
1569
1570        if (uri==null) {
1571            uri=webdavResource.getPath();
1572        }
1573
1574        if (!uri.startsWith("/")) {
1575            uri = getPath() + uri;
1576        }
1577
1578        return normalize(uri);
1579    }
1580
1581    private String checkPrincipal(String principal, WebdavResource webdavResource, String path) throws HttpException,IOException
1582    {
1583        // Do not complete reserved words
1584
String[] types={"all","authenticated","unauthenticated","property","self"};
1585        for (int i=0; i<types.length ; i++)
1586        {
1587            if (types[i].equals(principal))
1588                return principal;
1589        }
1590
1591        // FIXME: when search support is complete enhance this
1592
// to really search for the principal
1593
if (!principal.startsWith("/") && !principal.startsWith("http")) {
1594            PrincipalCollectionSetProperty set = webdavResource.principalCollectionSetFindMethod(path);
1595            if ((set!=null) && (set.getHrefs()!=null) && (set.getHrefs().length==1))
1596                principal = set.getHrefs()[0] + "/" + principal;
1597        }
1598        return normalize(principal);
1599    }
1600
1601    /**
1602     * Set the path.
1603     *
1604     * @param path the path string.
1605     */

1606    private void setPath(String path)
1607    {
1608        if (!path.endsWith("/")) {
1609            path = path + "/";
1610        }
1611
1612        this.path = normalize(path);
1613    }
1614
1615
1616    /**
1617     * Get the path.
1618     *
1619     * @return the path string.
1620     */

1621    private String getPath()
1622    {
1623        return path;
1624    }
1625
1626
1627    /**
1628     * Update the command prompt for the display.
1629     *
1630     * @param path the path string
1631     */

1632    private void updatePrompt(String path)
1633    {
1634        StringBuffer buff = new StringBuffer();
1635        try {
1636            buff.append("[" + httpURL.getHost().toUpperCase() + ":" );
1637            buff.append(path+ "] ");
1638            buff.append(dir.getCanonicalPath());
1639            
1640        } catch (Exception e) {
1641            buff.append("[ Slide ]");
1642        }
1643        buff.append(" $ ");
1644        commandPrompt = buff.toString();
1645    }
1646
1647
1648    /**
1649     * Get the prompt.
1650     *
1651     * @return the prompt to be displayed.
1652     */

1653    private String getPrompt()
1654    {
1655        return commandPrompt;
1656    }
1657
1658
1659    /**
1660     * Return a context-relative path, beginning with a "/", that represents
1661     * the canonical version of the specified path after ".." and "." elements
1662     * are resolved out. If the specified path attempts to go outside the
1663     * boundaries of the current context (i.e. too many ".." path elements
1664     * are present), return <code>null</code> instead.
1665     *
1666     * @param path the path to be normalized.
1667     * @return the normalized path.
1668     */

1669    private String normalize(String path)
1670    {
1671        if (path == null)
1672            return null;
1673
1674        String normalized = path;
1675
1676        // Normalize the slashes and add leading slash if necessary
1677
if (normalized.indexOf('\\') >= 0)
1678            normalized = normalized.replace('\\', '/');
1679        if (!normalized.startsWith("/"))
1680            normalized = "/" + normalized;
1681
1682        // Resolve occurrences of "/./" in the normalized path
1683
while (true) {
1684            int index = normalized.indexOf("/./");
1685            if (index < 0)
1686            break;
1687            normalized = normalized.substring(0, index) +
1688            normalized.substring(index + 2);
1689        }
1690
1691        // Resolve occurrences of "/../" in the normalized path
1692
while (true) {
1693            int index = normalized.indexOf("/../");
1694            if (index < 0)
1695            break;
1696            if (index == 0)
1697            return ("/"); // The only left path is the root.
1698
int index2 = normalized.lastIndexOf('/', index - 1);
1699            normalized = normalized.substring(0, index2) +
1700            normalized.substring(index + 3);
1701        }
1702
1703        // Resolve occurrences of "//" in the normalized path
1704
while (true) {
1705            int index = normalized.indexOf("//");
1706            if (index < 0)
1707            break;
1708            normalized = normalized.substring(0, index) +
1709            normalized.substring(index + 1);
1710        }
1711
1712        // Return the normalized path that we have completed
1713
return (normalized);
1714    }
1715
1716    /**
1717     * Print the Slide client commands for use
1718     */

1719    private void printSlideClientUsage()
1720    {
1721        out.println("Commands:");
1722        out.println(" options {http_URL|path} " +
1723            "Print available http methods");
1724        out.println(" open [http_URL] " +
1725            "Connect to specified URL");
1726        out.println(" close " +
1727            "Close current connection");
1728        out.println(" exit " +
1729            "Exit Slide");
1730        out.println(" help " +
1731            "Print this help message");
1732        out.println(" debug {ON|OFF} " +
1733            "set debugmode");
1734        out.println(" lpwd " +
1735            "Print local working directory");
1736        out.println(" lcd [path] " +
1737            "Change local working directory");
1738        out.println(" lls [-lF] [path] " +
1739            "List contents of local directory");
1740        out.println(" pwc " +
1741            "Print working collection");
1742        out.println(" cc [path] " +
1743            "Change working collection");
1744        out.println(" ls [-lF] [path] " +
1745            "List contents of collection");
1746        out.println(" url " +
1747            "Print working URL");
1748        out.println(" status " +
1749            "Print latest http status message");
1750        out.println(" get path [file] " +
1751            "Get a resource to a file");
1752        out.println(" put {URL|file} [path] " +
1753            "Put a given file or URL to path");
1754        out.println(" mkcol path ... " +
1755            "Make new collections");
1756        out.println(" delete path ... " +
1757            "Delete resources");
1758        out.println(" copy source destination " +
1759            "Copy resource from source to destination path");
1760        out.println(" move source destination " +
1761            "Move resource from source to destination path");
1762        out.println(" lock path [-t(xxx|inf)] " +
1763            "[-s(SHARED|EXCLUSIVE)] [-oOWNER]\n" +
1764            " " +
1765            "Lock specified resource.\n" +
1766            " " +
1767            "default:\n" +
1768            " " +
1769            "lock file -t120 -sexclusive with current owner");
1770        out.println(" unlock path [-oOWNER] " +
1771            "Unlock specified resource.\n"+
1772            " " +
1773            "default:\n" +
1774            " " +
1775            "unlock file with current owner");
1776        out.println(" locks [<path>] " +
1777            "Displays locks on specified resource");
1778        out.println(" propget path property ... " +
1779            "Print value of specified property");
1780        out.println(" propgetall [<path>] " +
1781            "Print value of all properties");
1782        out.println(" propput path property value " +
1783            "Set property with given value");
1784        out.println(" set URLencode {on|off} " +
1785            "Set URL encoding flag, default: on");
1786        out.println(" set debug {on|off} " +
1787            "Set debug level, default: off");
1788        out.println(" acl [<path>] " +
1789            "Displays the ACL of path");
1790        out.println(" principalcol [<path>] " +
1791            "Displays the principal collection set of path");
1792        out.println(" grant [<namespace>] <permission> [on <path>] to <principal>");
1793        out.println(" deny [<namespace>] <permission> [on <path>] to <principal>");
1794        out.println(" revoke [<namespace>] <permission> [on <path>] from <principal>");
1795        out.println(" versioncontrol path "+
1796            "set a versionable resource under versioncontrol");
1797        out.println(" versioncontrol URL path "+
1798            "create a new versioncontrolled resource at path based on history URL");
1799        out.println(" checkout path "+
1800            "checkout of a checkedin resource");
1801        out.println(" checkin path "+
1802            "checkin of a checkedout resource");
1803        out.println(" uncheckout path "+
1804            "undoing changes on Resource since checkedout (including checkout)");
1805        out.println(" report path [<property>] "+
1806            "getting report (version-tree) for any resource");
1807        out.println(" eReport path "+
1808            "getting report (expand-property) for any resource");
1809        out.println(" LReport path [<property>] ON [<historyuri>] "+
1810            "getting report (locate-by-history)");
1811        out.println(" mkws path ... " +
1812            "Make new workspace");
1813        out.println(" update path target " +
1814            "Update a resource identified by path to version identified by target");
1815        out.println(" begin starts a new transaction (only if server supports this)");
1816        out.println(" commit commits the transaction started by begin (only if server supports this)");
1817        out.println(" abort aborts and rolls back the transaction started by begin (only if server supports this)");
1818        out.println
1819            ("Aliases: help=?, open=connect, ls=dir, pwc=pwd, cc=cd, " +
1820             "lls=ldir, copy=cp,\n move=mv, delete=del=rm, mkcol=mkdir, " +
1821             "propget=propfind, propput=proppatch,\n exit=quit=bye");
1822        out.println("Comment : Once executed, the debug mode will " +
1823                           "be active.\n\t\tBecause it's not triggered by " +
1824                           "methods yet.");
1825    }
1826
1827
1828    /**
1829     * Sleep
1830     */

1831// private static void pause(int secs)
1832
// {
1833
//
1834
// try {
1835
// Thread.sleep( secs * 1000 );
1836
// } catch( InterruptedException ex ) {
1837
// }
1838
// }
1839

1840// private String resolveNamespace(String permission)
1841
// {
1842
// String DEFAULT_NAMESPACE = "DAV:";
1843
// String SLIDE_NAMESPACE = "http://jakarta.apache.org/slide/";
1844
// String namespace=null;
1845
//
1846
// if (permission==null)
1847
// return null;
1848
//
1849
// if ((permission.equalsIgnoreCase("all")) ||
1850
// (permission.equalsIgnoreCase("read")) ||
1851
// (permission.equalsIgnoreCase("write")) ||
1852
// (permission.equalsIgnoreCase("read-acl")) ||
1853
// (permission.equalsIgnoreCase("write-acl")))
1854
// {
1855
// namespace=DEFAULT_NAMESPACE;
1856
// }
1857
//
1858
// if ((permission.equalsIgnoreCase("read-object")) ||
1859
// (permission.equalsIgnoreCase("read-revision-metadata")) ||
1860
// (permission.equalsIgnoreCase("read-revision-content")) ||
1861
// (permission.equalsIgnoreCase("create-object")) ||
1862
// (permission.equalsIgnoreCase("remove-object")) ||
1863
// (permission.equalsIgnoreCase("lock-object")) ||
1864
// (permission.equalsIgnoreCase("read-locks")) ||
1865
// (permission.equalsIgnoreCase("create-revision-metadata")) ||
1866
// (permission.equalsIgnoreCase("modify-revision-metadata")) ||
1867
// (permission.equalsIgnoreCase("remove-revision-metadata")) ||
1868
// (permission.equalsIgnoreCase("create-revision-content")) ||
1869
// (permission.equalsIgnoreCase("modify-revision-content")) ||
1870
// (permission.equalsIgnoreCase("remove-revision-content")) ||
1871
// (permission.equalsIgnoreCase("grant-permission")) ||
1872
// (permission.equalsIgnoreCase("revoke-permission")))
1873
// {
1874
// namespace=SLIDE_NAMESPACE;
1875
// }
1876
//
1877
// return namespace;
1878
// }
1879

1880    private boolean grant(WebdavResource webdavResource, QName permission, String path, String principal) throws HttpException, IOException
1881    {
1882        out.println("grant " + permission + " on " + path + " to " + principal);
1883        return addPermission(webdavResource, permission, path, principal, false);
1884    }
1885
1886    private boolean deny(WebdavResource webdavResource, QName permission, String path, String principal) throws HttpException, IOException
1887    {
1888        out.println("deny " + permission + " on " + path + " to " + principal);
1889        return addPermission(webdavResource, permission, path, principal, true);
1890    }
1891
1892    private boolean revoke(WebdavResource webdavResource, QName permission, String path, String principal) throws HttpException, IOException
1893    {
1894        out.println("revoke " + permission + " on " + path + " from " + principal);
1895        return removePermission(webdavResource, permission, path, principal);
1896    }
1897
1898    private boolean addPermission(WebdavResource webdavResource, QName permission, String path, String principal, boolean negative) throws HttpException, IOException
1899    {
1900
1901        AclProperty acl = webdavResource.aclfindMethod(path);
1902        if (acl==null)
1903        {
1904            out.println("Error: PropFind didn't return an AclProperty!");
1905            return false;
1906        }
1907        Ace[] aces=acl.getAces();
1908
1909        if (aces==null)
1910            aces=new Ace[0];
1911
1912        if (debugLevel>5) {
1913            out.println();
1914            out.println("ACL from server");
1915            showAces(path, aces);
1916        }
1917
1918        Ace ace=null;
1919        for (int i=0; i<aces.length && (ace==null); i++)
1920        {
1921            if ((aces[i].isNegative()==negative) && !aces[i].isProtected()
1922                && !aces[i].isInherited() && aces[i].getPrincipal().equals(principal))
1923            {
1924                if (debugLevel>5)
1925                    out.println("found ace");
1926                ace=aces[i];
1927            }
1928        }
1929        if (ace==null)
1930        {
1931            Ace[] oldAces=aces;
1932            aces=new Ace[oldAces.length+1];
1933            System.arraycopy(oldAces,0,aces,0,oldAces.length);
1934            ace=new Ace(principal, negative, false, false,null);
1935            aces[oldAces.length]=ace;
1936        }
1937
1938        Privilege privilege=new Privilege(permission.getNamespaceURI(), permission.getLocalName(), null);
1939        ace.addPrivilege(privilege);
1940
1941        if (debugLevel>5) {
1942            out.println();
1943            out.println("ACL with updated privileges");
1944            showAces(path, aces);
1945        }
1946
1947        boolean success = webdavResource.aclMethod(path,aces);
1948
1949        if (!success)
1950            out.println(webdavResource.getStatusMessage());
1951
1952        if (debugLevel>5) {
1953            acl = webdavResource.aclfindMethod(path);
1954            if (acl==null)
1955                out.println("Error: PropFind didn't return an AclProperty!");
1956            else
1957            {
1958                aces=acl.getAces();
1959                out.println();
1960                out.println("ACL from server after update");
1961                showAces(path, aces);
1962            }
1963        }
1964
1965        return success;
1966    }
1967
1968    private boolean removePermission(WebdavResource webdavResource, QName permission, String path, String principal) throws HttpException, IOException
1969    {
1970        AclProperty acl = webdavResource.aclfindMethod(path);
1971        if (acl==null)
1972        {
1973            out.println("Error: PropFind didn't return an AclProperty!");
1974            return false;
1975        }
1976        Ace[] aces=acl.getAces();
1977
1978        if (aces==null)
1979        {
1980            out.println("Privilege not found");
1981            return false;
1982        }
1983
1984        if (debugLevel>5) {
1985            out.println();
1986            out.println("ACL from server");
1987            showAces(path, aces);
1988        }
1989
1990        boolean found=false;
1991        Privilege privilege=new Privilege(permission.getNamespaceURI(), permission.getLocalName(), null);
1992        for (int i=0; i<aces.length; i++)
1993        {
1994            if (!aces[i].isProtected() && !aces[i].isInherited() && aces[i].getPrincipal().equals(principal))
1995            {
1996                if (debugLevel>5)
1997                    out.println("found ace");
1998                boolean removed = aces[i].removePrivilege(privilege);
1999                found = found || removed;
2000                if (removed)
2001                    out.println("Privilege removed");
2002            }
2003        }
2004
2005        if (!found)
2006        {
2007            out.println("Privilege not found");
2008            return false;
2009        }
2010
2011        if (debugLevel>5) {
2012            out.println();
2013            out.println("ACL with updated privileges");
2014            showAces(path, aces);
2015        }
2016
2017        boolean success = webdavResource.aclMethod(path,aces);
2018
2019        if (!success)
2020            out.println(webdavResource.getStatusMessage());
2021
2022        if (debugLevel>5) {
2023            acl = webdavResource.aclfindMethod(path);
2024            if (acl==null)
2025                out.println("Error: PropFind didn't return an AclProperty!");
2026            else
2027            {
2028                aces=acl.getAces();
2029                out.println();
2030                out.println("ACL from server after update");
2031                showAces(path, aces);
2032            }
2033        }
2034
2035        return success;
2036    }
2037
2038    private void showAces(String path, Ace[] aces)
2039    {
2040        if ((aces==null) || (aces.length==0)) {
2041            out.println("ACL for " + path + " is empty.");
2042            return;
2043        }
2044
2045        out.println("ACL for " + path + ":");
2046        out.println("------------------------------------------------------------");
2047        for (int i=0; i<aces.length ; i++)
2048        {
2049            Ace ace=aces[i];
2050            out.println((!ace.isNegative()?"granted":"denied") +
2051                " to " + ace.getPrincipal() + " " +
2052                " (" + (ace.isProtected()?"protected":"not protected") + ")" +
2053                " (" + (ace.isInherited()? ("inherited from '" + ace.getInheritedFrom() + "'"): "not inherited") +")");
2054
2055            Enumeration privileges=ace.enumeratePrivileges();
2056            while (privileges.hasMoreElements())
2057            {
2058                Privilege priv=(Privilege)privileges.nextElement();
2059                out.println(" " + priv.getNamespace() + priv.getName() + " " + (priv.getParameter()==null?"":("("+priv.getParameter()+")")));
2060            }
2061        }
2062        out.println("------------------------------------------------------------");
2063    }
2064
2065    private void showLocks(String path, Lock[] locks)
2066    {
2067        if ((locks==null) || (locks.length==0)) {
2068            out.println("No locks on " + path);
2069            return;
2070        }
2071
2072        out.println("Locks for " + path + ":");
2073        out.println("------------------------------------------------------------");
2074        for (int i=0; i<locks.length ; i++)
2075        {
2076            int lockScope = locks[i].getLockScope();
2077            if (lockScope==Lock.SCOPE_EXCLUSIVE) {
2078                out.print("Exclusive ");
2079            }
2080            else if (lockScope==Lock.SCOPE_SHARED) {
2081                out.print("Shared ");
2082            }
2083            else if (lockScope==-1) {
2084                out.print("Unknown scope ");
2085            }
2086            else {
2087                out.println("!!! Internal error !!!");
2088                return;
2089            }
2090
2091            int lockType = locks[i].getLockType();
2092            if (lockType==Lock.TYPE_WRITE) {
2093                out.println("write lock");
2094            }
2095            else if (lockType==-1) {
2096                out.println("unknown type");
2097            }
2098            else {
2099                out.println("!!! Internal error !!!");
2100                return;
2101            }
2102
2103            int depth=locks[i].getDepth();
2104            if (depth==DepthSupport.DEPTH_INFINITY) {
2105                out.println(" depth: infinity");
2106            }
2107            else if (depth==-1) {
2108                // unknown
2109
}
2110            else {
2111                out.println(" depth: " + depth);
2112            }
2113
2114            String owner=locks[i].getOwner();
2115            if (owner!=null)
2116                out.println(" owner: " + owner);
2117
2118            int timeout=locks[i].getTimeout();
2119            if (timeout!=-1)
2120                out.println(" timeout: " + timeout);
2121
2122            String token=locks[i].getLockToken();
2123            if (token!=null)
2124                out.println(" token: " + token);
2125        }
2126    }
2127
2128    private String displayXML(String xmlString, int count)
2129    {
2130        String sResult ="";
2131
2132        if(xmlString.startsWith("</")) {
2133            count --;
2134            //out.println("cl: " + count);
2135
for (int cc = count; cc > 0; cc--) {
2136                sResult += "\t";
2137            }
2138
2139            try {
2140                sResult += xmlString.substring(0, xmlString.indexOf(">") + 1)+"\n";
2141                xmlString = xmlString.substring(xmlString.indexOf(">") + 1);
2142                //count --;
2143
sResult += displayXML(xmlString, count);
2144            }
2145            catch (Exception any) {
2146                //sResult += "endtag" + any;
2147
}
2148
2149        }
2150        else if (xmlString.startsWith("<")) {
2151            //out.println("op: " + count);
2152
for (int cc = count; cc > 0; cc--) {
2153                sResult += "\t";
2154            }
2155            try {
2156                sResult += xmlString.substring(0, xmlString.indexOf(">") + 1)+"\n";
2157                xmlString = xmlString.substring(xmlString.indexOf(">") + 1);
2158                count ++;
2159                sResult += displayXML(xmlString, count);
2160            }
2161            catch (Exception any) {
2162                //sResult += "starttag" + any;
2163
}
2164        }
2165        else {
2166            //out.println("em: " + count);
2167
for (int cc = count; cc > 0; cc--) {
2168                sResult += "\t";
2169            }
2170            try {
2171                sResult += xmlString.substring(0, xmlString.indexOf("<"))+ "\n";
2172                xmlString = xmlString.substring(xmlString.indexOf("<"));
2173                sResult += displayXML(xmlString, count);
2174            }
2175            catch (Exception any) {
2176                //sResult += any;
2177
}
2178        }
2179        return sResult;
2180    }
2181
2182    private static HttpURL uriToHttpURL(String uri) throws URIException {
2183        return uri.startsWith("https") ? new HttpsURL(uri)
2184                                       : new HttpURL(uri);
2185    }
2186}
2187
Popular Tags