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 );
139 repoRootInternal = new File( appserverBase, "data/repositories/internal" );
140 repoRootLegacy = new File( appserverBase, "data/repositories/legacy" );
141 Configuration config = archivaConfiguration.getConfiguration();
143 config.getManagedRepositories().clear();
145 config.addManagedRepository(
146 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
148 managedRepositoryAdmin.createIndexContext( managedRepositoryAdmin.getManagedRepository( REPOID_INTERNAL ) );
150 config.addManagedRepository(
151 createManagedRepository( REPOID_LEGACY, "Legacy Format Test Repo", repoRootLegacy, "legacy", true ) );
153 config.getProxyConnectors().clear();
155 config.getRemoteRepositories().clear();
157 saveConfiguration( archivaConfiguration );
159 CacheManager.getInstance().clearAll();
161 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
166 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
167 new UnauthenticatedRepositoryServlet();
169 protected void startRepository()
173 final MockServletContext mockServletContext = new MockServletContext();
175 WebApplicationContext webApplicationContext =
176 new TestWebapplicationContext( applicationContext, mockServletContext );
178 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
179 webApplicationContext );
181 MockServletConfig mockServletConfig = new MockServletConfig()
184 public ServletContext getServletContext()
186 return mockServletContext;
190 unauthenticatedRepositoryServlet.init( mockServletConfig );
195 static class TestWebapplicationContext
196 implements WebApplicationContext
198 private ApplicationContext applicationContext;
200 private ServletContext servletContext;
202 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
204 this.applicationContext = applicationContext;
208 public ServletContext getServletContext()
210 return servletContext;
214 public String getId()
216 return applicationContext.getId();
220 public String getApplicationName()
222 return applicationContext.getApplicationName();
226 public String getDisplayName()
228 return applicationContext.getDisplayName();
232 public long getStartupDate()
234 return applicationContext.getStartupDate();
238 public ApplicationContext getParent()
240 return applicationContext.getParent();
244 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
245 throws IllegalStateException
247 return applicationContext.getAutowireCapableBeanFactory();
251 public void publishEvent( ApplicationEvent applicationEvent )
253 applicationContext.publishEvent( applicationEvent );
257 public Environment getEnvironment()
259 return applicationContext.getEnvironment();
263 public BeanFactory getParentBeanFactory()
265 return applicationContext.getParentBeanFactory();
269 public boolean containsLocalBean( String s )
271 return applicationContext.containsLocalBean( s );
275 public boolean containsBeanDefinition( String s )
277 return applicationContext.containsBeanDefinition( s );
281 public int getBeanDefinitionCount()
283 return applicationContext.getBeanDefinitionCount();
287 public String[] getBeanDefinitionNames()
289 return applicationContext.getBeanDefinitionNames();
293 public String[] getBeanNamesForType( Class<?> aClass )
295 return applicationContext.getBeanNamesForType( aClass );
299 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
301 return applicationContext.getBeanNamesForType( aClass, b, b2 );
305 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
306 throws BeansException
308 return applicationContext.getBeansOfType( tClass );
312 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
313 throws BeansException
315 return applicationContext.getBeansOfType( tClass, b, b2 );
319 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
321 return applicationContext.getBeanNamesForAnnotation( aClass );
325 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
326 throws BeansException
328 return applicationContext.getBeansWithAnnotation( aClass );
332 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
333 throws NoSuchBeanDefinitionException
335 return applicationContext.findAnnotationOnBean( s, aClass );
339 public Object getBean( String s )
340 throws BeansException
342 return applicationContext.getBean( s );
346 public <T> T getBean( String s, Class<T> tClass )
347 throws BeansException
349 return applicationContext.getBean( s, tClass );
353 public <T> T getBean( Class<T> tClass )
354 throws BeansException
356 return applicationContext.getBean( tClass );
360 public Object getBean( String s, Object... objects )
361 throws BeansException
363 return applicationContext.getBean( s, objects );
367 public boolean containsBean( String s )
369 return applicationContext.containsBean( s );
373 public boolean isSingleton( String s )
374 throws NoSuchBeanDefinitionException
376 return applicationContext.isSingleton( s );
380 public boolean isPrototype( String s )
381 throws NoSuchBeanDefinitionException
383 return applicationContext.isPrototype( s );
387 public boolean isTypeMatch( String s, Class<?> aClass )
388 throws NoSuchBeanDefinitionException
390 return applicationContext.isTypeMatch( s, aClass );
394 public Class<?> getType( String s )
395 throws NoSuchBeanDefinitionException
397 return applicationContext.getType( s );
401 public String[] getAliases( String s )
403 return applicationContext.getAliases( s );
407 public String getMessage( String s, Object[] objects, String s2, Locale locale )
409 return applicationContext.getMessage( s, objects, s2, locale );
413 public String getMessage( String s, Object[] objects, Locale locale )
414 throws NoSuchMessageException
416 return applicationContext.getMessage( s, objects, locale );
420 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
421 throws NoSuchMessageException
423 return applicationContext.getMessage( messageSourceResolvable, locale );
427 public Resource[] getResources( String s )
430 return applicationContext.getResources( s );
434 public Resource getResource( String s )
436 return applicationContext.getResource( s );
440 public ClassLoader getClassLoader()
442 return applicationContext.getClassLoader();
446 protected Servlet findServlet( String name )
449 return unauthenticatedRepositoryServlet;
451 Container[] childs = context.findChildren();
452 for ( Container container : childs )
454 if ( StringUtils.equals( container.getName(), name ) )
456 Tomcat.ExistingStandardWrapper esw = Tomcat.ExistingStandardWrapper.class.cast( container );
457 Servlet servlet = esw.loadServlet();
465 protected String getSpringConfigLocation()
467 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
474 protected ServletUnitClient getServletUnitClient()
477 if ( servletUnitClient != null )
479 return servletUnitClient;
481 servletRunner = new ServletRunner( new File( "src/test/resources/WEB-INF/web.xml" ) );
483 servletRunner.registerServlet( "/repository/*", UnauthenticatedRepositoryServlet.class.getName() );
485 servletUnitClient = servletRunner.newClient();
487 return servletUnitClient;
491 protected <P extends Page> P page(final String path) throws IOException {
492 return newClient().getPage(base.toExternalForm() + "repository/" + path);
496 protected static WebClient newClient()
498 final WebClient webClient = new WebClient();
499 webClient.getOptions().setJavaScriptEnabled( false );
500 webClient.getOptions().setCssEnabled( false );
501 webClient.getOptions().setAppletEnabled( false );
502 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
503 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
508 protected WebResponse getWebResponse( String path )
511 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );
514 protected WebResponse getWebResponse( WebRequest webRequest )
518 //WebClient client = newClient();
519 //client.getPage( "http://localhost:" + port + "/reinit/reload" );
520 //return client.getPage( "http://localhost:" + port + path ).getWebResponse();
522 MockHttpServletRequest request = new MockHttpServletRequest();
523 request.setRequestURI( webRequest.getUrl().getPath() );
524 request.addHeader( "User-Agent", "Apache Archiva unit test" );
526 request.setMethod( webRequest.getHttpMethod().name() );
528 final MockHttpServletResponse response = execute( request );
530 return new WebResponse( null, null, 1 )
533 public String getContentAsString()
537 return response.getContentAsString();
539 catch ( UnsupportedEncodingException e )
541 throw new RuntimeException( e.getMessage(), e );
546 public int getStatusCode()
548 return response.getStatus();
553 protected MockHttpServletResponse execute( HttpServletRequest request )
556 MockHttpServletResponse response = new MockHttpServletResponse()
558 public String getContentAsString()
559 throws UnsupportedEncodingException
561 String errorMessage = getErrorMessage();
562 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
565 this.unauthenticatedRepositoryServlet.service( request, response );
569 public static class GetMethodWebRequest
574 public GetMethodWebRequest( String url )
577 super( new URL( url ) );
583 public static class PutMethodWebRequest
588 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
591 super( new URL( url ), HttpMethod.PUT );
598 public static class ServletUnitClient
601 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
603 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
605 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
608 public WebResponse getResponse( WebRequest request )
611 return abstractRepositoryServletTestCase.getWebResponse( request );
614 public WebResponse getResource( WebRequest request )
617 return getResponse( request );
621 public ServletUnitClient getServletUnitClient()
623 return new ServletUnitClient( this );
628 public void tearDown()
632 if ( repoRootInternal.exists() )
634 FileUtils.deleteDirectory( repoRootInternal );
637 if ( repoRootLegacy.exists() )
639 FileUtils.deleteDirectory( repoRootLegacy );
642 if ( this.tomcat != null )
650 protected void assertFileContents( String expectedContents, File repoRoot, String path )
653 File actualFile = new File( repoRoot, path );
654 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
655 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
656 actualFile.isFile() );
658 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
659 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
662 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
665 ManagedRepository repository = servlet.getRepository( repoId );
666 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
667 File repoRoot = new File( repository.getLocation() );
668 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
669 repoRoot.exists() && repoRoot.isDirectory() );
672 protected void assertResponseOK( WebResponse response )
675 assertNotNull( "Should have recieved a response", response );
676 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
677 response.getStatusCode() );
680 protected void assertResponseOK( WebResponse response, String path )
682 assertNotNull( "Should have recieved a response", response );
683 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
684 response.getStatusCode() );
687 protected void assertResponseNotFound( WebResponse response )
689 assertNotNull( "Should have recieved a response", response );
690 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
691 response.getStatusCode() );
694 protected void assertResponseInternalServerError( WebResponse response )
696 assertNotNull( "Should have recieved a response", response );
697 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
698 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
701 protected void assertResponseConflictError( WebResponse response )
703 assertNotNull( "Should have received a response", response );
704 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
705 response.getStatusCode() );
708 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
709 boolean blockRedeployments )
711 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
713 repo.setName( name );
714 repo.setLocation( location.getAbsolutePath() );
715 repo.setBlockRedeployments( blockRedeployments );
720 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
721 String layout, boolean blockRedeployments )
723 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
724 repo.setLayout( layout );
728 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
730 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
732 repo.setName( name );
737 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
740 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
744 protected void setupCleanRepo( File repoRootDir )
747 FileUtils.deleteDirectory( repoRootDir );
748 if ( !repoRootDir.exists() )
750 repoRootDir.mkdirs();
754 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
756 File repoFile = new File( repoRootInternal, resourcePath );
757 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
761 protected void setupCleanInternalRepo()
764 setupCleanRepo( repoRootInternal );
767 protected File populateRepo( File repoRootManaged, String path, String contents )
770 File destFile = new File( repoRootManaged, path );
771 destFile.getParentFile().mkdirs();
772 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );