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.httpunit.MkColMethodWebRequest;
38 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
39 import org.apache.catalina.core.StandardContext;
40 import org.apache.catalina.startup.Tomcat;
41 import org.apache.commons.io.FileUtils;
42 import org.apache.commons.io.IOUtils;
43 import org.junit.After;
44 import org.junit.Before;
45 import org.junit.runner.RunWith;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.BeansException;
49 import org.springframework.beans.factory.BeanFactory;
50 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
51 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
52 import org.springframework.context.ApplicationContext;
53 import org.springframework.context.ApplicationEvent;
54 import org.springframework.context.MessageSourceResolvable;
55 import org.springframework.context.NoSuchMessageException;
56 import org.springframework.core.env.Environment;
57 import org.springframework.core.io.Resource;
58 import org.springframework.mock.web.MockHttpServletRequest;
59 import org.springframework.mock.web.MockHttpServletResponse;
60 import org.springframework.mock.web.MockServletConfig;
61 import org.springframework.mock.web.MockServletContext;
62 import org.springframework.test.context.ContextConfiguration;
63 import org.springframework.web.context.WebApplicationContext;
65 import javax.inject.Inject;
66 import javax.servlet.Servlet;
67 import javax.servlet.ServletContext;
68 import javax.servlet.http.HttpServletRequest;
69 import javax.servlet.http.HttpServletResponse;
71 import java.io.IOException;
72 import java.io.InputStream;
73 import java.io.UnsupportedEncodingException;
74 import java.lang.annotation.Annotation;
76 import java.nio.charset.Charset;
77 import java.util.Locale;
81 * AbstractRepositoryServletTestCase
83 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
84 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:spring-context.xml",
85 "classpath*:/repository-servlet-simple.xml" } )
86 public abstract class AbstractRepositoryServletTestCase
89 protected static final String REPOID_INTERNAL = "internal";
91 protected static final String REPOID_LEGACY = "legacy";
93 protected File repoRootInternal;
95 protected File repoRootLegacy;
98 protected ArchivaConfiguration archivaConfiguration;
101 protected ApplicationContext applicationContext;
104 protected ManagedRepositoryAdmin managedRepositoryAdmin;
106 protected Logger log = LoggerFactory.getLogger( getClass() );
109 protected void saveConfiguration()
112 saveConfiguration( archivaConfiguration );
115 protected Tomcat tomcat;
117 protected static int port;
120 StandardContext context;
129 String appserverBase = new File( "target/appserver-base" ).getAbsolutePath();
130 System.setProperty( "appserver.base", appserverBase );
132 File testConf = new File( "src/test/resources/repository-archiva.xml" );
133 File testConfDest = new File( appserverBase, "conf/archiva.xml" );
134 if ( testConfDest.exists() )
136 FileUtils.deleteQuietly( testConfDest );
138 FileUtils.copyFile( testConf, testConfDest );
140 repoRootInternal = new File( appserverBase, "data/repositories/internal" );
141 repoRootLegacy = new File( appserverBase, "data/repositories/legacy" );
142 Configuration config = archivaConfiguration.getConfiguration();
144 config.getManagedRepositories().clear();
146 config.addManagedRepository(
147 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
149 managedRepositoryAdmin.createIndexContext( managedRepositoryAdmin.getManagedRepository( REPOID_INTERNAL ) );
151 config.addManagedRepository(
152 createManagedRepository( REPOID_LEGACY, "Legacy Format Test Repo", repoRootLegacy, "legacy", true ) );
154 config.getProxyConnectors().clear();
156 config.getRemoteRepositories().clear();
158 saveConfiguration( archivaConfiguration );
160 CacheManager.getInstance().clearAll();
162 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
167 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
168 new UnauthenticatedRepositoryServlet();
170 protected void startRepository()
174 final MockServletContext mockServletContext = new MockServletContext();
176 WebApplicationContext webApplicationContext =
177 new TestWebapplicationContext( applicationContext, mockServletContext );
179 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
180 webApplicationContext );
182 MockServletConfig mockServletConfig = new MockServletConfig()
185 public ServletContext getServletContext()
187 return mockServletContext;
191 unauthenticatedRepositoryServlet.init( mockServletConfig );
196 static class TestWebapplicationContext
197 implements WebApplicationContext
199 private ApplicationContext applicationContext;
201 private ServletContext servletContext;
203 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
205 this.applicationContext = applicationContext;
209 public ServletContext getServletContext()
211 return servletContext;
215 public String getId()
217 return applicationContext.getId();
221 public String getApplicationName()
223 return applicationContext.getApplicationName();
227 public String getDisplayName()
229 return applicationContext.getDisplayName();
233 public long getStartupDate()
235 return applicationContext.getStartupDate();
239 public ApplicationContext getParent()
241 return applicationContext.getParent();
245 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
246 throws IllegalStateException
248 return applicationContext.getAutowireCapableBeanFactory();
252 public void publishEvent( ApplicationEvent applicationEvent )
254 applicationContext.publishEvent( applicationEvent );
258 public Environment getEnvironment()
260 return applicationContext.getEnvironment();
264 public BeanFactory getParentBeanFactory()
266 return applicationContext.getParentBeanFactory();
270 public boolean containsLocalBean( String s )
272 return applicationContext.containsLocalBean( s );
276 public boolean containsBeanDefinition( String s )
278 return applicationContext.containsBeanDefinition( s );
282 public int getBeanDefinitionCount()
284 return applicationContext.getBeanDefinitionCount();
288 public String[] getBeanDefinitionNames()
290 return applicationContext.getBeanDefinitionNames();
294 public String[] getBeanNamesForType( Class<?> aClass )
296 return applicationContext.getBeanNamesForType( aClass );
300 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
302 return applicationContext.getBeanNamesForType( aClass, b, b2 );
306 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
307 throws BeansException
309 return applicationContext.getBeansOfType( tClass );
313 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
314 throws BeansException
316 return applicationContext.getBeansOfType( tClass, b, b2 );
320 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
322 return applicationContext.getBeanNamesForAnnotation( aClass );
326 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
327 throws BeansException
329 return applicationContext.getBeansWithAnnotation( aClass );
333 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
334 throws NoSuchBeanDefinitionException
336 return applicationContext.findAnnotationOnBean( s, aClass );
340 public Object getBean( String s )
341 throws BeansException
343 return applicationContext.getBean( s );
347 public <T> T getBean( String s, Class<T> tClass )
348 throws BeansException
350 return applicationContext.getBean( s, tClass );
354 public <T> T getBean( Class<T> tClass )
355 throws BeansException
357 return applicationContext.getBean( tClass );
361 public Object getBean( String s, Object... objects )
362 throws BeansException
364 return applicationContext.getBean( s, objects );
368 public boolean containsBean( String s )
370 return applicationContext.containsBean( s );
374 public boolean isSingleton( String s )
375 throws NoSuchBeanDefinitionException
377 return applicationContext.isSingleton( s );
381 public boolean isPrototype( String s )
382 throws NoSuchBeanDefinitionException
384 return applicationContext.isPrototype( s );
388 public boolean isTypeMatch( String s, Class<?> aClass )
389 throws NoSuchBeanDefinitionException
391 return applicationContext.isTypeMatch( s, aClass );
395 public Class<?> getType( String s )
396 throws NoSuchBeanDefinitionException
398 return applicationContext.getType( s );
402 public String[] getAliases( String s )
404 return applicationContext.getAliases( s );
408 public String getMessage( String s, Object[] objects, String s2, Locale locale )
410 return applicationContext.getMessage( s, objects, s2, locale );
414 public String getMessage( String s, Object[] objects, Locale locale )
415 throws NoSuchMessageException
417 return applicationContext.getMessage( s, objects, locale );
421 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
422 throws NoSuchMessageException
424 return applicationContext.getMessage( messageSourceResolvable, locale );
428 public Resource[] getResources( String s )
431 return applicationContext.getResources( s );
435 public Resource getResource( String s )
437 return applicationContext.getResource( s );
441 public ClassLoader getClassLoader()
443 return applicationContext.getClassLoader();
447 protected Servlet findServlet( String name )
450 return unauthenticatedRepositoryServlet;
452 Container[] childs = context.findChildren();
453 for ( Container container : childs )
455 if ( StringUtils.equals( container.getName(), name ) )
457 Tomcat.ExistingStandardWrapper esw = Tomcat.ExistingStandardWrapper.class.cast( container );
458 Servlet servlet = esw.loadServlet();
466 protected String getSpringConfigLocation()
468 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
475 protected ServletUnitClient getServletUnitClient()
478 if ( servletUnitClient != null )
480 return servletUnitClient;
482 servletRunner = new ServletRunner( new File( "src/test/resources/WEB-INF/web.xml" ) );
484 servletRunner.registerServlet( "/repository/*", UnauthenticatedRepositoryServlet.class.getName() );
486 servletUnitClient = servletRunner.newClient();
488 return servletUnitClient;
492 protected <P extends Page> P page(final String path) throws IOException {
493 return newClient().getPage(base.toExternalForm() + "repository/" + path);
497 protected static WebClient newClient()
499 final WebClient webClient = new WebClient();
500 webClient.getOptions().setJavaScriptEnabled( false );
501 webClient.getOptions().setCssEnabled( false );
502 webClient.getOptions().setAppletEnabled( false );
503 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
504 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
509 protected WebResponse getWebResponse( String path )
512 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
515 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
519 MockHttpServletRequest request = new MockHttpServletRequest();
520 request.setRequestURI( webRequest.getUrl().getPath() );
521 request.addHeader( "User-Agent", "Apache Archiva unit test" );
523 request.setMethod( webRequest.getHttpMethod().name() );
525 if (webRequest.getHttpMethod() == HttpMethod.PUT )
527 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
528 request.setContentType( putRequest.contentType );
529 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
532 if ( webRequest instanceof MkColMethodWebRequest )
534 request.setMethod( "MKCOL" );
537 final MockHttpServletResponse response = execute( request );
539 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
540 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
542 String location = response.getHeader( "Location" );
543 log.debug("follow redirect to {}", location);
544 return getWebResponse( new GetMethodWebRequest( location ) );
547 return new WebResponse( null, null, 1 )
550 public String getContentAsString()
554 return response.getContentAsString();
556 catch ( UnsupportedEncodingException e )
558 throw new RuntimeException( e.getMessage(), e );
563 public int getStatusCode()
565 return response.getStatus();
569 public String getResponseHeaderValue( String headerName )
571 return response.getHeader( headerName );
576 protected MockHttpServletResponse execute( HttpServletRequest request )
579 MockHttpServletResponse response = new MockHttpServletResponse()
581 public String getContentAsString()
582 throws UnsupportedEncodingException
584 String errorMessage = getErrorMessage();
585 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
588 this.unauthenticatedRepositoryServlet.service( request, response );
592 public static class GetMethodWebRequest
597 public GetMethodWebRequest( String url )
600 super( new URL( url ) );
606 public static class PutMethodWebRequest
611 InputStream inputStream;
615 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
618 super( new URL( url ), HttpMethod.PUT );
620 this.inputStream = inputStream;
621 this.contentType = contentType;
627 public static class ServletUnitClient
630 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
632 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
634 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
637 public WebResponse getResponse( WebRequest request )
640 return getResponse( request, false );
643 public WebResponse getResponse( WebRequest request, boolean followRedirect )
646 // alwasy following redirect as it's normal
647 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
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() );