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.configuration.ArchivaConfiguration;
30 import org.apache.archiva.configuration.Configuration;
31 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
32 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
33 import org.apache.archiva.repository.ManagedRepository;
34 import org.apache.archiva.repository.RepositoryException;
35 import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
36 import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
37 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
38 import org.apache.archiva.webdav.httpunit.MkColMethodWebRequest;
39 import org.apache.commons.io.FileUtils;
40 import org.apache.commons.io.IOUtils;
41 import org.apache.commons.lang3.StringUtils;
42 import org.junit.After;
43 import org.junit.Assert;
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.ObjectProvider;
52 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
53 import org.springframework.context.ApplicationContext;
54 import org.springframework.context.ApplicationEvent;
55 import org.springframework.context.MessageSourceResolvable;
56 import org.springframework.context.NoSuchMessageException;
57 import org.springframework.core.ResolvableType;
58 import org.springframework.core.env.Environment;
59 import org.springframework.core.io.Resource;
60 import org.springframework.mock.web.MockHttpServletRequest;
61 import org.springframework.mock.web.MockHttpServletResponse;
62 import org.springframework.mock.web.MockServletConfig;
63 import org.springframework.mock.web.MockServletContext;
64 import org.springframework.test.context.ContextConfiguration;
65 import org.springframework.web.context.WebApplicationContext;
67 import javax.inject.Inject;
68 import javax.servlet.Servlet;
69 import javax.servlet.ServletContext;
70 import javax.servlet.http.HttpServletRequest;
71 import javax.servlet.http.HttpServletResponse;
72 import java.io.IOException;
73 import java.io.InputStream;
74 import java.io.UnsupportedEncodingException;
75 import java.lang.annotation.Annotation;
77 import java.nio.charset.Charset;
78 import java.nio.file.Files;
79 import java.nio.file.Path;
80 import java.nio.file.Paths;
81 import java.util.Locale;
83 import java.util.concurrent.atomic.AtomicReference;
86 * AbstractRepositoryServletTestCase
88 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
89 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:spring-context.xml",
90 "classpath*:/repository-servlet-simple.xml" } )
91 public abstract class AbstractRepositoryServletTestCase
94 protected static final String REPOID_INTERNAL = "internal";
96 protected Path repoRootInternal;
98 protected Path repoRootLegacy;
101 protected ArchivaConfiguration archivaConfiguration;
104 protected ApplicationContext applicationContext;
106 @SuppressWarnings( "unused" )
108 RepositoryHandlerDependencies repositoryHandlerDependencies;
111 ArchivaRepositoryRegistry repositoryRegistry;
113 protected Logger log = LoggerFactory.getLogger( getClass() );
115 private AtomicReference<Path> projectBase = new AtomicReference<>( );
116 private AtomicReference<Path> appserverBase = new AtomicReference<>( );
119 public Path getProjectBase() {
120 if (this.projectBase.get()==null) {
121 String pathVal = System.getProperty("mvn.project.base.dir");
123 if (StringUtils.isEmpty(pathVal)) {
124 baseDir= Paths.get("").toAbsolutePath();
126 baseDir = Paths.get(pathVal).toAbsolutePath();
128 this.projectBase.compareAndSet(null, baseDir);
130 return this.projectBase.get();
133 public Path getAppserverBase() {
134 if (appserverBase.get()==null)
136 String pathVal = System.getProperty( "appserver.base" );
138 if ( StringUtils.isNotEmpty( pathVal ) )
140 basePath = Paths.get( pathVal );
144 log.warn("Using relative path to working directory, appserver.base was not set!");
145 basePath = Paths.get( "target/appserver-base" );
147 appserverBase.set( basePath );
149 return appserverBase.get();
152 protected void saveConfiguration()
155 repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
156 repositoryRegistry.reload();
157 saveConfiguration( archivaConfiguration );
169 System.setProperty( "appserver.base", getAppserverBase().toAbsolutePath().toString());
170 log.info("setUp appserverBase={}, projectBase={}, workingDir={}", getAppserverBase(), getProjectBase(), Paths.get("").toString());
172 repositoryRegistry.getRepositories().stream().forEach(r -> {
175 repositoryRegistry.removeRepository( r );
177 catch ( RepositoryException e )
179 e.printStackTrace( );
182 org.apache.archiva.common.utils.FileUtils.deleteDirectory( getAppserverBase() );
184 Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
185 Path testConfDest = getAppserverBase().resolve("conf/archiva.xml" );
186 if ( Files.exists(testConfDest) )
188 org.apache.archiva.common.utils.FileUtils.deleteQuietly( testConfDest );
190 FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
192 repoRootInternal = getAppserverBase().resolve("data/repositories/internal" );
193 repoRootLegacy = getAppserverBase().resolve( "data/repositories/legacy" );
194 Configuration config = archivaConfiguration.getConfiguration();
196 config.getManagedRepositories().clear();
198 config.addManagedRepository(
199 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
200 config.getProxyConnectors().clear();
202 config.getRemoteRepositories().clear();
204 saveConfiguration( archivaConfiguration );
205 // repositoryRegistry.reload();
207 // ArchivaIndexingContext ctx = repositoryRegistry.getManagedRepository( REPOID_INTERNAL ).getIndexingContext( );
210 // if (repositoryRegistry.getIndexManager(RepositoryType.MAVEN)!=null) {
211 // repositoryRegistry.getIndexManager(RepositoryType.MAVEN).pack(ctx);
221 CacheManager.getInstance().clearAll();
226 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
227 new UnauthenticatedRepositoryServlet();
229 protected void startRepository()
233 final MockServletContext mockServletContext = new MockServletContext();
235 WebApplicationContext webApplicationContext =
236 new TestWebapplicationContext( applicationContext, mockServletContext );
238 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
239 webApplicationContext );
241 MockServletConfig mockServletConfig = new MockServletConfig()
244 public ServletContext getServletContext()
246 return mockServletContext;
250 unauthenticatedRepositoryServlet.init( mockServletConfig );
254 protected String createVersionMetadata(String groupId, String artifactId, String version) {
255 return createVersionMetadata(groupId, artifactId, version, null, null, null);
258 protected String createVersionMetadata(String groupId, String artifactId, String version, String timestamp, String buildNumber, String lastUpdated) {
259 StringBuilder buf = new StringBuilder();
260 buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
261 buf.append("<metadata>\n");
262 buf.append(" <groupId>").append(groupId).append("</groupId>\n");
263 buf.append(" <artifactId>").append(artifactId).append("</artifactId>\n");
264 buf.append(" <version>").append(version).append("</version>\n");
265 boolean hasSnapshot = StringUtils.isNotBlank(timestamp) || StringUtils.isNotBlank(buildNumber);
266 boolean hasLastUpdated = StringUtils.isNotBlank(lastUpdated);
267 if (hasSnapshot || hasLastUpdated) {
268 buf.append(" <versioning>\n");
270 buf.append(" <snapshot>\n");
271 buf.append(" <buildNumber>").append(buildNumber).append("</buildNumber>\n");
272 buf.append(" <timestamp>").append(timestamp).append("</timestamp>\n");
273 buf.append(" </snapshot>\n");
275 if (hasLastUpdated) {
276 buf.append(" <lastUpdated>").append(lastUpdated).append("</lastUpdated>\n");
278 buf.append(" </versioning>\n");
280 buf.append("</metadata>");
281 return buf.toString();
285 public static class TestWebapplicationContext
286 implements WebApplicationContext
288 private ApplicationContext applicationContext;
290 private ServletContext servletContext;
292 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
294 this.applicationContext = applicationContext;
298 public ServletContext getServletContext()
300 return servletContext;
304 public String getId()
306 return applicationContext.getId();
310 public String getApplicationName()
312 return applicationContext.getApplicationName();
316 public String getDisplayName()
318 return applicationContext.getDisplayName();
322 public long getStartupDate()
324 return applicationContext.getStartupDate();
328 public ApplicationContext getParent()
330 return applicationContext.getParent();
334 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
335 throws IllegalStateException
337 return applicationContext.getAutowireCapableBeanFactory();
341 public void publishEvent( ApplicationEvent applicationEvent )
343 applicationContext.publishEvent( applicationEvent );
347 public Environment getEnvironment()
349 return applicationContext.getEnvironment();
353 public BeanFactory getParentBeanFactory()
355 return applicationContext.getParentBeanFactory();
359 public boolean containsLocalBean( String s )
361 return applicationContext.containsLocalBean( s );
365 public boolean containsBeanDefinition( String s )
367 return applicationContext.containsBeanDefinition( s );
371 public int getBeanDefinitionCount()
373 return applicationContext.getBeanDefinitionCount();
377 public String[] getBeanDefinitionNames()
379 return applicationContext.getBeanDefinitionNames();
383 public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass, boolean b )
389 public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType, boolean b )
395 public String[] getBeanNamesForType( Class<?> aClass )
397 return applicationContext.getBeanNamesForType( aClass );
401 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
403 return applicationContext.getBeanNamesForType( aClass, b, b2 );
407 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
408 throws BeansException
410 return applicationContext.getBeansOfType( tClass );
414 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
415 throws BeansException
417 return applicationContext.getBeansOfType( tClass, b, b2 );
421 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
423 return applicationContext.getBeanNamesForAnnotation( aClass );
427 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
428 throws BeansException
430 return applicationContext.getBeansWithAnnotation( aClass );
434 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
435 throws NoSuchBeanDefinitionException
437 return applicationContext.findAnnotationOnBean( s, aClass );
441 public <T> T getBean( Class<T> aClass, Object... objects )
442 throws BeansException
444 return applicationContext.getBean( aClass, objects );
448 public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass )
454 public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType )
460 public Object getBean( String s )
461 throws BeansException
463 return applicationContext.getBean( s );
467 public <T> T getBean( String s, Class<T> tClass )
468 throws BeansException
470 return applicationContext.getBean( s, tClass );
474 public <T> T getBean( Class<T> tClass )
475 throws BeansException
477 return applicationContext.getBean( tClass );
481 public Object getBean( String s, Object... objects )
482 throws BeansException
484 return applicationContext.getBean( s, objects );
488 public boolean containsBean( String s )
490 return applicationContext.containsBean( s );
494 public boolean isSingleton( String s )
495 throws NoSuchBeanDefinitionException
497 return applicationContext.isSingleton( s );
501 public boolean isPrototype( String s )
502 throws NoSuchBeanDefinitionException
504 return applicationContext.isPrototype( s );
508 public boolean isTypeMatch( String s, Class<?> aClass )
509 throws NoSuchBeanDefinitionException
511 return applicationContext.isTypeMatch( s, aClass );
515 public Class<?> getType( String s )
516 throws NoSuchBeanDefinitionException
518 return applicationContext.getType( s );
522 public Class<?> getType( String s, boolean b ) throws NoSuchBeanDefinitionException
528 public String[] getAliases( String s )
530 return applicationContext.getAliases( s );
534 public String getMessage( String s, Object[] objects, String s2, Locale locale )
536 return applicationContext.getMessage( s, objects, s2, locale );
540 public String getMessage( String s, Object[] objects, Locale locale )
541 throws NoSuchMessageException
543 return applicationContext.getMessage( s, objects, locale );
547 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
548 throws NoSuchMessageException
550 return applicationContext.getMessage( messageSourceResolvable, locale );
554 public Resource[] getResources( String s )
557 return applicationContext.getResources( s );
561 public void publishEvent( Object o )
567 public String[] getBeanNamesForType( ResolvableType resolvableType )
569 return new String[0];
573 public String[] getBeanNamesForType( ResolvableType resolvableType, boolean b, boolean b1 )
575 return new String[0];
579 public boolean isTypeMatch( String s, ResolvableType resolvableType )
580 throws NoSuchBeanDefinitionException
586 public Resource getResource( String s )
588 return applicationContext.getResource( s );
592 public ClassLoader getClassLoader()
594 return applicationContext.getClassLoader();
598 protected Servlet findServlet( String name )
601 return unauthenticatedRepositoryServlet;
605 protected String getSpringConfigLocation()
607 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
611 protected static WebClient newClient()
613 final WebClient webClient = new WebClient();
614 webClient.getOptions().setJavaScriptEnabled( false );
615 webClient.getOptions().setCssEnabled( false );
616 webClient.getOptions().setAppletEnabled( false );
617 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
618 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
623 protected WebResponse getWebResponse( String path )
626 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
629 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
633 MockHttpServletRequest request = new MockHttpServletRequest();
634 request.setRequestURI( webRequest.getUrl().getPath() );
635 request.addHeader( "User-Agent", "Apache Archiva unit test" );
637 request.setMethod( webRequest.getHttpMethod().name() );
639 if ( webRequest.getHttpMethod() == HttpMethod.PUT )
641 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
642 request.setContentType( putRequest.contentType );
643 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
646 if ( webRequest instanceof MkColMethodWebRequest )
648 request.setMethod( "MKCOL" );
651 final MockHttpServletResponse response = execute( request );
653 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
654 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
656 String location = response.getHeader( "Location" );
657 log.debug( "follow redirect to {}", location );
658 return getWebResponse( new GetMethodWebRequest( location ) );
661 return new WebResponse( null, null, 1 )
664 public String getContentAsString()
668 return response.getContentAsString();
670 catch ( UnsupportedEncodingException e )
672 throw new RuntimeException( e.getMessage(), e );
677 public int getStatusCode()
679 return response.getStatus();
683 public String getResponseHeaderValue( String headerName )
685 return response.getHeader( headerName );
690 protected MockHttpServletResponse execute( HttpServletRequest request )
693 MockHttpServletResponse response = new MockHttpServletResponse()
696 public String getContentAsString()
697 throws UnsupportedEncodingException
699 String errorMessage = getErrorMessage();
700 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
703 this.unauthenticatedRepositoryServlet.service( request, response );
707 public static class GetMethodWebRequest
712 public GetMethodWebRequest( String url )
715 super( new URL( url ) );
721 public static class PutMethodWebRequest
726 InputStream inputStream;
730 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
733 super( new URL( url ), HttpMethod.PUT );
735 this.inputStream = inputStream;
736 this.contentType = contentType;
742 public static class ServletUnitClient
745 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
747 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
749 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
752 public WebResponse getResponse( WebRequest request )
755 return getResponse( request, false );
758 public WebResponse getResponse( WebRequest request, boolean followRedirect )
761 // alwasy following redirect as it's normal
762 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
765 public WebResponse getResource( WebRequest request )
768 return getResponse( request );
772 public ServletUnitClient getServletUnitClient()
774 return new ServletUnitClient( this );
779 public void tearDown()
782 repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
784 if ( Files.exists(repoRootInternal) )
786 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootInternal );
789 if ( Files.exists(repoRootLegacy) )
791 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootLegacy );
794 String appserverBase = System.getProperty( "appserver.base" );
795 if ( StringUtils.isNotEmpty( appserverBase ) )
797 org.apache.archiva.common.utils.FileUtils.deleteQuietly( Paths.get( appserverBase ) );
803 protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
806 String path = Paths.get(subpath).isAbsolute() ? subpath.substring( 1,subpath.length() ) : subpath;
807 Path actualFile = repoRoot.resolve( path );
808 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should exist.", Files.exists(actualFile) );
809 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
810 Files.isRegularFile( actualFile ) );
812 String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
813 assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
816 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
819 ManagedRepository repository = servlet.getRepository( repoId );
820 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
821 Path repoRoot = Paths.get( repository.getLocation() );
822 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
823 Files.exists(repoRoot) && Files.isDirectory(repoRoot) );
826 protected void assertResponseOK( WebResponse response )
828 assertNotNull( "Should have recieved a response", response );
829 Assert.assertEquals( "Should have been an OK response code", //
830 HttpServletResponse.SC_OK, //
831 response.getStatusCode() );
834 protected void assertResponseOK( WebResponse response, String path )
836 assertNotNull( "Should have recieved a response", response );
837 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
838 response.getStatusCode() );
841 protected void assertResponseNotFound( WebResponse response )
843 assertNotNull( "Should have recieved a response", response );
844 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
845 response.getStatusCode() );
848 protected void assertResponseInternalServerError( WebResponse response )
850 assertNotNull( "Should have recieved a response", response );
851 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
852 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
855 protected void assertResponseConflictError( WebResponse response )
857 assertNotNull( "Should have received a response", response );
858 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
859 response.getStatusCode() );
862 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
863 boolean blockRedeployments )
865 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
867 repo.setName( name );
868 repo.setLocation( location.toAbsolutePath().toString() );
869 repo.setBlockRedeployments( blockRedeployments );
870 repo.setType( "MAVEN" );
871 repo.setIndexDir(location.resolve( ".indexer" ).toAbsolutePath().toString());
872 repo.setPackedIndexDir( location.resolve( ".index" ).toAbsolutePath( ).toString( ) );
877 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
878 String layout, boolean blockRedeployments )
880 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
881 repo.setLayout( layout );
885 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
887 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
889 repo.setName( name );
894 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
897 repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
898 // repositoryRegistry.reload();
899 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
904 protected void setupCleanRepo( Path repoRootDir )
907 if (repoRootDir!=null)
909 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
910 if ( !Files.exists( repoRootDir ) )
912 Files.createDirectories( repoRootDir );
917 protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
919 Path repoFile = repoRootInternal.resolve( resourcePath );
920 assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
921 Files.exists(repoFile) );
924 protected void setupCleanInternalRepo()
927 setupCleanRepo( repoRootInternal );
930 protected Path populateRepo( Path repoRootManaged, String path, String contents )
933 Path destFile = repoRootManaged.resolve( path );
934 Files.createDirectories( destFile.getParent() );
935 org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );