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 String[] getBeanNamesForType( Class<?> aClass )
369 return applicationContext.getBeanNamesForType( aClass );
373 public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
375 return applicationContext.getBeanNamesForType( aClass, b, b2 );
379 public <T> Map<String, T> getBeansOfType( Class<T> tClass )
380 throws BeansException
382 return applicationContext.getBeansOfType( tClass );
386 public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
387 throws BeansException
389 return applicationContext.getBeansOfType( tClass, b, b2 );
393 public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
395 return applicationContext.getBeanNamesForAnnotation( aClass );
399 public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
400 throws BeansException
402 return applicationContext.getBeansWithAnnotation( aClass );
406 public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
407 throws NoSuchBeanDefinitionException
409 return applicationContext.findAnnotationOnBean( s, aClass );
413 public <T> T getBean( Class<T> aClass, Object... objects )
414 throws BeansException
416 return applicationContext.getBean( aClass, objects );
420 public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass )
426 public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType )
432 public Object getBean( String s )
433 throws BeansException
435 return applicationContext.getBean( s );
439 public <T> T getBean( String s, Class<T> tClass )
440 throws BeansException
442 return applicationContext.getBean( s, tClass );
446 public <T> T getBean( Class<T> tClass )
447 throws BeansException
449 return applicationContext.getBean( tClass );
453 public Object getBean( String s, Object... objects )
454 throws BeansException
456 return applicationContext.getBean( s, objects );
460 public boolean containsBean( String s )
462 return applicationContext.containsBean( s );
466 public boolean isSingleton( String s )
467 throws NoSuchBeanDefinitionException
469 return applicationContext.isSingleton( s );
473 public boolean isPrototype( String s )
474 throws NoSuchBeanDefinitionException
476 return applicationContext.isPrototype( s );
480 public boolean isTypeMatch( String s, Class<?> aClass )
481 throws NoSuchBeanDefinitionException
483 return applicationContext.isTypeMatch( s, aClass );
487 public Class<?> getType( String s )
488 throws NoSuchBeanDefinitionException
490 return applicationContext.getType( s );
494 public Class<?> getType( String s, boolean b ) throws NoSuchBeanDefinitionException
500 public String[] getAliases( String s )
502 return applicationContext.getAliases( s );
506 public String getMessage( String s, Object[] objects, String s2, Locale locale )
508 return applicationContext.getMessage( s, objects, s2, locale );
512 public String getMessage( String s, Object[] objects, Locale locale )
513 throws NoSuchMessageException
515 return applicationContext.getMessage( s, objects, locale );
519 public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
520 throws NoSuchMessageException
522 return applicationContext.getMessage( messageSourceResolvable, locale );
526 public Resource[] getResources( String s )
529 return applicationContext.getResources( s );
533 public void publishEvent( Object o )
539 public String[] getBeanNamesForType( ResolvableType resolvableType )
541 return new String[0];
545 public String[] getBeanNamesForType( ResolvableType resolvableType, boolean b, boolean b1 )
547 return new String[0];
551 public boolean isTypeMatch( String s, ResolvableType resolvableType )
552 throws NoSuchBeanDefinitionException
558 public Resource getResource( String s )
560 return applicationContext.getResource( s );
564 public ClassLoader getClassLoader()
566 return applicationContext.getClassLoader();
570 protected Servlet findServlet( String name )
573 return unauthenticatedRepositoryServlet;
577 protected String getSpringConfigLocation()
579 return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
583 protected static WebClient newClient()
585 final WebClient webClient = new WebClient();
586 webClient.getOptions().setJavaScriptEnabled( false );
587 webClient.getOptions().setCssEnabled( false );
588 webClient.getOptions().setAppletEnabled( false );
589 webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
590 webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
595 protected WebResponse getWebResponse( String path )
598 return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
601 protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
605 MockHttpServletRequest request = new MockHttpServletRequest();
606 request.setRequestURI( webRequest.getUrl().getPath() );
607 request.addHeader( "User-Agent", "Apache Archiva unit test" );
609 request.setMethod( webRequest.getHttpMethod().name() );
611 if ( webRequest.getHttpMethod() == HttpMethod.PUT )
613 PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
614 request.setContentType( putRequest.contentType );
615 request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
618 if ( webRequest instanceof MkColMethodWebRequest )
620 request.setMethod( "MKCOL" );
623 final MockHttpServletResponse response = execute( request );
625 if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
626 || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
628 String location = response.getHeader( "Location" );
629 log.debug( "follow redirect to {}", location );
630 return getWebResponse( new GetMethodWebRequest( location ) );
633 return new WebResponse( null, null, 1 )
636 public String getContentAsString()
640 return response.getContentAsString();
642 catch ( UnsupportedEncodingException e )
644 throw new RuntimeException( e.getMessage(), e );
649 public int getStatusCode()
651 return response.getStatus();
655 public String getResponseHeaderValue( String headerName )
657 return response.getHeader( headerName );
662 protected MockHttpServletResponse execute( HttpServletRequest request )
665 MockHttpServletResponse response = new MockHttpServletResponse()
668 public String getContentAsString()
669 throws UnsupportedEncodingException
671 String errorMessage = getErrorMessage();
672 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
675 this.unauthenticatedRepositoryServlet.service( request, response );
679 public static class GetMethodWebRequest
684 public GetMethodWebRequest( String url )
687 super( new URL( url ) );
693 public static class PutMethodWebRequest
698 InputStream inputStream;
702 public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
705 super( new URL( url ), HttpMethod.PUT );
707 this.inputStream = inputStream;
708 this.contentType = contentType;
714 public static class ServletUnitClient
717 AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
719 public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
721 this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
724 public WebResponse getResponse( WebRequest request )
727 return getResponse( request, false );
730 public WebResponse getResponse( WebRequest request, boolean followRedirect )
733 // alwasy following redirect as it's normal
734 return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
737 public WebResponse getResource( WebRequest request )
740 return getResponse( request );
744 public ServletUnitClient getServletUnitClient()
746 return new ServletUnitClient( this );
751 public void tearDown()
754 repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
756 if ( Files.exists(repoRootInternal) )
758 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootInternal );
761 if ( Files.exists(repoRootLegacy) )
763 org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootLegacy );
766 String appserverBase = System.getProperty( "appserver.base" );
767 if ( StringUtils.isNotEmpty( appserverBase ) )
769 org.apache.archiva.common.utils.FileUtils.deleteQuietly( Paths.get( appserverBase ) );
775 protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
778 String path = Paths.get(subpath).isAbsolute() ? subpath.substring( 1,subpath.length() ) : subpath;
779 Path actualFile = repoRoot.resolve( path );
780 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should exist.", Files.exists(actualFile) );
781 assertTrue( "File <" + actualFile.toAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
782 Files.isRegularFile( actualFile ) );
784 String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
785 assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
788 protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
791 ManagedRepository repository = servlet.getRepository( repoId );
792 assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
793 Path repoRoot = Paths.get( repository.getLocation() );
794 assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
795 Files.exists(repoRoot) && Files.isDirectory(repoRoot) );
798 protected void assertResponseOK( WebResponse response )
800 assertNotNull( "Should have recieved a response", response );
801 Assert.assertEquals( "Should have been an OK response code", //
802 HttpServletResponse.SC_OK, //
803 response.getStatusCode() );
806 protected void assertResponseOK( WebResponse response, String path )
808 assertNotNull( "Should have recieved a response", response );
809 Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
810 response.getStatusCode() );
813 protected void assertResponseNotFound( WebResponse response )
815 assertNotNull( "Should have recieved a response", response );
816 Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
817 response.getStatusCode() );
820 protected void assertResponseInternalServerError( WebResponse response )
822 assertNotNull( "Should have recieved a response", response );
823 Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
824 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
827 protected void assertResponseConflictError( WebResponse response )
829 assertNotNull( "Should have received a response", response );
830 Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
831 response.getStatusCode() );
834 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
835 boolean blockRedeployments )
837 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
839 repo.setName( name );
840 repo.setLocation( location.toAbsolutePath().toString() );
841 repo.setBlockRedeployments( blockRedeployments );
842 repo.setType( "MAVEN" );
843 repo.setIndexDir(".indexer");
844 repo.setPackedIndexDir(".index");
849 protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
850 String layout, boolean blockRedeployments )
852 ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
853 repo.setLayout( layout );
857 protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
859 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
861 repo.setName( name );
866 protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
869 repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
870 // repositoryRegistry.reload();
871 archivaConfiguration.save( archivaConfiguration.getConfiguration() );
876 protected void setupCleanRepo( Path repoRootDir )
879 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
880 if ( !Files.exists(repoRootDir) )
882 Files.createDirectories( repoRootDir );
886 protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
888 Path repoFile = repoRootInternal.resolve( resourcePath );
889 assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
890 Files.exists(repoFile) );
893 protected void setupCleanInternalRepo()
896 setupCleanRepo( repoRootInternal );
899 protected Path populateRepo( Path repoRootManaged, String path, String contents )
902 Path destFile = repoRootManaged.resolve( path );
903 Files.createDirectories( destFile.getParent() );
904 org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );