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.*;
23 import junit.framework.TestCase;
24 import net.sf.ehcache.CacheManager;
25 import org.apache.archiva.admin.model.beans.ManagedRepository;
26 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
27 import org.apache.archiva.configuration.ArchivaConfiguration;
28 import org.apache.archiva.configuration.Configuration;
29 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
30 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
31 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
32 import org.apache.archiva.webdav.httpunit.MkColMethodWebRequest;
33 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
34 import org.apache.commons.io.FileUtils;
35 import org.apache.commons.io.IOUtils;
36 import org.apache.commons.lang.StringUtils;
37 import org.junit.After;
38 import org.junit.Assert;
39 import org.junit.Before;
40 import org.junit.runner.RunWith;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.BeansException;
44 import org.springframework.beans.factory.BeanFactory;
45 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
46 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
47 import org.springframework.context.ApplicationContext;
48 import org.springframework.context.ApplicationEvent;
49 import org.springframework.context.MessageSourceResolvable;
50 import org.springframework.context.NoSuchMessageException;
51 import org.springframework.core.ResolvableType;
52 import org.springframework.core.env.Environment;
53 import org.springframework.core.io.Resource;
54 import org.springframework.mock.web.MockHttpServletRequest;
55 import org.springframework.mock.web.MockHttpServletResponse;
56 import org.springframework.mock.web.MockServletConfig;
57 import org.springframework.mock.web.MockServletContext;
58 import org.springframework.test.context.ContextConfiguration;
59 import org.springframework.web.context.WebApplicationContext;
61 import javax.inject.Inject;
62 import javax.servlet.Servlet;
63 import javax.servlet.ServletContext;
64 import javax.servlet.http.HttpServletRequest;
65 import javax.servlet.http.HttpServletResponse;
66 import java.io.IOException;
67 import java.io.InputStream;
68 import java.io.UnsupportedEncodingException;
69 import java.lang.annotation.Annotation;
71 import java.nio.charset.Charset;
72 import java.nio.file.Files;
73 import java.nio.file.Path;
74 import java.nio.file.Paths;
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 Path repoRootInternal;
91 protected Path repoRootLegacy;
94 protected ArchivaConfiguration archivaConfiguration;
97 protected ApplicationContext applicationContext;
100 protected ManagedRepositoryAdmin managedRepositoryAdmin;
102 protected Logger log = LoggerFactory.getLogger( getClass() );
105 protected void saveConfiguration()
108 saveConfiguration( archivaConfiguration );
119 String appserverBase = Paths.get( "target/appserver-base" ).toAbsolutePath().toString();
120 System.setProperty( "appserver.base", appserverBase );
122 Path testConf = Paths.get( "src/test/resources/repository-archiva.xml" );
123 Path testConfDest = Paths.get(appserverBase, "conf/archiva.xml" );
124 if ( Files.exists(testConfDest) )
126 org.apache.archiva.common.utils.FileUtils.deleteQuietly( testConfDest );
128 FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
130 repoRootInternal = Paths.get( appserverBase, "data/repositories/internal" );
131 repoRootLegacy = Paths.get( appserverBase, "data/repositories/legacy" );
132 Configuration config = archivaConfiguration.getConfiguration();
134 config.getManagedRepositories().clear();
136 config.addManagedRepository(
137 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
139 managedRepositoryAdmin.createIndexContext( managedRepositoryAdmin.getManagedRepository( REPOID_INTERNAL ) );
141 config.getProxyConnectors().clear();
143 config.getRemoteRepositories().clear();
145 saveConfiguration( archivaConfiguration );
147 CacheManager.getInstance().clearAll();
149 applicationContext.getBean( MavenIndexerCleaner.class ).cleanupIndex();
154 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
155 new UnauthenticatedRepositoryServlet();
157 protected void startRepository()
161 final MockServletContext mockServletContext = new MockServletContext();
163 WebApplicationContext webApplicationContext =
164 new TestWebapplicationContext( applicationContext, mockServletContext );
166 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
167 webApplicationContext );
169 MockServletConfig mockServletConfig = new MockServletConfig()
172 public ServletContext getServletContext()
174 return mockServletContext;
178 unauthenticatedRepositoryServlet.init( mockServletConfig );
182 protected String createVersionMetadata(String groupId, String artifactId, String version) {
183 return createVersionMetadata(groupId, artifactId, version, null, null, null);
186 protected String createVersionMetadata(String groupId, String artifactId, String version, String timestamp, String buildNumber, String lastUpdated) {
187 StringBuilder buf = new StringBuilder();
188 buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
189 buf.append("<metadata>\n");
190 buf.append(" <groupId>").append(groupId).append("</groupId>\n");
191 buf.append(" <artifactId>").append(artifactId).append("</artifactId>\n");
192 buf.append(" <version>").append(version).append("</version>\n");
193 boolean hasSnapshot = StringUtils.isNotBlank(timestamp) || StringUtils.isNotBlank(buildNumber);
194 boolean hasLastUpdated = StringUtils.isNotBlank(lastUpdated);
195 if (hasSnapshot || hasLastUpdated) {
196 buf.append(" <versioning>\n");
198 buf.append(" <snapshot>\n");
199 buf.append(" <buildNumber>").append(buildNumber).append("</buildNumber>\n");
200 buf.append(" <timestamp>").append(timestamp).append("</timestamp>\n");
201 buf.append(" </snapshot>\n");
203 if (hasLastUpdated) {
204 buf.append(" <lastUpdated>").append(lastUpdated).append("</lastUpdated>\n");
206 buf.append(" </versioning>\n");
208 buf.append("</metadata>");
209 return buf.toString();
213 public static class TestWebapplicationContext
214 implements WebApplicationContext
216 private ApplicationContext applicationContext;
218 private ServletContext servletContext;
220 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
222 this.applicationContext = applicationContext;
226 public ServletContext getServletContext()
228 return servletContext;
232 public String getId()
234 return applicationContext.getId();
238 public String getApplicationName()
240 return applicationContext.getApplicationName();
244 public String getDisplayName()
246 return applicationContext.getDisplayName();
250 public long getStartupDate()
252 return applicationContext.getStartupDate();
256 public ApplicationContext getParent()
258 return applicationContext.getParent();
262 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
263 throws IllegalStateException
265 return applicationContext.getAutowireCapableBeanFactory();
269 public void publishEvent( ApplicationEvent applicationEvent )
271 applicationContext.publishEvent( applicationEvent );
275 public Environment getEnvironment()
277 return applicationContext.getEnvironment();
281 public BeanFactory getParentBeanFactory()
283 return applicationContext.getParentBeanFactory();
287 public boolean containsLocalBean( String s )
289 return applicationContext.containsLocalBean( s );
293 public boolean containsBeanDefinition( String s )
295 return applicationContext.containsBeanDefinition( s );
299 public int getBeanDefinitionCount()
301 return applicationContext.getBeanDefinitionCount();
305 public String[] getBeanDefinitionNames()
307 return applicationContext.getBeanDefinitionNames();
311 public String[] getBeanNamesForType( Class<?> aClass )
313 return applicationContext.getBeanNamesForType( aClass );
317 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
319 return applicationContext.getBeanNamesForType( aClass, b, b2 );
323 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
324 throws BeansException
326 return applicationContext.getBeansOfType( tClass );
330 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
331 throws BeansException
333 return applicationContext.getBeansOfType( tClass, b, b2 );
337 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
339 return applicationContext.getBeanNamesForAnnotation( aClass );
343 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
344 throws BeansException
346 return applicationContext.getBeansWithAnnotation( aClass );
350 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
351 throws NoSuchBeanDefinitionException
353 return applicationContext.findAnnotationOnBean( s, aClass );
357 public <T> T getBean( Class<T> aClass, Object... objects )
358 throws BeansException
360 return applicationContext.getBean( aClass, objects );
364 public Object getBean( String s )
365 throws BeansException
367 return applicationContext.getBean( s );
371 public <T> T getBean( String s, Class<T> tClass )
372 throws BeansException
374 return applicationContext.getBean( s, tClass );
378 public <T> T getBean( Class<T> tClass )
379 throws BeansException
381 return applicationContext.getBean( tClass );
385 public Object getBean( String s, Object... objects )
386 throws BeansException
388 return applicationContext.getBean( s, objects );
392 public boolean containsBean( String s )
394 return applicationContext.containsBean( s );
398 public boolean isSingleton( String s )
399 throws NoSuchBeanDefinitionException
401 return applicationContext.isSingleton( s );
405 public boolean isPrototype( String s )
406 throws NoSuchBeanDefinitionException
408 return applicationContext.isPrototype( s );
412 public boolean isTypeMatch( String s, Class<?> aClass )
413 throws NoSuchBeanDefinitionException
415 return applicationContext.isTypeMatch( s, aClass );
419 public Class<?> getType( String s )
420 throws NoSuchBeanDefinitionException
422 return applicationContext.getType( s );
426 public String[] getAliases( String s )
428 return applicationContext.getAliases( s );
432 public String getMessage( String s, Object[] objects, String s2, Locale locale )
434 return applicationContext.getMessage( s, objects, s2, locale );
438 public String getMessage( String s, Object[] objects, Locale locale )
439 throws NoSuchMessageException
441 return applicationContext.getMessage( s, objects, locale );
445 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
446 throws NoSuchMessageException
448 return applicationContext.getMessage( messageSourceResolvable, locale );
452 public Resource[] getResources( String s )
455 return applicationContext.getResources( s );
459 public void publishEvent( Object o )
465 public String[] getBeanNamesForType( ResolvableType resolvableType )
467 return new String[0];
471 public boolean isTypeMatch( String s, ResolvableType resolvableType )
472 throws NoSuchBeanDefinitionException
478 public Resource getResource( String s )
480 return applicationContext.getResource( s );
484 public ClassLoader getClassLoader()
486 return applicationContext.getClassLoader();
490 protected Servlet findServlet( String name )
493 return unauthenticatedRepositoryServlet;
497 protected String getSpringConfigLocation()
499 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
503 protected static WebClient newClient()
505 final WebClient webClient = new WebClient();
506 webClient.getOptions().setJavaScriptEnabled( false );
507 webClient.getOptions().setCssEnabled( false );
508 webClient.getOptions().setAppletEnabled( false );
509 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
510 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
515 protected WebResponse getWebResponse( String path )
518 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
521 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
525 MockHttpServletRequest request = new MockHttpServletRequest();
526 request.setRequestURI( webRequest.getUrl().getPath() );
527 request.addHeader( "User-Agent", "Apache Archiva unit test" );
529 request.setMethod( webRequest.getHttpMethod().name() );
531 if ( webRequest.getHttpMethod() == HttpMethod.PUT )
533 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
534 request.setContentType( putRequest.contentType );
535 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
538 if ( webRequest instanceof MkColMethodWebRequest )
540 request.setMethod( "MKCOL" );
543 final MockHttpServletResponse response = execute( request );
545 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
546 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
548 String location = response.getHeader( "Location" );
549 log.debug( "follow redirect to {}", location );
550 return getWebResponse( new GetMethodWebRequest( location ) );
553 return new WebResponse( null, null, 1 )
556 public String getContentAsString()
560 return response.getContentAsString();
562 catch ( UnsupportedEncodingException e )
564 throw new RuntimeException( e.getMessage(), e );
569 public int getStatusCode()
571 return response.getStatus();
575 public String getResponseHeaderValue( String headerName )
577 return response.getHeader( headerName );
582 protected MockHttpServletResponse execute( HttpServletRequest request )
585 MockHttpServletResponse response = new MockHttpServletResponse()
588 public String getContentAsString()
589 throws UnsupportedEncodingException
591 String errorMessage = getErrorMessage();
592 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
595 this.unauthenticatedRepositoryServlet.service( request, response );
599 public static class GetMethodWebRequest
604 public GetMethodWebRequest( String url )
607 super( new URL( url ) );
613 public static class PutMethodWebRequest
618 InputStream inputStream;
622 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
625 super( new URL( url ), HttpMethod.PUT );
627 this.inputStream = inputStream;
628 this.contentType = contentType;
634 public static class ServletUnitClient
637 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
639 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
641 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
644 public WebResponse getResponse( WebRequest request )
647 return getResponse( request, false );
650 public WebResponse getResponse( WebRequest request, boolean followRedirect )
653 // alwasy following redirect as it's normal
654 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
657 public WebResponse getResource( WebRequest request )
660 return getResponse( request );
664 public ServletUnitClient getServletUnitClient()
666 return new ServletUnitClient( this );
671 public void tearDown()
675 if ( Files.exists(repoRootInternal) )
677 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootInternal );
680 if ( Files.exists(repoRootLegacy) )
682 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootLegacy );
688 protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
691 String path = Paths.get(subpath).isAbsolute() ? subpath.substring( 1,subpath.length() ) : subpath;
692 Path actualFile = repoRoot.resolve( path );
693 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should exist.", Files.exists(actualFile) );
694 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
695 Files.isRegularFile( actualFile ) );
697 String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
698 assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
701 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
704 ManagedRepository repository = servlet.getRepository( repoId );
705 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
706 Path repoRoot = Paths.get( repository.getLocation() );
707 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
708 Files.exists(repoRoot) && Files.isDirectory(repoRoot) );
711 protected void assertResponseOK( WebResponse response )
713 assertNotNull( "Should have recieved a response", response );
714 Assert.assertEquals( "Should have been an OK response code", //
715 HttpServletResponse.SC_OK, //
716 response.getStatusCode() );
719 protected void assertResponseOK( WebResponse response, String path )
721 assertNotNull( "Should have recieved a response", response );
722 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
723 response.getStatusCode() );
726 protected void assertResponseNotFound( WebResponse response )
728 assertNotNull( "Should have recieved a response", response );
729 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
730 response.getStatusCode() );
733 protected void assertResponseInternalServerError( WebResponse response )
735 assertNotNull( "Should have recieved a response", response );
736 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
737 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
740 protected void assertResponseConflictError( WebResponse response )
742 assertNotNull( "Should have received a response", response );
743 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
744 response.getStatusCode() );
747 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
748 boolean blockRedeployments )
750 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
752 repo.setName( name );
753 repo.setLocation( location.toAbsolutePath().toString() );
754 repo.setBlockRedeployments( blockRedeployments );
759 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
760 String layout, boolean blockRedeployments )
762 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
763 repo.setLayout( layout );
767 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
769 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
771 repo.setName( name );
776 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
779 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
783 protected void setupCleanRepo( Path repoRootDir )
786 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
787 if ( !Files.exists(repoRootDir) )
789 Files.createDirectories( repoRootDir );
793 protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
795 Path repoFile = repoRootInternal.resolve( resourcePath );
796 assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
797 Files.exists(repoFile) );
800 protected void setupCleanInternalRepo()
803 setupCleanRepo( repoRootInternal );
806 protected Path populateRepo( Path repoRootManaged, String path, String contents )
809 Path destFile = repoRootManaged.resolve( path );
810 Files.createDirectories( destFile.getParent() );
811 org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );