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.TestCase;
28 import net.sf.ehcache.CacheManager;
29 import org.apache.archiva.admin.model.beans.ManagedRepository;
30 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
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.httpunit.MkColMethodWebRequest;
37 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
38 import org.apache.commons.io.FileUtils;
39 import org.apache.commons.io.IOUtils;
40 import org.junit.After;
41 import org.junit.Assert;
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 );
121 String appserverBase = new File( "target/appserver-base" ).getAbsolutePath();
122 System.setProperty( "appserver.base", appserverBase );
124 File testConf = new File( "src/test/resources/repository-archiva.xml" );
125 File testConfDest = new File( appserverBase, "conf/archiva.xml" );
126 if ( testConfDest.exists() )
128 FileUtils.deleteQuietly( testConfDest );
130 FileUtils.copyFile( testConf, testConfDest );
132 repoRootInternal = new File( appserverBase, "data/repositories/internal" );
133 repoRootLegacy = new File( appserverBase, "data/repositories/legacy" );
134 Configuration config = archivaConfiguration.getConfiguration();
136 config.getManagedRepositories().clear();
138 config.addManagedRepository(
139 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
141 managedRepositoryAdmin.createIndexContext( managedRepositoryAdmin.getManagedRepository( REPOID_INTERNAL ) );
143 config.addManagedRepository(
144 createManagedRepository( REPOID_LEGACY, "Legacy Format Test Repo", repoRootLegacy, "legacy", true ) );
146 config.getProxyConnectors().clear();
148 config.getRemoteRepositories().clear();
150 saveConfiguration( archivaConfiguration );
152 CacheManager.getInstance().clearAll();
154 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
159 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
160 new UnauthenticatedRepositoryServlet();
162 protected void startRepository()
166 final MockServletContext mockServletContext = new MockServletContext();
168 WebApplicationContext webApplicationContext =
169 new TestWebapplicationContext( applicationContext, mockServletContext );
171 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
172 webApplicationContext );
174 MockServletConfig mockServletConfig = new MockServletConfig()
177 public ServletContext getServletContext()
179 return mockServletContext;
183 unauthenticatedRepositoryServlet.init( mockServletConfig );
188 public static class TestWebapplicationContext
189 implements WebApplicationContext
191 private ApplicationContext applicationContext;
193 private ServletContext servletContext;
195 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
197 this.applicationContext = applicationContext;
201 public ServletContext getServletContext()
203 return servletContext;
207 public String getId()
209 return applicationContext.getId();
213 public String getApplicationName()
215 return applicationContext.getApplicationName();
219 public String getDisplayName()
221 return applicationContext.getDisplayName();
225 public long getStartupDate()
227 return applicationContext.getStartupDate();
231 public ApplicationContext getParent()
233 return applicationContext.getParent();
237 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
238 throws IllegalStateException
240 return applicationContext.getAutowireCapableBeanFactory();
244 public void publishEvent( ApplicationEvent applicationEvent )
246 applicationContext.publishEvent( applicationEvent );
250 public Environment getEnvironment()
252 return applicationContext.getEnvironment();
256 public BeanFactory getParentBeanFactory()
258 return applicationContext.getParentBeanFactory();
262 public boolean containsLocalBean( String s )
264 return applicationContext.containsLocalBean( s );
268 public boolean containsBeanDefinition( String s )
270 return applicationContext.containsBeanDefinition( s );
274 public int getBeanDefinitionCount()
276 return applicationContext.getBeanDefinitionCount();
280 public String[] getBeanDefinitionNames()
282 return applicationContext.getBeanDefinitionNames();
286 public String[] getBeanNamesForType( Class<?> aClass )
288 return applicationContext.getBeanNamesForType( aClass );
292 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
294 return applicationContext.getBeanNamesForType( aClass, b, b2 );
298 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
299 throws BeansException
301 return applicationContext.getBeansOfType( tClass );
305 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
306 throws BeansException
308 return applicationContext.getBeansOfType( tClass, b, b2 );
312 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
314 return applicationContext.getBeanNamesForAnnotation( aClass );
318 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
319 throws BeansException
321 return applicationContext.getBeansWithAnnotation( aClass );
325 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
326 throws NoSuchBeanDefinitionException
328 return applicationContext.findAnnotationOnBean( s, aClass );
332 public <T> T getBean( Class<T> aClass, Object... objects )
333 throws BeansException
335 return applicationContext.getBean( aClass, objects );
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 ) );//, false );
514 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
518 MockHttpServletRequest request = new MockHttpServletRequest();
519 request.setRequestURI( webRequest.getUrl().getPath() );
520 request.addHeader( "User-Agent", "Apache Archiva unit test" );
522 request.setMethod( webRequest.getHttpMethod().name() );
524 if (webRequest.getHttpMethod() == HttpMethod.PUT )
526 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
527 request.setContentType( putRequest.contentType );
528 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
531 if ( webRequest instanceof MkColMethodWebRequest )
533 request.setMethod( "MKCOL" );
536 final MockHttpServletResponse response = execute( request );
538 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
539 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
541 String location = response.getHeader( "Location" );
542 log.debug("follow redirect to {}", location);
543 return getWebResponse( new GetMethodWebRequest( location ) );
546 return new WebResponse( null, null, 1 )
549 public String getContentAsString()
553 return response.getContentAsString();
555 catch ( UnsupportedEncodingException e )
557 throw new RuntimeException( e.getMessage(), e );
562 public int getStatusCode()
564 return response.getStatus();
568 public String getResponseHeaderValue( String headerName )
570 return response.getHeader( headerName );
575 protected MockHttpServletResponse execute( HttpServletRequest request )
578 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 );
681 protected void assertFileContents( String expectedContents, File repoRoot, String path )
684 File actualFile = new File( repoRoot, path );
685 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should exist.", actualFile.exists() );
686 assertTrue( "File <" + actualFile.getAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
687 actualFile.isFile() );
689 String actualContents = FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
690 assertEquals( "File Contents of <" + actualFile.getAbsolutePath() + ">", expectedContents, actualContents );
693 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
696 ManagedRepository repository = servlet.getRepository( repoId );
697 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
698 File repoRoot = new File( repository.getLocation() );
699 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
700 repoRoot.exists() && repoRoot.isDirectory() );
703 protected void assertResponseOK( WebResponse response )
706 assertNotNull( "Should have recieved a response", response );
707 Assert.assertEquals( "Should have been an OK response code", HttpServletResponse.SC_OK,
708 response.getStatusCode() );
711 protected void assertResponseOK( WebResponse response, String path )
713 assertNotNull( "Should have recieved a response", response );
714 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
715 response.getStatusCode() );
718 protected void assertResponseNotFound( WebResponse response )
720 assertNotNull( "Should have recieved a response", response );
721 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
722 response.getStatusCode() );
725 protected void assertResponseInternalServerError( WebResponse response )
727 assertNotNull( "Should have recieved a response", response );
728 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
729 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
732 protected void assertResponseConflictError( WebResponse response )
734 assertNotNull( "Should have received a response", response );
735 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
736 response.getStatusCode() );
739 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
740 boolean blockRedeployments )
742 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
744 repo.setName( name );
745 repo.setLocation( location.getAbsolutePath() );
746 repo.setBlockRedeployments( blockRedeployments );
751 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location,
752 String layout, boolean blockRedeployments )
754 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
755 repo.setLayout( layout );
759 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
761 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
763 repo.setName( name );
768 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
771 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
775 protected void setupCleanRepo( File repoRootDir )
778 FileUtils.deleteDirectory( repoRootDir );
779 if ( !repoRootDir.exists() )
781 repoRootDir.mkdirs();
785 protected void assertManagedFileNotExists( File repoRootInternal, String resourcePath )
787 File repoFile = new File( repoRootInternal, resourcePath );
788 assertFalse( "Managed Repository File <" + repoFile.getAbsolutePath() + "> should not exist.",
792 protected void setupCleanInternalRepo()
795 setupCleanRepo( repoRootInternal );
798 protected File populateRepo( File repoRootManaged, String path, String contents )
801 File destFile = new File( repoRootManaged, path );
802 destFile.getParentFile().mkdirs();
803 FileUtils.writeStringToFile( destFile, contents, Charset.defaultCharset() );