View Javadoc

1   package org.apache.continuum.buildagent.webdav.client;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import org.apache.commons.httpclient.Credentials;
23  import org.apache.commons.httpclient.HostConfiguration;
24  import org.apache.commons.httpclient.HttpConnectionManager;
25  import org.apache.commons.httpclient.HttpMethod;
26  import org.apache.commons.httpclient.HttpStatus;
27  import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
28  import org.apache.commons.httpclient.methods.GetMethod;
29  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
30  import org.apache.commons.io.IOUtils;
31  import org.apache.commons.lang.StringUtils;
32  import org.apache.http.HttpHost;
33  import org.apache.http.HttpResponse;
34  import org.apache.http.HttpVersion;
35  import org.apache.http.auth.AuthScope;
36  import org.apache.http.auth.UsernamePasswordCredentials;
37  import org.apache.http.client.AuthCache;
38  import org.apache.http.client.methods.HttpGet;
39  import org.apache.http.client.protocol.ClientContext;
40  import org.apache.http.conn.ClientConnectionManager;
41  import org.apache.http.conn.params.ConnManagerPNames;
42  import org.apache.http.conn.params.ConnPerRouteBean;
43  import org.apache.http.conn.scheme.PlainSocketFactory;
44  import org.apache.http.conn.scheme.Scheme;
45  import org.apache.http.conn.scheme.SchemeRegistry;
46  import org.apache.http.impl.auth.BasicScheme;
47  import org.apache.http.impl.client.BasicAuthCache;
48  import org.apache.http.impl.client.DefaultHttpClient;
49  import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
50  import org.apache.http.params.BasicHttpParams;
51  import org.apache.http.params.HttpParams;
52  import org.apache.http.params.HttpProtocolParams;
53  import org.apache.http.protocol.BasicHttpContext;
54  import org.apache.http.util.EntityUtils;
55  import org.apache.jackrabbit.webdav.DavConstants;
56  import org.apache.jackrabbit.webdav.DavException;
57  import org.apache.jackrabbit.webdav.MultiStatus;
58  import org.apache.jackrabbit.webdav.MultiStatusResponse;
59  import org.apache.jackrabbit.webdav.client.methods.DavMethod;
60  import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
61  import org.apache.jackrabbit.webdav.property.DavProperty;
62  
63  import java.io.IOException;
64  import java.io.InputStream;
65  import java.net.URI;
66  import java.net.URISyntaxException;
67  import java.net.URL;
68  
69  public class WorkingCopyWebdavClient
70  {
71      public static void main( String[] args )
72          throws Exception
73      {
74          System.out.println( "Running webdav client.." );
75  
76          // get resource
77          getResourceUsingHttpclient( args[0], "", args[1] );
78  
79          // list resources
80          getResourcesUsingJackrabbit( args[0], "", args[1] );
81      }
82  
83      private static void getResourceUsingHttpclient( String resourceUrl, String username, String password )
84          throws URISyntaxException, IOException
85      {
86          SchemeRegistry schemeRegistry = new SchemeRegistry();
87          schemeRegistry.register( new Scheme( "http", PlainSocketFactory.getSocketFactory(), 80 ) );
88  
89          HttpParams params = new BasicHttpParams();
90          params.setParameter( ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30 );
91          params.setParameter( ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean( 30 ) );
92  
93          HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 );
94  
95          ClientConnectionManager cm = new ThreadSafeClientConnManager( params, schemeRegistry );
96  
97          DefaultHttpClient httpClient = new DefaultHttpClient( cm, params );
98  
99          URL url = new URL( resourceUrl );
100         URI uri = url.toURI();
101         HttpGet httpGet = new HttpGet( uri );
102 
103         httpClient.getCredentialsProvider().setCredentials( new AuthScope( uri.getHost(), uri.getPort() ),
104                                                             new UsernamePasswordCredentials( username, password ) );
105 
106         HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
107 
108         AuthCache authCache = new BasicAuthCache();
109         BasicScheme basicAuth = new BasicScheme();
110         authCache.put( targetHost, basicAuth );
111 
112         BasicHttpContext localcontext = new BasicHttpContext();
113         localcontext.setAttribute( ClientContext.AUTH_CACHE, authCache );
114 
115         System.out.println( "Retrieving resource '" + url.toString() + "' using HttpClient's get method.." );
116 
117         HttpResponse httpResponse = httpClient.execute( targetHost, httpGet, localcontext );
118 
119         System.out.println( "Response status code :: " + httpResponse.getStatusLine().getStatusCode() );
120 
121         InputStream is = IOUtils.toInputStream( EntityUtils.toString( httpResponse.getEntity(),
122                                                                       EntityUtils.getContentCharSet(
123                                                                           httpResponse.getEntity() ) ) );
124         String content = IOUtils.toString( is );
125 
126         System.out.println( "Content :: " + content );
127     }
128 
129     private static void getResourcesUsingJackrabbit( String filePath, String username, String password )
130         throws IOException, URISyntaxException, DavException
131     {
132         int idx = filePath.lastIndexOf( "/" );
133         if ( idx != -1 )
134         {
135             filePath = StringUtils.substring( filePath, 0, idx + 1 );
136         }
137 
138         System.out.println( "\nRetrieve resources from '" + filePath + "' using Jackrabbit's webdav client.." );
139 
140         URL url = new URL( filePath );
141         URI uri = url.toURI();
142 
143         DavMethod pFind = new PropFindMethod( uri.toString(), DavConstants.PROPFIND_ALL_PROP, DavConstants.DEPTH_1 );
144 
145         executeMethod( username, password, uri, pFind );
146 
147         MultiStatus multiStatus = pFind.getResponseBodyAsMultiStatus();
148         MultiStatusResponse[] responses = multiStatus.getResponses();
149         MultiStatusResponse currResponse;
150         System.out.println( "Folders and files in " + filePath + ":" );
151 
152         for ( int i = 0; i < responses.length; i++ )
153         {
154             currResponse = responses[i];
155             if ( !( currResponse.getHref().equals( uri.toString() ) || currResponse.getHref().equals(
156                 uri.toString() + "/" ) ) )
157             {
158                 String currResponseHref = StringUtils.trim( currResponse.getHref() );
159 
160                 System.out.println( "\nResource url :: " + currResponseHref );
161 
162                 DavProperty displayNameDavProperty = currResponse.getProperties( HttpStatus.SC_OK ).get(
163                     "displayname" );
164                 String displayName;
165                 if ( displayNameDavProperty != null )
166                 {
167                     displayName = (String) displayNameDavProperty.getValue();
168                 }
169                 else
170                 {
171                     displayName = StringUtils.substring( currResponseHref, currResponseHref.lastIndexOf( "/" ) );
172                 }
173 
174                 HttpMethod httpGet = new GetMethod( currResponseHref );
175 
176                 URL resourceUrl = new URL( currResponseHref );
177 
178                 executeMethod( username, password, resourceUrl.toURI(), httpGet );
179 
180                 System.out.println( "Returned status code :: " + httpGet.getStatusCode() );
181 
182                 if ( httpGet.getStatusCode() == HttpStatus.SC_OK )
183                 {
184                     InputStream is = httpGet.getResponseBodyAsStream();
185 
186                     try
187                     {
188                         System.out.println( "Contents of file '" + displayName + "' :: " + IOUtils.toString( is ) );
189                     }
190                     finally
191                     {
192                         IOUtils.closeQuietly( is );
193                     }
194                 }
195             }
196         }
197     }
198 
199     private static void executeMethod( String username, String password, URI uri, HttpMethod pFind )
200         throws IOException
201     {
202         HostConfiguration hostConfig = new HostConfiguration();
203         hostConfig.setHost( uri.getHost() );
204 
205         int maxHostConnections = 20;
206 
207         HttpConnectionManagerParams params = new HttpConnectionManagerParams();
208         params.setMaxConnectionsPerHost( hostConfig, maxHostConnections );
209 
210         HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
211         connectionManager.setParams( params );
212 
213         org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
214             connectionManager );
215 
216         Credentials creds = new org.apache.commons.httpclient.UsernamePasswordCredentials( username, password );
217 
218         client.getState().setCredentials( org.apache.commons.httpclient.auth.AuthScope.ANY, creds );
219         client.setHostConfiguration( hostConfig );
220         client.getParams().setAuthenticationPreemptive( true );
221 
222         client.executeMethod( hostConfig, pFind );
223     }
224 
225 }