1 package org.apache.archiva.webdav;
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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
22 import com.gargoylesoftware.htmlunit.HttpMethod;
23 import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
24 import com.gargoylesoftware.htmlunit.WebClient;
25 import com.gargoylesoftware.htmlunit.WebRequest;
26 import com.gargoylesoftware.htmlunit.WebResponse;
27 import junit.framework.Assert;
28 import junit.framework.TestCase;
29 import net.sf.ehcache.CacheManager;
30 import org.apache.archiva.admin.model.beans.ManagedRepository;
31 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
32 import org.apache.archiva.configuration.ArchivaConfiguration;
33 import org.apache.archiva.configuration.Configuration;
34 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
35 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
36 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
37 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
38 import org.apache.catalina.core.StandardContext;
39 import org.apache.catalina.startup.Tomcat;
40 import org.apache.commons.io.FileUtils;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.runner.RunWith;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.BeansException;
47 import org.springframework.beans.factory.BeanFactory;
48 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
49 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
50 import org.springframework.context.ApplicationContext;
51 import org.springframework.context.ApplicationEvent;
52 import org.springframework.context.MessageSourceResolvable;
53 import org.springframework.context.NoSuchMessageException;
54 import org.springframework.core.env.Environment;
55 import org.springframework.core.io.Resource;
56 import org.springframework.mock.web.MockHttpServletRequest;
57 import org.springframework.mock.web.MockHttpServletResponse;
58 import org.springframework.mock.web.MockServletConfig;
59 import org.springframework.mock.web.MockServletContext;
60 import org.springframework.test.context.ContextConfiguration;
61 import org.springframework.web.context.WebApplicationContext;
63 import javax.inject.Inject;
64 import javax.servlet.Servlet;
65 import javax.servlet.ServletContext;
66 import javax.servlet.http.HttpServletRequest;
67 import javax.servlet.http.HttpServletResponse;
69 import java.io.IOException;
70 import java.io.InputStream;
71 import java.io.UnsupportedEncodingException;
72 import java.lang.annotation.Annotation;
74 import java.nio.charset.Charset;
75 import java.util.Locale;
79 * AbstractRepositoryServletTestCase
81 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
82 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:spring-context.xml",
83 "classpath*:/repository-servlet-simple.xml" } )
84 public abstract class AbstractRepositoryServletTestCase
87 protected static final String REPOID_INTERNAL = "internal";
89 protected static final String REPOID_LEGACY = "legacy";
91 protected File repoRootInternal;
93 protected File repoRootLegacy;
96 protected ArchivaConfiguration archivaConfiguration;
99 protected ApplicationContext applicationContext;
102 protected ManagedRepositoryAdmin managedRepositoryAdmin;
104 protected Logger log = LoggerFactory.getLogger( getClass() );
107 protected void saveConfiguration()
110 saveConfiguration( archivaConfiguration );
113 protected Tomcat tomcat;
115 protected static int port;
118 StandardContext context;
127 String appserverBase = new File( "target/appserver-base" ).getAbsolutePath();
128 System.setProperty( "appserver.base", appserverBase );
130 File testConf = new File( "src/test/resources/repository-archiva.xml" );
131 File testConfDest = new File( appserverBase, "conf/archiva.xml" );
132 if ( testConfDest.exists() )
134 FileUtils.deleteQuietly( testConfDest );
136 FileUtils.copyFile( testConf, testConfDest );
138 repoRootInternal = new File( appserverBase, "data/repositories/internal" );
139 repoRootLegacy = new File( appserverBase, "data/repositories/legacy" );
140 Configuration config = archivaConfiguration.getConfiguration();
142 config.getManagedRepositories().clear();
144 config.addManagedRepository(
145 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
147 managedRepositoryAdmin.createIndexContext( managedRepositoryAdmin.getManagedRepository( REPOID_INTERNAL ) );
149 config.addManagedRepository(
150 createManagedRepository( REPOID_LEGACY, "Legacy Format Test Repo", repoRootLegacy, "legacy", true ) );
152 config.getProxyConnectors().clear();
154 config.getRemoteRepositories().clear();
156 saveConfiguration( archivaConfiguration );
158 CacheManager.getInstance().clearAll();
160 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
165 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
166 new UnauthenticatedRepositoryServlet();
168 protected void startRepository()
172 final MockServletContext mockServletContext = new MockServletContext();
174 WebApplicationContext webApplicationContext =
175 new TestWebapplicationContext( applicationContext, mockServletContext );
177 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
178 webApplicationContext );
180 MockServletConfig mockServletConfig = new MockServletConfig()
183 public ServletContext getServletContext()
185 return mockServletContext;
189 unauthenticatedRepositoryServlet.init( mockServletConfig );
194 static class TestWebapplicationContext
195 implements WebApplicationContext
197 private ApplicationContext applicationContext;
199 private ServletContext servletContext;
201 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
203 this.applicationContext = applicationContext;
207 public ServletContext getServletContext()
209 return servletContext;
213 public String getId()
215 return applicationContext.getId();
219 public String getApplicationName()
221 return applicationContext.getApplicationName();
225 public String getDisplayName()
227 return applicationContext.getDisplayName();
231 public long getStartupDate()
233 return applicationContext.getStartupDate();
237 public ApplicationContext getParent()
239 return applicationContext.getParent();
243 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
244 throws IllegalStateException
246 return applicationContext.getAutowireCapableBeanFactory();
250 public void publishEvent( ApplicationEvent applicationEvent )
252 applicationContext.publishEvent( applicationEvent );
256 public Environment getEnvironment()
258 return applicationContext.getEnvironment();
262 public BeanFactory getParentBeanFactory()
264 return applicationContext.getParentBeanFactory();
268 public boolean containsLocalBean( String s )
270 return applicationContext.containsLocalBean( s );
274 public boolean containsBeanDefinition( String s )
276 return applicationContext.containsBeanDefinition( s );
280 public int getBeanDefinitionCount()
282 return applicationContext.getBeanDefinitionCount();
286 public String[] getBeanDefinitionNames()
288 return applicationContext.getBeanDefinitionNames();
292 public String[] getBeanNamesForType( Class<?> aClass )
294 return applicationContext.getBeanNamesForType( aClass );
298 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
300 return applicationContext.getBeanNamesForType( aClass, b, b2 );
304 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
305 throws BeansException
307 return applicationContext.getBeansOfType( tClass );
311 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
312 throws BeansException
314 return applicationContext.getBeansOfType( tClass, b, b2 );
318 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
320 return applicationContext.getBeanNamesForAnnotation( aClass );
324 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
325 throws BeansException
327 return applicationContext.getBeansWithAnnotation( aClass );
331 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
332 throws NoSuchBeanDefinitionException
334 return applicationContext.findAnnotationOnBean( s, aClass );
338 public Object getBean( String s )
339 throws BeansException
341 return applicationContext.getBean( s );
345 public <T> T getBean( String s, Class<T> tClass )
346 throws BeansException
348 return applicationContext.getBean( s, tClass );
352 public <T> T getBean( Class<T> tClass )
353 throws BeansException
355 return applicationContext.getBean( tClass );
359 public Object getBean( String s, Object... objects )
360 throws BeansException
362 return applicationContext.getBean( s, objects );
366 public boolean containsBean( String s )
368 return applicationContext.containsBean( s );
372 public boolean isSingleton( String s )
373 throws NoSuchBeanDefinitionException
375 return applicationContext.isSingleton( s );
379 public boolean isPrototype( String s )
380 throws NoSuchBeanDefinitionException
382 return applicationContext.isPrototype( s );
386 public boolean isTypeMatch( String s, Class<?> aClass )
387 throws NoSuchBeanDefinitionException
389 return applicationContext.isTypeMatch( s, aClass );
393 public Class<?> getType( String s )
394 throws NoSuchBeanDefinitionException
396 return applicationContext.getType( s );
400 public String[] getAliases( String s )
402 return applicationContext.getAliases( s );
406 public String getMessage( String s, Object[] objects, String s2, Locale locale )
408 return applicationContext.getMessage( s, objects, s2, locale );
412 public String getMessage( String s, Object[] objects, Locale locale )
413 throws NoSuchMessageException
415 return applicationContext.getMessage( s, objects, locale );
419 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
420 throws NoSuchMessageException
422 return applicationContext.getMessage( messageSourceResolvable, locale );
426 public Resource[] getResources( String s )
429 return applicationContext.getResources( s );
433 public Resource getResource( String s )
435 return applicationContext.getResource( s );
439 public ClassLoader getClassLoader()
441 return applicationContext.getClassLoader();
445 protected Servlet findServlet( String name )
448 return unauthenticatedRepositoryServlet;
450 Container[] childs = context.findChildren();
451 for ( Container container : childs )
453 if ( StringUtils.equals( container.getName(), name ) )
455 Tomcat.ExistingStandardWrapper esw = Tomcat.ExistingStandardWrapper.class.cast( container );
456 Servlet servlet = esw.loadServlet();
464 protected String getSpringConfigLocation()
466 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
473 protected ServletUnitClient getServletUnitClient()
476 if ( servletUnitClient != null )
478 return servletUnitClient;
480 servletRunner = new ServletRunner( new File( "src/test/resources/WEB-INF/web.xml" ) );
482 servletRunner.registerServlet( "/repository/*", UnauthenticatedRepositoryServlet.class.getName() );
484 servletUnitClient = servletRunner.newClient();
486 return servletUnitClient;
490 protected <P extends Page> P page(final String path) throws IOException {
491 return newClient().getPage(base.toExternalForm() + "repository/" + path);
495 protected static WebClient newClient()
497 final WebClient webClient = new WebClient();
498 webClient.getOptions().setJavaScriptEnabled( false );
499 webClient.getOptions().setCssEnabled( false );
500 webClient.getOptions().setAppletEnabled( false );
501 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
502 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
507 protected WebResponse getWebResponse( String path )
510 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
513 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
517 MockHttpServletRequest request = new MockHttpServletRequest();
518 request.setRequestURI( webRequest.getUrl().getPath() );
519 request.addHeader( "User-Agent", "Apache Archiva unit test" );
521 request.setMethod( webRequest.getHttpMethod().name() );
523 final MockHttpServletResponse response = execute( request );
525 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
526 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
528 String location = response.getHeader( "Location" );
529 log.debug("follow redirect to {}", location);
530 return getWebResponse( new GetMethodWebRequest( location ) );
533 return new WebResponse( null, null, 1 )
536 public String getContentAsString()
540 return response.getContentAsString();
542 catch ( UnsupportedEncodingException e )
544 throw new RuntimeException( e.getMessage(), e );
549 public int getStatusCode()
551 return response.getStatus();
555 public String getResponseHeaderValue( String headerName )
557 return response.getHeader( headerName );
562 protected MockHttpServletResponse execute( HttpServletRequest request )
565 MockHttpServletResponse response = new MockHttpServletResponse()
567 public String getContentAsString()
568 throws UnsupportedEncodingException
570 String errorMessage = getErrorMessage();
571 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
574 this.unauthenticatedRepositoryServlet.service( request, response );
578 public static class GetMethodWebRequest
583 public GetMethodWebRequest( String url )
586 super( new URL( url ) );
592 public static class PutMethodWebRequest
597 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
600 super( new URL( url ), HttpMethod.PUT );
607 public static class ServletUnitClient
610 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
612 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
614 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
617 public WebResponse getResponse( WebRequest request )
620 return getResponse( request, false );
623 public WebResponse getResponse( WebRequest request, boolean followRedirect )
626 // alwasy following redirect as it's normal
627 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
630 public WebResponse getResource( WebRequest request )
633 return getResponse( request );
637 public ServletUnitClient getServletUnitClient()
639 return new ServletUnitClient( this );
644 public void tearDown()
648 if ( repoRootInternal.exists() )
650 FileUtils.deleteDirectory( repoRootInternal );
653 if ( repoRootLegacy.exists() )
655 FileUtils.deleteDirectory( repoRootLegacy );
658 if ( this.tomcat != null )
666 protected void assertFileContents( String expectedContents, File repoRoot, String path )
669 File actualFile = new File( repoRoot, path );
670 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
671 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
672 actualFile.isFile() );
674 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
675 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
678 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
681 ManagedRepository repository = servlet.getRepository( repoId );
682 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
683 File repoRoot = new File( repository.getLocation() );
684 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
685 repoRoot.exists() && repoRoot.isDirectory() );
688 protected void assertResponseOK( WebResponse response )
691 assertNotNull( "Should have recieved a response", response );
692 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
693 response.getStatusCode() );
696 protected void assertResponseOK( WebResponse response, String path )
698 assertNotNull( "Should have recieved a response", response );
699 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
700 response.getStatusCode() );
703 protected void assertResponseNotFound( WebResponse response )
705 assertNotNull( "Should have recieved a response", response );
706 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
707 response.getStatusCode() );
710 protected void assertResponseInternalServerError( WebResponse response )
712 assertNotNull( "Should have recieved a response", response );
713 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
714 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
717 protected void assertResponseConflictError( WebResponse response )
719 assertNotNull( "Should have received a response", response );
720 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
721 response.getStatusCode() );
724 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
725 boolean blockRedeployments )
727 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
729 repo.setName( name );
730 repo.setLocation( location.getAbsolutePath() );
731 repo.setBlockRedeployments( blockRedeployments );
736 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
737 String layout, boolean blockRedeployments )
739 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
740 repo.setLayout( layout );
744 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
746 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
748 repo.setName( name );
753 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
756 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
760 protected void setupCleanRepo( File repoRootDir )
763 FileUtils.deleteDirectory( repoRootDir );
764 if ( !repoRootDir.exists() )
766 repoRootDir.mkdirs();
770 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
772 File repoFile = new File( repoRootInternal, resourcePath );
773 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
777 protected void setupCleanInternalRepo()
780 setupCleanRepo( repoRootInternal );
783 protected File populateRepo( File repoRootManaged, String path, String contents )
786 File destFile = new File( repoRootManaged, path );
787 destFile.getParentFile().mkdirs();
788 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );