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.configuration.ArchivaConfiguration;
32 import org.apache.archiva.configuration.Configuration;
33 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
34 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
35 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
36 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
37 import org.apache.archiva.webdav.util.ReinitServlet;
38 import org.apache.catalina.Container;
39 import org.apache.catalina.Context;
40 import org.apache.catalina.core.StandardContext;
41 import org.apache.catalina.deploy.ApplicationParameter;
42 import org.apache.catalina.startup.Tomcat;
43 import org.apache.commons.io.FileUtils;
44 import org.apache.commons.lang.StringUtils;
45 import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
46 import org.junit.After;
47 import org.junit.Before;
48 import org.junit.runner.RunWith;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.BeansException;
52 import org.springframework.beans.factory.BeanFactory;
53 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
54 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
55 import org.springframework.context.ApplicationContext;
56 import org.springframework.context.ApplicationEvent;
57 import org.springframework.context.MessageSourceResolvable;
58 import org.springframework.context.NoSuchMessageException;
59 import org.springframework.core.env.Environment;
60 import org.springframework.core.io.Resource;
61 import org.springframework.mock.web.MockHttpServletRequest;
62 import org.springframework.mock.web.MockHttpServletResponse;
63 import org.springframework.mock.web.MockServletConfig;
64 import org.springframework.mock.web.MockServletContext;
65 import org.springframework.test.context.ContextConfiguration;
66 import org.springframework.web.context.ContextLoaderListener;
67 import org.springframework.web.context.WebApplicationContext;
68 import org.springframework.web.context.support.GenericWebApplicationContext;
69 import org.springframework.web.context.support.StaticWebApplicationContext;
70 import org.springframework.web.context.support.WebApplicationContextUtils;
72 import javax.inject.Inject;
73 import javax.servlet.Servlet;
74 import javax.servlet.ServletContext;
75 import javax.servlet.http.HttpServletRequest;
76 import javax.servlet.http.HttpServletResponse;
78 import java.io.IOException;
79 import java.io.InputStream;
80 import java.io.UnsupportedEncodingException;
81 import java.lang.annotation.Annotation;
83 import java.nio.charset.Charset;
84 import java.util.Locale;
88 * AbstractRepositoryServletTestCase
90 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
91 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:spring-context.xml",
92 "classpath*:/repository-servlet-simple.xml" } )
93 public abstract class AbstractRepositoryServletTestCase
96 protected static final String REPOID_INTERNAL = "internal";
98 protected static final String REPOID_LEGACY = "legacy";
100 protected File repoRootInternal;
102 protected File repoRootLegacy;
105 protected ArchivaConfiguration archivaConfiguration;
108 protected ApplicationContext applicationContext;
110 protected Logger log = LoggerFactory.getLogger( getClass() );
113 protected void saveConfiguration()
116 saveConfiguration( archivaConfiguration );
119 protected Tomcat tomcat;
121 protected static int port;
124 StandardContext context;
133 String appserverBase = new File( "target/appserver-base" ).getAbsolutePath();
134 System.setProperty( "appserver.base", appserverBase );
136 File testConf = new File( "src/test/resources/repository-archiva.xml" );
137 File testConfDest = new File( appserverBase, "conf/archiva.xml" );
138 if ( testConfDest.exists() )
140 FileUtils.deleteQuietly( testConfDest );
142 FileUtils.copyFile( testConf, testConfDest );
144 archivaConfiguration = applicationContext.getBean( ArchivaConfiguration.class );
146 repoRootInternal = new File( appserverBase, "data/repositories/internal" );
147 repoRootLegacy = new File( appserverBase, "data/repositories/legacy" );
148 Configuration config = archivaConfiguration.getConfiguration();
150 config.getManagedRepositories().clear();
152 config.addManagedRepository(
153 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
155 config.addManagedRepository(
156 createManagedRepository( REPOID_LEGACY, "Legacy Format Test Repo", repoRootLegacy, "legacy", true ) );
158 config.getProxyConnectors().clear();
160 config.getRemoteRepositories().clear();
162 saveConfiguration( archivaConfiguration );
164 CacheManager.getInstance().clearAll();
166 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
171 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
172 new UnauthenticatedRepositoryServlet();
174 protected void startRepository()
178 tomcat = new Tomcat();
179 tomcat.setBaseDir( System.getProperty( "java.io.tmpdir" ) );
182 context = StandardContext.class.cast( tomcat.addContext( "", System.getProperty( "java.io.tmpdir" ) ) );
184 ApplicationParameter applicationParameter = new ApplicationParameter();
185 applicationParameter.setName( "contextConfigLocation" );
186 applicationParameter.setValue( getSpringConfigLocation() );
187 context.addApplicationParameter( applicationParameter );
189 context.addApplicationListener( ContextLoaderListener.class.getName() );
191 context.addApplicationListener( MavenIndexerCleaner.class.getName() );
193 Tomcat.addServlet( context, "repository", new UnauthenticatedRepositoryServlet() );
194 context.addServletMapping( "/repository/*", "repository" );
196 Tomcat.addServlet( context, "reinitservlet", new ReinitServlet() );
197 context.addServletMapping( "/reinit/*", "reinitservlet" );
201 this.port = tomcat.getConnector().getLocalPort();
204 final MockServletContext mockServletContext = new MockServletContext();
206 WebApplicationContext webApplicationContext =
207 new TestWebapplicationContext( applicationContext, mockServletContext );
209 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
210 webApplicationContext );
212 MockServletConfig mockServletConfig = new MockServletConfig()
215 public ServletContext getServletContext()
217 return mockServletContext;
221 unauthenticatedRepositoryServlet.init( mockServletConfig );
226 static class TestWebapplicationContext
227 implements WebApplicationContext
229 private ApplicationContext applicationContext;
231 private ServletContext servletContext;
233 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
235 this.applicationContext = applicationContext;
239 public ServletContext getServletContext()
241 return servletContext;
245 public String getId()
247 return applicationContext.getId();
251 public String getApplicationName()
253 return applicationContext.getApplicationName();
257 public String getDisplayName()
259 return applicationContext.getDisplayName();
263 public long getStartupDate()
265 return applicationContext.getStartupDate();
269 public ApplicationContext getParent()
271 return applicationContext.getParent();
275 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
276 throws IllegalStateException
278 return applicationContext.getAutowireCapableBeanFactory();
282 public void publishEvent( ApplicationEvent applicationEvent )
284 applicationContext.publishEvent( applicationEvent );
288 public Environment getEnvironment()
290 return applicationContext.getEnvironment();
294 public BeanFactory getParentBeanFactory()
296 return applicationContext.getParentBeanFactory();
300 public boolean containsLocalBean( String s )
302 return applicationContext.containsLocalBean( s );
306 public boolean containsBeanDefinition( String s )
308 return applicationContext.containsBeanDefinition( s );
312 public int getBeanDefinitionCount()
314 return applicationContext.getBeanDefinitionCount();
318 public String[] getBeanDefinitionNames()
320 return applicationContext.getBeanDefinitionNames();
324 public String[] getBeanNamesForType( Class<?> aClass )
326 return applicationContext.getBeanNamesForType( aClass );
330 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
332 return applicationContext.getBeanNamesForType( aClass, b, b2 );
336 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
337 throws BeansException
339 return applicationContext.getBeansOfType( tClass );
343 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
344 throws BeansException
346 return applicationContext.getBeansOfType( tClass, b, b2 );
350 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
352 return applicationContext.getBeanNamesForAnnotation( aClass );
356 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
357 throws BeansException
359 return applicationContext.getBeansWithAnnotation( aClass );
363 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
364 throws NoSuchBeanDefinitionException
366 return applicationContext.findAnnotationOnBean( s, aClass );
370 public Object getBean( String s )
371 throws BeansException
373 return applicationContext.getBean( s );
377 public <T> T getBean( String s, Class<T> tClass )
378 throws BeansException
380 return applicationContext.getBean( s, tClass );
384 public <T> T getBean( Class<T> tClass )
385 throws BeansException
387 return applicationContext.getBean( tClass );
391 public Object getBean( String s, Object... objects )
392 throws BeansException
394 return applicationContext.getBean( s, objects );
398 public boolean containsBean( String s )
400 return applicationContext.containsBean( s );
404 public boolean isSingleton( String s )
405 throws NoSuchBeanDefinitionException
407 return applicationContext.isSingleton( s );
411 public boolean isPrototype( String s )
412 throws NoSuchBeanDefinitionException
414 return applicationContext.isPrototype( s );
418 public boolean isTypeMatch( String s, Class<?> aClass )
419 throws NoSuchBeanDefinitionException
421 return applicationContext.isTypeMatch( s, aClass );
425 public Class<?> getType( String s )
426 throws NoSuchBeanDefinitionException
428 return applicationContext.getType( s );
432 public String[] getAliases( String s )
434 return applicationContext.getAliases( s );
438 public String getMessage( String s, Object[] objects, String s2, Locale locale )
440 return applicationContext.getMessage( s, objects, s2, locale );
444 public String getMessage( String s, Object[] objects, Locale locale )
445 throws NoSuchMessageException
447 return applicationContext.getMessage( s, objects, locale );
451 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
452 throws NoSuchMessageException
454 return applicationContext.getMessage( messageSourceResolvable, locale );
458 public Resource[] getResources( String s )
461 return applicationContext.getResources( s );
465 public Resource getResource( String s )
467 return applicationContext.getResource( s );
471 public ClassLoader getClassLoader()
473 return applicationContext.getClassLoader();
477 protected Servlet findServlet( String name )
480 return unauthenticatedRepositoryServlet;
482 Container[] childs = context.findChildren();
483 for ( Container container : childs )
485 if ( StringUtils.equals( container.getName(), name ) )
487 Tomcat.ExistingStandardWrapper esw = Tomcat.ExistingStandardWrapper.class.cast( container );
488 Servlet servlet = esw.loadServlet();
496 protected String getSpringConfigLocation()
498 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
505 protected ServletUnitClient getServletUnitClient()
508 if ( servletUnitClient != null )
510 return servletUnitClient;
512 servletRunner = new ServletRunner( new File( "src/test/resources/WEB-INF/web.xml" ) );
514 servletRunner.registerServlet( "/repository/*", UnauthenticatedRepositoryServlet.class.getName() );
516 servletUnitClient = servletRunner.newClient();
518 return servletUnitClient;
522 protected <P extends Page> P page(final String path) throws IOException {
523 return newClient().getPage(base.toExternalForm() + "repository/" + path);
527 protected static WebClient newClient()
529 final WebClient webClient = new WebClient();
530 webClient.getOptions().setJavaScriptEnabled( false );
531 webClient.getOptions().setCssEnabled( false );
532 webClient.getOptions().setAppletEnabled( false );
533 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
534 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
539 protected WebResponse getWebResponse( String path )
542 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );
545 protected WebResponse getWebResponse( WebRequest webRequest )
549 //WebClient client = newClient();
550 //client.getPage( "http://localhost:" + port + "/reinit/reload" );
551 //return client.getPage( "http://localhost:" + port + path ).getWebResponse();
553 MockHttpServletRequest request = new MockHttpServletRequest();
554 request.setRequestURI( webRequest.getUrl().getPath() );
555 request.addHeader( "User-Agent", "Apache Archiva unit test" );
557 request.setMethod( webRequest.getHttpMethod().name() );
560 if (webRequest.getHttpMethod() == HttpMethod.PUT)
565 final MockHttpServletResponse response = execute( request );
566 return new WebResponse( null, null, 1 )
569 public String getContentAsString()
573 return response.getContentAsString();
575 catch ( UnsupportedEncodingException e )
577 throw new RuntimeException( e.getMessage(), e );
582 public int getStatusCode()
584 return response.getStatus();
589 protected MockHttpServletResponse execute( HttpServletRequest request )
592 MockHttpServletResponse response = new MockHttpServletResponse()
594 public String getContentAsString()
595 throws UnsupportedEncodingException
597 String errorMessage = getErrorMessage();
598 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
601 this.unauthenticatedRepositoryServlet.service( request, response );
605 public static class GetMethodWebRequest
610 public GetMethodWebRequest( String url )
613 super( new URL( url ) );
619 public static class PutMethodWebRequest
624 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
627 super( new URL( url ), HttpMethod.PUT );
634 public static class ServletUnitClient
637 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
639 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
641 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
644 public WebResponse getResponse( WebRequest request )
647 return abstractRepositoryServletTestCase.getWebResponse( request );
650 public WebResponse getResource( WebRequest request )
653 return getResponse( request );
657 public ServletUnitClient getServletUnitClient()
659 return new ServletUnitClient( this );
664 public void tearDown()
668 if ( repoRootInternal.exists() )
670 FileUtils.deleteDirectory( repoRootInternal );
673 if ( repoRootLegacy.exists() )
675 FileUtils.deleteDirectory( repoRootLegacy );
678 if ( this.tomcat != null )
686 protected void assertFileContents( String expectedContents, File repoRoot, String path )
689 File actualFile = new File( repoRoot, path );
690 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
691 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
692 actualFile.isFile() );
694 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
695 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
698 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
701 ManagedRepository repository = servlet.getRepository( repoId );
702 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
703 File repoRoot = new File( repository.getLocation() );
704 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
705 repoRoot.exists() && repoRoot.isDirectory() );
708 protected void assertResponseOK( WebResponse response )
711 assertNotNull( "Should have recieved a response", response );
712 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
713 response.getStatusCode() );
716 protected void assertResponseOK( WebResponse response, String path )
718 assertNotNull( "Should have recieved a response", response );
719 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
720 response.getStatusCode() );
723 protected void assertResponseNotFound( WebResponse response )
725 assertNotNull( "Should have recieved a response", response );
726 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
727 response.getStatusCode() );
730 protected void assertResponseInternalServerError( WebResponse response )
732 assertNotNull( "Should have recieved a response", response );
733 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
734 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
737 protected void assertResponseConflictError( WebResponse response )
739 assertNotNull( "Should have received a response", response );
740 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
741 response.getStatusCode() );
744 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
745 boolean blockRedeployments )
747 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
749 repo.setName( name );
750 repo.setLocation( location.getAbsolutePath() );
751 repo.setBlockRedeployments( blockRedeployments );
756 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
757 String layout, boolean blockRedeployments )
759 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
760 repo.setLayout( layout );
764 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
766 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
768 repo.setName( name );
773 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
776 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
780 protected void setupCleanRepo( File repoRootDir )
783 FileUtils.deleteDirectory( repoRootDir );
784 if ( !repoRootDir.exists() )
786 repoRootDir.mkdirs();
790 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
792 File repoFile = new File( repoRootInternal, resourcePath );
793 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
797 protected void setupCleanInternalRepo()
800 setupCleanRepo( repoRootInternal );
803 protected File populateRepo( File repoRootManaged, String path, String contents )
806 File destFile = new File( repoRootManaged, path );
807 destFile.getParentFile().mkdirs();
808 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );