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.configuration.ArchivaConfiguration;
26 import org.apache.archiva.configuration.Configuration;
27 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
28 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
29 import org.apache.archiva.indexer.ArchivaIndexingContext;
30 import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
31 import org.apache.archiva.repository.ManagedRepository;
32 import org.apache.archiva.repository.RepositoryType;
33 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
34 import org.apache.archiva.webdav.httpunit.MkColMethodWebRequest;
35 import org.apache.commons.io.FileUtils;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.commons.lang3.StringUtils;
38 import org.junit.After;
39 import org.junit.Assert;
40 import org.junit.Before;
41 import org.junit.runner.RunWith;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.BeansException;
45 import org.springframework.beans.factory.BeanFactory;
46 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
47 import org.springframework.beans.factory.ObjectProvider;
48 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
49 import org.springframework.context.ApplicationContext;
50 import org.springframework.context.ApplicationEvent;
51 import org.springframework.context.MessageSourceResolvable;
52 import org.springframework.context.NoSuchMessageException;
53 import org.springframework.core.ResolvableType;
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;
68 import java.io.IOException;
69 import java.io.InputStream;
70 import java.io.UnsupportedEncodingException;
71 import java.lang.annotation.Annotation;
73 import java.nio.charset.Charset;
74 import java.nio.file.Files;
75 import java.nio.file.Path;
76 import java.nio.file.Paths;
77 import java.util.Locale;
79 import java.util.concurrent.atomic.AtomicReference;
82 * AbstractRepositoryServletTestCase
84 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
85 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:spring-context.xml",
86 "classpath*:/repository-servlet-simple.xml" } )
87 public abstract class AbstractRepositoryServletTestCase
90 protected static final String REPOID_INTERNAL = "internal";
92 protected Path repoRootInternal;
94 protected Path repoRootLegacy;
97 protected ArchivaConfiguration archivaConfiguration;
100 protected ApplicationContext applicationContext;
104 ArchivaRepositoryRegistry repositoryRegistry;
106 protected Logger log = LoggerFactory.getLogger( getClass() );
108 private AtomicReference<Path> projectBase = new AtomicReference<>( );
109 private AtomicReference<Path> appserverBase = new AtomicReference<>( );
112 public Path getProjectBase() {
113 if (this.projectBase.get()==null) {
114 String pathVal = System.getProperty("mvn.project.base.dir");
116 if (StringUtils.isEmpty(pathVal)) {
117 baseDir= Paths.get("").toAbsolutePath();
119 baseDir = Paths.get(pathVal).toAbsolutePath();
121 this.projectBase.compareAndSet(null, baseDir);
123 return this.projectBase.get();
126 public Path getAppserverBase() {
127 if (appserverBase.get()==null)
129 String pathVal = System.getProperty( "appserver.base" );
131 if ( StringUtils.isNotEmpty( pathVal ) )
133 basePath = Paths.get( pathVal );
137 log.warn("Using relative path to working directory, appserver.base was not set!");
138 basePath = Paths.get( "target/appserver-base" );
140 appserverBase.set( basePath );
142 return appserverBase.get();
145 protected void saveConfiguration()
148 repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
149 repositoryRegistry.reload();
150 saveConfiguration( archivaConfiguration );
162 System.setProperty( "appserver.base", getAppserverBase().toAbsolutePath().toString());
163 log.info("setUp appserverBase={}, projectBase={}, workingDir={}", getAppserverBase(), getProjectBase(), Paths.get("").toString());
165 repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
167 org.apache.archiva.common.utils.FileUtils.deleteDirectory( getAppserverBase() );
169 Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
170 Path testConfDest = getAppserverBase().resolve("conf/archiva.xml" );
171 if ( Files.exists(testConfDest) )
173 org.apache.archiva.common.utils.FileUtils.deleteQuietly( testConfDest );
175 FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
177 repoRootInternal = getAppserverBase().resolve("data/repositories/internal" );
178 repoRootLegacy = getAppserverBase().resolve( "data/repositories/legacy" );
179 Configuration config = archivaConfiguration.getConfiguration();
181 config.getManagedRepositories().clear();
183 config.addManagedRepository(
184 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
185 config.getProxyConnectors().clear();
187 config.getRemoteRepositories().clear();
189 saveConfiguration( archivaConfiguration );
191 ArchivaIndexingContext ctx = repositoryRegistry.getManagedRepository( REPOID_INTERNAL ).getIndexingContext( );
194 if (repositoryRegistry.getIndexManager(RepositoryType.MAVEN)!=null) {
195 repositoryRegistry.getIndexManager(RepositoryType.MAVEN).pack(ctx);
205 CacheManager.getInstance().clearAll();
210 protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
211 new UnauthenticatedRepositoryServlet();
213 protected void startRepository()
217 final MockServletContext mockServletContext = new MockServletContext();
219 WebApplicationContext webApplicationContext =
220 new TestWebapplicationContext( applicationContext, mockServletContext );
222 mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
223 webApplicationContext );
225 MockServletConfig mockServletConfig = new MockServletConfig()
228 public ServletContext getServletContext()
230 return mockServletContext;
234 unauthenticatedRepositoryServlet.init( mockServletConfig );
238 protected String createVersionMetadata(String groupId, String artifactId, String version) {
239 return createVersionMetadata(groupId, artifactId, version, null, null, null);
242 protected String createVersionMetadata(String groupId, String artifactId, String version, String timestamp, String buildNumber, String lastUpdated) {
243 StringBuilder buf = new StringBuilder();
244 buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
245 buf.append("<metadata>\n");
246 buf.append(" <groupId>").append(groupId).append("</groupId>\n");
247 buf.append(" <artifactId>").append(artifactId).append("</artifactId>\n");
248 buf.append(" <version>").append(version).append("</version>\n");
249 boolean hasSnapshot = StringUtils.isNotBlank(timestamp) || StringUtils.isNotBlank(buildNumber);
250 boolean hasLastUpdated = StringUtils.isNotBlank(lastUpdated);
251 if (hasSnapshot || hasLastUpdated) {
252 buf.append(" <versioning>\n");
254 buf.append(" <snapshot>\n");
255 buf.append(" <buildNumber>").append(buildNumber).append("</buildNumber>\n");
256 buf.append(" <timestamp>").append(timestamp).append("</timestamp>\n");
257 buf.append(" </snapshot>\n");
259 if (hasLastUpdated) {
260 buf.append(" <lastUpdated>").append(lastUpdated).append("</lastUpdated>\n");
262 buf.append(" </versioning>\n");
264 buf.append("</metadata>");
265 return buf.toString();
269 public static class TestWebapplicationContext
270 implements WebApplicationContext
272 private ApplicationContext applicationContext;
274 private ServletContext servletContext;
276 TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
278 this.applicationContext = applicationContext;
282 public ServletContext getServletContext()
284 return servletContext;
288 public String getId()
290 return applicationContext.getId();
294 public String getApplicationName()
296 return applicationContext.getApplicationName();
300 public String getDisplayName()
302 return applicationContext.getDisplayName();
306 public long getStartupDate()
308 return applicationContext.getStartupDate();
312 public ApplicationContext getParent()
314 return applicationContext.getParent();
318 public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
319 throws IllegalStateException
321 return applicationContext.getAutowireCapableBeanFactory();
325 public void publishEvent( ApplicationEvent applicationEvent )
327 applicationContext.publishEvent( applicationEvent );
331 public Environment getEnvironment()
333 return applicationContext.getEnvironment();
337 public BeanFactory getParentBeanFactory()
339 return applicationContext.getParentBeanFactory();
343 public boolean containsLocalBean( String s )
345 return applicationContext.containsLocalBean( s );
349 public boolean containsBeanDefinition( String s )
351 return applicationContext.containsBeanDefinition( s );
355 public int getBeanDefinitionCount()
357 return applicationContext.getBeanDefinitionCount();
361 public String[] getBeanDefinitionNames()
363 return applicationContext.getBeanDefinitionNames();
367 public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass, boolean b )
373 public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType, boolean b )
379 public String[] getBeanNamesForType( Class<?> aClass )
381 return applicationContext.getBeanNamesForType( aClass );
385 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
387 return applicationContext.getBeanNamesForType( aClass, b, b2 );
391 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
392 throws BeansException
394 return applicationContext.getBeansOfType( tClass );
398 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
399 throws BeansException
401 return applicationContext.getBeansOfType( tClass, b, b2 );
405 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
407 return applicationContext.getBeanNamesForAnnotation( aClass );
411 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
412 throws BeansException
414 return applicationContext.getBeansWithAnnotation( aClass );
418 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
419 throws NoSuchBeanDefinitionException
421 return applicationContext.findAnnotationOnBean( s, aClass );
425 public <T> T getBean( Class<T> aClass, Object... objects )
426 throws BeansException
428 return applicationContext.getBean( aClass, objects );
432 public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass )
438 public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType )
444 public Object getBean( String s )
445 throws BeansException
447 return applicationContext.getBean( s );
451 public <T> T getBean( String s, Class<T> tClass )
452 throws BeansException
454 return applicationContext.getBean( s, tClass );
458 public <T> T getBean( Class<T> tClass )
459 throws BeansException
461 return applicationContext.getBean( tClass );
465 public Object getBean( String s, Object... objects )
466 throws BeansException
468 return applicationContext.getBean( s, objects );
472 public boolean containsBean( String s )
474 return applicationContext.containsBean( s );
478 public boolean isSingleton( String s )
479 throws NoSuchBeanDefinitionException
481 return applicationContext.isSingleton( s );
485 public boolean isPrototype( String s )
486 throws NoSuchBeanDefinitionException
488 return applicationContext.isPrototype( s );
492 public boolean isTypeMatch( String s, Class<?> aClass )
493 throws NoSuchBeanDefinitionException
495 return applicationContext.isTypeMatch( s, aClass );
499 public Class<?> getType( String s )
500 throws NoSuchBeanDefinitionException
502 return applicationContext.getType( s );
506 public Class<?> getType( String s, boolean b ) throws NoSuchBeanDefinitionException
512 public String[] getAliases( String s )
514 return applicationContext.getAliases( s );
518 public String getMessage( String s, Object[] objects, String s2, Locale locale )
520 return applicationContext.getMessage( s, objects, s2, locale );
524 public String getMessage( String s, Object[] objects, Locale locale )
525 throws NoSuchMessageException
527 return applicationContext.getMessage( s, objects, locale );
531 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
532 throws NoSuchMessageException
534 return applicationContext.getMessage( messageSourceResolvable, locale );
538 public Resource[] getResources( String s )
541 return applicationContext.getResources( s );
545 public void publishEvent( Object o )
551 public String[] getBeanNamesForType( ResolvableType resolvableType )
553 return new String[0];
557 public String[] getBeanNamesForType( ResolvableType resolvableType, boolean b, boolean b1 )
559 return new String[0];
563 public boolean isTypeMatch( String s, ResolvableType resolvableType )
564 throws NoSuchBeanDefinitionException
570 public Resource getResource( String s )
572 return applicationContext.getResource( s );
576 public ClassLoader getClassLoader()
578 return applicationContext.getClassLoader();
582 protected Servlet findServlet( String name )
585 return unauthenticatedRepositoryServlet;
589 protected String getSpringConfigLocation()
591 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
595 protected static WebClient newClient()
597 final WebClient webClient = new WebClient();
598 webClient.getOptions().setJavaScriptEnabled( false );
599 webClient.getOptions().setCssEnabled( false );
600 webClient.getOptions().setAppletEnabled( false );
601 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
602 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
607 protected WebResponse getWebResponse( String path )
610 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
613 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
617 MockHttpServletRequest request = new MockHttpServletRequest();
618 request.setRequestURI( webRequest.getUrl().getPath() );
619 request.addHeader( "User-Agent", "Apache Archiva unit test" );
621 request.setMethod( webRequest.getHttpMethod().name() );
623 if ( webRequest.getHttpMethod() == HttpMethod.PUT )
625 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
626 request.setContentType( putRequest.contentType );
627 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
630 if ( webRequest instanceof MkColMethodWebRequest )
632 request.setMethod( "MKCOL" );
635 final MockHttpServletResponse response = execute( request );
637 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
638 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
640 String location = response.getHeader( "Location" );
641 log.debug( "follow redirect to {}", location );
642 return getWebResponse( new GetMethodWebRequest( location ) );
645 return new WebResponse( null, null, 1 )
648 public String getContentAsString()
652 return response.getContentAsString();
654 catch ( UnsupportedEncodingException e )
656 throw new RuntimeException( e.getMessage(), e );
661 public int getStatusCode()
663 return response.getStatus();
667 public String getResponseHeaderValue( String headerName )
669 return response.getHeader( headerName );
674 protected MockHttpServletResponse execute( HttpServletRequest request )
677 MockHttpServletResponse response = new MockHttpServletResponse()
680 public String getContentAsString()
681 throws UnsupportedEncodingException
683 String errorMessage = getErrorMessage();
684 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
687 this.unauthenticatedRepositoryServlet.service( request, response );
691 public static class GetMethodWebRequest
696 public GetMethodWebRequest( String url )
699 super( new URL( url ) );
705 public static class PutMethodWebRequest
710 InputStream inputStream;
714 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
717 super( new URL( url ), HttpMethod.PUT );
719 this.inputStream = inputStream;
720 this.contentType = contentType;
726 public static class ServletUnitClient
729 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
731 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
733 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
736 public WebResponse getResponse( WebRequest request )
739 return getResponse( request, false );
742 public WebResponse getResponse( WebRequest request, boolean followRedirect )
745 // alwasy following redirect as it's normal
746 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
749 public WebResponse getResource( WebRequest request )
752 return getResponse( request );
756 public ServletUnitClient getServletUnitClient()
758 return new ServletUnitClient( this );
763 public void tearDown()
766 repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
768 if ( Files.exists(repoRootInternal) )
770 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootInternal );
773 if ( Files.exists(repoRootLegacy) )
775 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootLegacy );
778 String appserverBase = System.getProperty( "appserver.base" );
779 if ( StringUtils.isNotEmpty( appserverBase ) )
781 org.apache.archiva.common.utils.FileUtils.deleteQuietly( Paths.get( appserverBase ) );
787 protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
790 String path = Paths.get(subpath).isAbsolute() ? subpath.substring( 1,subpath.length() ) : subpath;
791 Path actualFile = repoRoot.resolve( path );
792 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should exist.", Files.exists(actualFile) );
793 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
794 Files.isRegularFile( actualFile ) );
796 String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
797 assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
800 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
803 ManagedRepository repository = servlet.getRepository( repoId );
804 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
805 Path repoRoot = Paths.get( repository.getLocation() );
806 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
807 Files.exists(repoRoot) && Files.isDirectory(repoRoot) );
810 protected void assertResponseOK( WebResponse response )
812 assertNotNull( "Should have recieved a response", response );
813 Assert.assertEquals( "Should have been an OK response code", //
814 HttpServletResponse.SC_OK, //
815 response.getStatusCode() );
818 protected void assertResponseOK( WebResponse response, String path )
820 assertNotNull( "Should have recieved a response", response );
821 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
822 response.getStatusCode() );
825 protected void assertResponseNotFound( WebResponse response )
827 assertNotNull( "Should have recieved a response", response );
828 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
829 response.getStatusCode() );
832 protected void assertResponseInternalServerError( WebResponse response )
834 assertNotNull( "Should have recieved a response", response );
835 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
836 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
839 protected void assertResponseConflictError( WebResponse response )
841 assertNotNull( "Should have received a response", response );
842 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
843 response.getStatusCode() );
846 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
847 boolean blockRedeployments )
849 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
851 repo.setName( name );
852 repo.setLocation( location.toAbsolutePath().toString() );
853 repo.setBlockRedeployments( blockRedeployments );
854 repo.setType( "MAVEN" );
855 repo.setIndexDir(".indexer");
856 repo.setPackedIndexDir(".index");
861 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
862 String layout, boolean blockRedeployments )
864 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
865 repo.setLayout( layout );
869 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
871 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
873 repo.setName( name );
878 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
881 repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
882 // repositoryRegistry.reload();
883 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
888 protected void setupCleanRepo( Path repoRootDir )
891 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
892 if ( !Files.exists(repoRootDir) )
894 Files.createDirectories( repoRootDir );
898 protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
900 Path repoFile = repoRootInternal.resolve( resourcePath );
901 assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
902 Files.exists(repoFile) );
905 protected void setupCleanInternalRepo()
908 setupCleanRepo( repoRootInternal );
911 protected Path populateRepo( Path repoRootManaged, String path, String contents )
914 Path destFile = repoRootManaged.resolve( path );
915 Files.createDirectories( destFile.getParent() );
916 org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );