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 //WebClient client = newClient();
518 //client.getPage( "http://localhost:" + port + "/reinit/reload" );
519 //return client.getPage( "http://localhost:" + port + path ).getWebResponse();
521 MockHttpServletRequest request = new MockHttpServletRequest();
522 request.setRequestURI( webRequest.getUrl().getPath() );
523 request.addHeader( "User-Agent", "Apache Archiva unit test" );
525 request.setMethod( webRequest.getHttpMethod().name() );
527 final MockHttpServletResponse response = execute( request );
529 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
530 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
532 String location = response.getHeader( "Location" );
533 log.debug("follow redirect to {}", location);
534 return getWebResponse( new GetMethodWebRequest( location ) );
537 return new WebResponse( null, null, 1 )
540 public String getContentAsString()
544 return response.getContentAsString();
546 catch ( UnsupportedEncodingException e )
548 throw new RuntimeException( e.getMessage(), e );
553 public int getStatusCode()
555 return response.getStatus();
560 protected MockHttpServletResponse execute( HttpServletRequest request )
563 MockHttpServletResponse response = new MockHttpServletResponse()
565 public String getContentAsString()
566 throws UnsupportedEncodingException
568 String errorMessage = getErrorMessage();
569 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
572 this.unauthenticatedRepositoryServlet.service( request, response );
576 public static class GetMethodWebRequest
581 public GetMethodWebRequest( String url )
584 super( new URL( url ) );
590 public static class PutMethodWebRequest
595 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
598 super( new URL( url ), HttpMethod.PUT );
605 public static class ServletUnitClient
608 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
610 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
612 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
615 public WebResponse getResponse( WebRequest request )
618 return getResponse( request, false );
621 public WebResponse getResponse( WebRequest request, boolean followRedirect )
624 // alwasy following redirect as it's normal
625 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
628 public WebResponse getResource( WebRequest request )
631 return getResponse( request );
635 public ServletUnitClient getServletUnitClient()
637 return new ServletUnitClient( this );
642 public void tearDown()
646 if ( repoRootInternal.exists() )
648 FileUtils.deleteDirectory( repoRootInternal );
651 if ( repoRootLegacy.exists() )
653 FileUtils.deleteDirectory( repoRootLegacy );
656 if ( this.tomcat != null )
664 protected void assertFileContents( String expectedContents, File repoRoot, String path )
667 File actualFile = new File( repoRoot, path );
668 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
669 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
670 actualFile.isFile() );
672 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
673 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
676 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
679 ManagedRepository repository = servlet.getRepository( repoId );
680 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
681 File repoRoot = new File( repository.getLocation() );
682 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
683 repoRoot.exists() && repoRoot.isDirectory() );
686 protected void assertResponseOK( WebResponse response )
689 assertNotNull( "Should have recieved a response", response );
690 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
691 response.getStatusCode() );
694 protected void assertResponseOK( WebResponse response, String path )
696 assertNotNull( "Should have recieved a response", response );
697 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
698 response.getStatusCode() );
701 protected void assertResponseNotFound( WebResponse response )
703 assertNotNull( "Should have recieved a response", response );
704 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
705 response.getStatusCode() );
708 protected void assertResponseInternalServerError( WebResponse response )
710 assertNotNull( "Should have recieved a response", response );
711 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
712 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
715 protected void assertResponseConflictError( WebResponse response )
717 assertNotNull( "Should have received a response", response );
718 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
719 response.getStatusCode() );
722 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
723 boolean blockRedeployments )
725 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
727 repo.setName( name );
728 repo.setLocation( location.getAbsolutePath() );
729 repo.setBlockRedeployments( blockRedeployments );
734 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
735 String layout, boolean blockRedeployments )
737 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
738 repo.setLayout( layout );
742 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
744 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
746 repo.setName( name );
751 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
754 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
758 protected void setupCleanRepo( File repoRootDir )
761 FileUtils.deleteDirectory( repoRootDir );
762 if ( !repoRootDir.exists() )
764 repoRootDir.mkdirs();
768 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
770 File repoFile = new File( repoRootInternal, resourcePath );
771 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
775 protected void setupCleanInternalRepo()
778 setupCleanRepo( repoRootInternal );
781 protected File populateRepo( File repoRootManaged, String path, String contents )
784 File destFile = new File( repoRootManaged, path );
785 destFile.getParentFile().mkdirs();
786 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );