]> source.dussan.org Git - archiva.git/blob
cdb26b39eab0304dbd547cce751868245bc1c072
[archiva.git] /
1 package org.apache.archiva;
2 /*
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  */
20
21 import junit.framework.TestCase;
22 import org.apache.archiva.admin.model.beans.RemoteRepository;
23 import org.apache.archiva.rest.api.services.ProxyConnectorService;
24 import org.apache.archiva.rest.api.services.RemoteRepositoriesService;
25 import org.apache.archiva.security.common.ArchivaRoleConstants;
26 import org.apache.archiva.webdav.RepositoryServlet;
27 import org.apache.commons.io.FileUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.cxf.common.util.Base64Utility;
30 import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
31 import org.apache.cxf.jaxrs.client.WebClient;
32 import org.apache.cxf.transport.servlet.CXFServlet;
33 import org.codehaus.plexus.util.IOUtil;
34 import org.codehaus.redback.integration.security.role.RedbackRoleConstants;
35 import org.codehaus.redback.rest.api.services.RoleManagementService;
36 import org.codehaus.redback.rest.api.services.UserService;
37 import org.codehaus.redback.rest.services.FakeCreateAdminService;
38 import org.eclipse.jetty.server.Connector;
39 import org.eclipse.jetty.server.Server;
40 import org.eclipse.jetty.server.session.SessionHandler;
41 import org.eclipse.jetty.servlet.ServletContextHandler;
42 import org.eclipse.jetty.servlet.ServletHolder;
43 import org.junit.After;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.junit.runners.JUnit4;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.web.context.ContextLoaderListener;
53
54 import javax.servlet.ServletException;
55 import javax.servlet.http.HttpServlet;
56 import javax.servlet.http.HttpServletRequest;
57 import javax.servlet.http.HttpServletResponse;
58 import java.io.File;
59 import java.io.FileWriter;
60 import java.io.IOException;
61 import java.io.InputStream;
62 import java.net.HttpURLConnection;
63 import java.net.URL;
64 import java.util.ArrayList;
65 import java.util.Enumeration;
66 import java.util.List;
67 import java.util.zip.ZipEntry;
68 import java.util.zip.ZipFile;
69
70 /**
71  * @author Olivier Lamy
72  */
73 @RunWith( JUnit4.class )
74 public class DownloadArtifactsTest
75     extends TestCase
76 {
77
78     protected static Logger log = LoggerFactory.getLogger( DownloadArtifactsTest.class );
79
80     public String authorizationHeader = getAdminAuthzHeader();
81
82     public Server server = null;
83
84     public Server redirectServer = null;
85
86     public int port;
87
88     public int redirectPort;
89
90     public static String encode( String uid, String password )
91     {
92         return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
93     }
94
95     public static String getAdminAuthzHeader()
96     {
97         String adminPwdSysProps = System.getProperty( "rest.admin.pwd" );
98         if ( StringUtils.isBlank( adminPwdSysProps ) )
99         {
100             return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, FakeCreateAdminService.ADMIN_TEST_PWD );
101         }
102         return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminPwdSysProps );
103     }
104
105     protected String getSpringConfigLocation()
106     {
107         return "classpath*:META-INF/spring-context.xml classpath*:spring-context-artifacts-download.xml";
108     }
109
110
111     protected String getRestServicesPath()
112     {
113         return "restServices";
114     }
115
116     static String previousAppServerBase;
117
118     @BeforeClass
119     public static void setAppServerBase()
120     {
121
122         previousAppServerBase = System.getProperty( "appserver.base" );
123         System.setProperty( "appserver.base", "target/" + DownloadArtifactsTest.class.getName() );
124     }
125
126
127     @AfterClass
128     public static void resetAppServerBase()
129     {
130
131         System.setProperty( "appserver.base", previousAppServerBase );
132     }
133
134     @Before
135     public void startServer()
136         throws Exception
137     {
138
139         System.setProperty( "redback.admin.creation.file", "target/auto-admin-creation.properties" );
140         this.server = new Server( 0 );
141
142         ServletContextHandler context = new ServletContextHandler();
143
144         context.setContextPath( "/" );
145
146         context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
147
148         ContextLoaderListener contextLoaderListener = new ContextLoaderListener();
149
150         context.addEventListener( contextLoaderListener );
151
152         ServletHolder sh = new ServletHolder( CXFServlet.class );
153
154         SessionHandler sessionHandler = new SessionHandler();
155
156         context.setSessionHandler( sessionHandler );
157
158         context.addServlet( sh, "/" + getRestServicesPath() + "/*" );
159
160         ServletHolder repoSh = new ServletHolder( RepositoryServlet.class );
161         context.addServlet( repoSh, "/repository/*" );
162
163         server.setHandler( context );
164         this.server.start();
165         Connector connector = this.server.getConnectors()[0];
166         this.port = connector.getLocalPort();
167         log.info( "start server on port " + this.port );
168
169         //redirect handler
170
171         this.redirectServer = new Server( 0 );
172         ServletHolder shRedirect = new ServletHolder( RedirectServlet.class );
173         ServletContextHandler contextRedirect = new ServletContextHandler();
174
175         contextRedirect.setContextPath( "/" );
176         contextRedirect.addServlet( shRedirect, "/*" );
177
178         redirectServer.setHandler( contextRedirect );
179         redirectServer.start();
180         this.redirectPort = redirectServer.getConnectors()[0].getLocalPort();
181         log.info( "redirect server port {}", redirectPort );
182
183         FakeCreateAdminService fakeCreateAdminService = getFakeCreateAdminService();
184
185         Boolean res = fakeCreateAdminService.createAdminIfNeeded();
186         assertTrue( res.booleanValue() );
187
188
189     }
190
191     @After
192     public void tearDown()
193         throws Exception
194     {
195         System.clearProperty( "redback.admin.creation.file" );
196         super.tearDown();
197     }
198
199     @Test
200     public void downloadWithRemoteRedirect()
201         throws Exception
202     {
203         RemoteRepository remoteRepository = getRemoteRepositoriesService().getRemoteRepository( "central" );
204         remoteRepository.setUrl( "http://localhost:" + redirectPort );
205         getRemoteRepositoriesService().updateRemoteRepository( remoteRepository );
206
207         RoleManagementService roleManagementService = getRoleManagementService( authorizationHeader );
208
209         if ( !roleManagementService.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
210                                                          "internal" ) )
211         {
212             roleManagementService.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal" );
213         }
214
215         getUserService( authorizationHeader ).createGuestUser();
216         roleManagementService.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, "guest" );
217
218         roleManagementService.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal",
219                                                    "guest" );
220
221         getUserService( authorizationHeader ).removeFromCache( "guest" );
222
223         URL url = new URL( "http://localhost:" + port + "/repository/internal/junit/junit/4.9/junit-4.9.jar" );
224         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
225         //urlConnection.setRequestProperty( "Authorization", authorizationHeader );
226         InputStream is = urlConnection.getInputStream();
227         File file = new File( "target/junit-4.9.jar" );
228         if ( file.exists() )
229         {
230             file.delete();
231         }
232
233         FileWriter fw = new FileWriter( file );
234         IOUtil.copy( is, fw );
235         // assert jar contains org/junit/runners/JUnit4.class
236         ZipFile zipFile = new ZipFile( file );
237         List<String> entries = getZipEntriesNames( zipFile );
238         ZipEntry zipEntry = zipFile.getEntry( "org/junit/runners/JUnit4.class" );
239         assertNotNull( "cannot find zipEntry org/junit/runners/JUnit4.class, entries: " + entries + ", content is: "
240                            + FileUtils.readFileToString( file ), zipEntry );
241         zipFile.close();
242         file.deleteOnExit();
243     }
244
245     private List<String> getZipEntriesNames( ZipFile zipFile )
246     {
247         List<String> entriesNames = new ArrayList<String>();
248         Enumeration<? extends ZipEntry> entries = zipFile.entries();
249         while ( entries.hasMoreElements() )
250         {
251             entriesNames.add( entries.nextElement().getName() );
252         }
253         return entriesNames;
254     }
255
256     public static class RedirectServlet
257         extends HttpServlet
258     {
259         @Override
260         protected void doGet( HttpServletRequest req, HttpServletResponse resp )
261             throws ServletException, IOException
262         {
263
264             log.info( "redirect servlet receive: {}", req.getRequestURI() );
265             resp.setStatus( 302 );
266             resp.getWriter().write( "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n"
267                                         + "<title>302 Found</title>\n" + "</head><body>\n" + "<h1>Found</h1>\n"
268                                         + "<p>The document has moved <a href=\"http://repo1.maven.apache.org/maven2/junit/junit/4.9/junit-4.9.jar\">here</a>.</p>\n"
269                                         + "</body></html>\n" + "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
270                                         + "<html><head>\n" );
271             resp.sendRedirect( "http://repo1.maven.apache.org/maven2/" + req.getRequestURI() );
272         }
273     }
274
275     protected ProxyConnectorService getProxyConnectorService()
276     {
277         ProxyConnectorService service =
278             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
279                                        ProxyConnectorService.class );
280
281         WebClient.client( service ).header( "Authorization", authorizationHeader );
282         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
283         return service;
284     }
285
286     protected RemoteRepositoriesService getRemoteRepositoriesService()
287     {
288         RemoteRepositoriesService service =
289             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
290                                        RemoteRepositoriesService.class );
291
292         WebClient.client( service ).header( "Authorization", authorizationHeader );
293         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000L );
294         return service;
295     }
296
297     protected String getBaseUrl()
298     {
299         String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
300         return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + port : baseUrlSysProps;
301     }
302
303
304     protected RoleManagementService getRoleManagementService( String authzHeader )
305     {
306         RoleManagementService service =
307             JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
308                                        RoleManagementService.class );
309
310         // for debuging purpose
311         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
312
313         if ( authzHeader != null )
314         {
315             WebClient.client( service ).header( "Authorization", authzHeader );
316         }
317         return service;
318     }
319
320     protected UserService getUserService( String authzHeader )
321     {
322         UserService service =
323             JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/redbackServices/",
324                                        UserService.class );
325
326         // for debuging purpose
327         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 3000000L );
328
329         if ( authzHeader != null )
330         {
331             WebClient.client( service ).header( "Authorization", authzHeader );
332         }
333         return service;
334     }
335
336     protected FakeCreateAdminService getFakeCreateAdminService()
337     {
338         return JAXRSClientFactory.create(
339             "http://localhost:" + port + "/" + getRestServicesPath() + "/fakeCreateAdminService/",
340             FakeCreateAdminService.class );
341     }
342
343
344 }