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 )
543 //WebClient client = newClient();
544 //client.getPage( "http://localhost:" + port + "/reinit/reload" );
545 //return client.getPage( "http://localhost:" + port + path ).getWebResponse();
547 MockHttpServletRequest request = new MockHttpServletRequest();
548 request.setRequestURI( path );
549 request.addHeader( "User-Agent", "Apache Archiva unit test" );
550 request.setMethod( "GET" );
551 final MockHttpServletResponse response = execute( request );
552 return new WebResponse( null, null, 1 )
555 public String getContentAsString()
559 return response.getContentAsString();
561 catch ( UnsupportedEncodingException e )
563 throw new RuntimeException( e.getMessage(), e );
568 public int getStatusCode()
570 return response.getStatus();
575 protected MockHttpServletResponse execute( HttpServletRequest request )
578 MockHttpServletResponse response = new MockHttpServletResponse()
580 public String getContentAsString()
581 throws UnsupportedEncodingException
583 String errorMessage = getErrorMessage();
584 return ( errorMessage != null ) ? errorMessage: super.getContentAsString();
587 this.unauthenticatedRepositoryServlet.service( request, response );
591 public static class GetMethodWebRequest
596 public GetMethodWebRequest( String url )
599 super( new URL( url ) );
605 public static class PutMethodWebRequest
610 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
613 super( new URL( url ), HttpMethod.PUT );
621 public static class ServletUnitClient
624 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
626 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
628 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
631 public WebResponse getResponse( WebRequest request )
634 return abstractRepositoryServletTestCase.getWebResponse( request.getUrl().getPath() );
637 public WebResponse getResource( WebRequest request )
640 return getResponse( request );
644 public ServletUnitClient getServletUnitClient()
646 return new ServletUnitClient( this );
651 public void tearDown()
655 if ( repoRootInternal.exists() )
657 FileUtils.deleteDirectory( repoRootInternal );
660 if ( repoRootLegacy.exists() )
662 FileUtils.deleteDirectory( repoRootLegacy );
665 if ( this.tomcat != null )
673 protected void assertFileContents( String expectedContents, File repoRoot, String path )
676 File actualFile = new File( repoRoot, path );
677 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
678 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
679 actualFile.isFile() );
681 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
682 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
685 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
688 ManagedRepository repository = servlet.getRepository( repoId );
689 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
690 File repoRoot = new File( repository.getLocation() );
691 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
692 repoRoot.exists() && repoRoot.isDirectory() );
695 protected void assertResponseOK( WebResponse response )
698 assertNotNull( "Should have recieved a response", response );
699 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
700 response.getStatusCode() );
703 protected void assertResponseOK( WebResponse response, String path )
705 assertNotNull( "Should have recieved a response", response );
706 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
707 response.getStatusCode() );
710 protected void assertResponseNotFound( WebResponse response )
712 assertNotNull( "Should have recieved a response", response );
713 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
714 response.getStatusCode() );
717 protected void assertResponseInternalServerError( WebResponse response )
719 assertNotNull( "Should have recieved a response", response );
720 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
721 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
724 protected void assertResponseConflictError( WebResponse response )
726 assertNotNull( "Should have received a response", response );
727 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
728 response.getStatusCode() );
731 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
732 boolean blockRedeployments )
734 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
736 repo.setName( name );
737 repo.setLocation( location.getAbsolutePath() );
738 repo.setBlockRedeployments( blockRedeployments );
743 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
744 String layout, boolean blockRedeployments )
746 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
747 repo.setLayout( layout );
751 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
753 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
755 repo.setName( name );
760 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
763 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
767 protected void setupCleanRepo( File repoRootDir )
770 FileUtils.deleteDirectory( repoRootDir );
771 if ( !repoRootDir.exists() )
773 repoRootDir.mkdirs();
777 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
779 File repoFile = new File( repoRootInternal, resourcePath );
780 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
784 protected void setupCleanInternalRepo()
787 setupCleanRepo( repoRootInternal );
790 protected File populateRepo( File repoRootManaged, String path, String contents )
793 File destFile = new File( repoRootManaged, path );
794 destFile.getParentFile().mkdirs();
795 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );