]> source.dussan.org Git - archiva.git/blob
6c564a5e37745a8bf5e40d5fe96ee47bc4a40a69
[archiva.git] /
1 package org.apache.archiva.webdav;
2
3 /*
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
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
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;
62
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;
72 import java.net.URL;
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;
78 import java.util.Map;
79 import java.util.concurrent.atomic.AtomicReference;
80
81 /**
82  * AbstractRepositoryServletTestCase
83  */
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
88     extends TestCase
89 {
90     protected static final String REPOID_INTERNAL = "internal";
91
92     protected Path repoRootInternal;
93
94     protected Path repoRootLegacy;
95
96     @Inject
97     protected ArchivaConfiguration archivaConfiguration;
98
99     @Inject
100     protected ApplicationContext applicationContext;
101
102
103     @Inject
104     ArchivaRepositoryRegistry repositoryRegistry;
105
106     protected Logger log = LoggerFactory.getLogger( getClass() );
107
108     private AtomicReference<Path> projectBase = new AtomicReference<>( );
109     private AtomicReference<Path> appserverBase = new AtomicReference<>( );
110
111
112     public Path getProjectBase() {
113         if (this.projectBase.get()==null) {
114             String pathVal = System.getProperty("mvn.project.base.dir");
115             Path baseDir;
116             if (StringUtils.isEmpty(pathVal)) {
117                 baseDir= Paths.get("").toAbsolutePath();
118             } else {
119                 baseDir = Paths.get(pathVal).toAbsolutePath();
120             }
121             this.projectBase.compareAndSet(null, baseDir);
122         }
123         return this.projectBase.get();
124     }
125
126     public Path getAppserverBase() {
127         if (appserverBase.get()==null)
128         {
129             String pathVal = System.getProperty( "appserver.base" );
130             Path basePath;
131             if ( StringUtils.isNotEmpty( pathVal ) )
132             {
133                 basePath = Paths.get( pathVal );
134             }
135             else
136             {
137                 log.warn("Using relative path to working directory, appserver.base was not set!");
138                 basePath = Paths.get( "target/appserver-base" );
139             }
140             appserverBase.set( basePath );
141         }
142         return appserverBase.get();
143     }
144
145     protected void saveConfiguration()
146         throws Exception
147     {
148         repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
149         repositoryRegistry.reload();
150         saveConfiguration( archivaConfiguration );
151
152     }
153
154     @Before
155     @Override
156     public void setUp()
157         throws Exception
158     {
159
160         super.setUp();
161
162         System.setProperty( "appserver.base", getAppserverBase().toAbsolutePath().toString());
163         log.info("setUp appserverBase={}, projectBase={}, workingDir={}", getAppserverBase(), getProjectBase(), Paths.get("").toString());
164
165         repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
166
167         org.apache.archiva.common.utils.FileUtils.deleteDirectory( getAppserverBase() );
168
169         Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
170         Path testConfDest = getAppserverBase().resolve("conf/archiva.xml" );
171         if ( Files.exists(testConfDest) )
172         {
173             org.apache.archiva.common.utils.FileUtils.deleteQuietly( testConfDest );
174         }
175         FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
176
177         repoRootInternal = getAppserverBase().resolve("data/repositories/internal" );
178         repoRootLegacy = getAppserverBase().resolve( "data/repositories/legacy" );
179         Configuration config = archivaConfiguration.getConfiguration();
180
181         config.getManagedRepositories().clear();
182
183         config.addManagedRepository(
184             createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal, true ) );
185         config.getProxyConnectors().clear();
186
187         config.getRemoteRepositories().clear();
188
189         saveConfiguration( archivaConfiguration );
190
191         ArchivaIndexingContext ctx = repositoryRegistry.getManagedRepository( REPOID_INTERNAL ).getIndexingContext( );
192         try
193         {
194             if (repositoryRegistry.getIndexManager(RepositoryType.MAVEN)!=null) {
195                 repositoryRegistry.getIndexManager(RepositoryType.MAVEN).pack(ctx);
196             }
197         } finally
198         {
199             if (ctx!=null)
200             {
201                 ctx.close( );
202             }
203         }
204
205         CacheManager.getInstance().clearAll();
206
207
208     }
209
210     protected UnauthenticatedRepositoryServlet unauthenticatedRepositoryServlet =
211         new UnauthenticatedRepositoryServlet();
212
213     protected void startRepository()
214         throws Exception
215     {
216
217         final MockServletContext mockServletContext = new MockServletContext();
218
219         WebApplicationContext webApplicationContext =
220             new TestWebapplicationContext( applicationContext, mockServletContext );
221
222         mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
223                                          webApplicationContext );
224
225         MockServletConfig mockServletConfig = new MockServletConfig()
226         {
227             @Override
228             public ServletContext getServletContext()
229             {
230                 return mockServletContext;
231             }
232         };
233
234         unauthenticatedRepositoryServlet.init( mockServletConfig );
235
236     }
237
238     protected String createVersionMetadata(String groupId, String artifactId, String version) {
239         return createVersionMetadata(groupId, artifactId, version, null, null, null);
240     }
241
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");
253             if (hasSnapshot) {
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");
258             }
259             if (hasLastUpdated) {
260                 buf.append("    <lastUpdated>").append(lastUpdated).append("</lastUpdated>\n");
261             }
262             buf.append("  </versioning>\n");
263         }
264         buf.append("</metadata>");
265         return buf.toString();
266     }
267
268
269     public static class TestWebapplicationContext
270         implements WebApplicationContext
271     {
272         private ApplicationContext applicationContext;
273
274         private ServletContext servletContext;
275
276         TestWebapplicationContext( ApplicationContext applicationContext, ServletContext servletContext )
277         {
278             this.applicationContext = applicationContext;
279         }
280
281         @Override
282         public ServletContext getServletContext()
283         {
284             return servletContext;
285         }
286
287         @Override
288         public String getId()
289         {
290             return applicationContext.getId();
291         }
292
293         @Override
294         public String getApplicationName()
295         {
296             return applicationContext.getApplicationName();
297         }
298
299         @Override
300         public String getDisplayName()
301         {
302             return applicationContext.getDisplayName();
303         }
304
305         @Override
306         public long getStartupDate()
307         {
308             return applicationContext.getStartupDate();
309         }
310
311         @Override
312         public ApplicationContext getParent()
313         {
314             return applicationContext.getParent();
315         }
316
317         @Override
318         public AutowireCapableBeanFactory getAutowireCapableBeanFactory()
319             throws IllegalStateException
320         {
321             return applicationContext.getAutowireCapableBeanFactory();
322         }
323
324         @Override
325         public void publishEvent( ApplicationEvent applicationEvent )
326         {
327             applicationContext.publishEvent( applicationEvent );
328         }
329
330         @Override
331         public Environment getEnvironment()
332         {
333             return applicationContext.getEnvironment();
334         }
335
336         @Override
337         public BeanFactory getParentBeanFactory()
338         {
339             return applicationContext.getParentBeanFactory();
340         }
341
342         @Override
343         public boolean containsLocalBean( String s )
344         {
345             return applicationContext.containsLocalBean( s );
346         }
347
348         @Override
349         public boolean containsBeanDefinition( String s )
350         {
351             return applicationContext.containsBeanDefinition( s );
352         }
353
354         @Override
355         public int getBeanDefinitionCount()
356         {
357             return applicationContext.getBeanDefinitionCount();
358         }
359
360         @Override
361         public String[] getBeanDefinitionNames()
362         {
363             return applicationContext.getBeanDefinitionNames();
364         }
365
366         @Override
367         public String[] getBeanNamesForType( Class<?> aClass )
368         {
369             return applicationContext.getBeanNamesForType( aClass );
370         }
371
372         @Override
373         public String[] getBeanNamesForType( Class<?> aClass, boolean b, boolean b2 )
374         {
375             return applicationContext.getBeanNamesForType( aClass, b, b2 );
376         }
377
378         @Override
379         public <T> Map<String, T> getBeansOfType( Class<T> tClass )
380             throws BeansException
381         {
382             return applicationContext.getBeansOfType( tClass );
383         }
384
385         @Override
386         public <T> Map<String, T> getBeansOfType( Class<T> tClass, boolean b, boolean b2 )
387             throws BeansException
388         {
389             return applicationContext.getBeansOfType( tClass, b, b2 );
390         }
391
392         @Override
393         public String[] getBeanNamesForAnnotation( Class<? extends Annotation> aClass )
394         {
395             return applicationContext.getBeanNamesForAnnotation( aClass );
396         }
397
398         @Override
399         public Map<String, Object> getBeansWithAnnotation( Class<? extends Annotation> aClass )
400             throws BeansException
401         {
402             return applicationContext.getBeansWithAnnotation( aClass );
403         }
404
405         @Override
406         public <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass )
407             throws NoSuchBeanDefinitionException
408         {
409             return applicationContext.findAnnotationOnBean( s, aClass );
410         }
411
412         @Override
413         public <T> T getBean( Class<T> aClass, Object... objects )
414             throws BeansException
415         {
416             return applicationContext.getBean( aClass, objects );
417         }
418
419         @Override
420         public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass )
421         {
422             return null;
423         }
424
425         @Override
426         public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType )
427         {
428             return null;
429         }
430
431         @Override
432         public Object getBean( String s )
433             throws BeansException
434         {
435             return applicationContext.getBean( s );
436         }
437
438         @Override
439         public <T> T getBean( String s, Class<T> tClass )
440             throws BeansException
441         {
442             return applicationContext.getBean( s, tClass );
443         }
444
445         @Override
446         public <T> T getBean( Class<T> tClass )
447             throws BeansException
448         {
449             return applicationContext.getBean( tClass );
450         }
451
452         @Override
453         public Object getBean( String s, Object... objects )
454             throws BeansException
455         {
456             return applicationContext.getBean( s, objects );
457         }
458
459         @Override
460         public boolean containsBean( String s )
461         {
462             return applicationContext.containsBean( s );
463         }
464
465         @Override
466         public boolean isSingleton( String s )
467             throws NoSuchBeanDefinitionException
468         {
469             return applicationContext.isSingleton( s );
470         }
471
472         @Override
473         public boolean isPrototype( String s )
474             throws NoSuchBeanDefinitionException
475         {
476             return applicationContext.isPrototype( s );
477         }
478
479         @Override
480         public boolean isTypeMatch( String s, Class<?> aClass )
481             throws NoSuchBeanDefinitionException
482         {
483             return applicationContext.isTypeMatch( s, aClass );
484         }
485
486         @Override
487         public Class<?> getType( String s )
488             throws NoSuchBeanDefinitionException
489         {
490             return applicationContext.getType( s );
491         }
492
493         @Override
494         public Class<?> getType( String s, boolean b ) throws NoSuchBeanDefinitionException
495         {
496             return null;
497         }
498
499         @Override
500         public String[] getAliases( String s )
501         {
502             return applicationContext.getAliases( s );
503         }
504
505         @Override
506         public String getMessage( String s, Object[] objects, String s2, Locale locale )
507         {
508             return applicationContext.getMessage( s, objects, s2, locale );
509         }
510
511         @Override
512         public String getMessage( String s, Object[] objects, Locale locale )
513             throws NoSuchMessageException
514         {
515             return applicationContext.getMessage( s, objects, locale );
516         }
517
518         @Override
519         public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
520             throws NoSuchMessageException
521         {
522             return applicationContext.getMessage( messageSourceResolvable, locale );
523         }
524
525         @Override
526         public Resource[] getResources( String s )
527             throws IOException
528         {
529             return applicationContext.getResources( s );
530         }
531
532         @Override
533         public void publishEvent( Object o )
534         {
535             // no op
536         }
537
538         @Override
539         public String[] getBeanNamesForType( ResolvableType resolvableType )
540         {
541             return new String[0];
542         }
543
544         @Override
545         public String[] getBeanNamesForType( ResolvableType resolvableType, boolean b, boolean b1 )
546         {
547             return new String[0];
548         }
549
550         @Override
551         public boolean isTypeMatch( String s, ResolvableType resolvableType )
552             throws NoSuchBeanDefinitionException
553         {
554             return false;
555         }
556
557         @Override
558         public Resource getResource( String s )
559         {
560             return applicationContext.getResource( s );
561         }
562
563         @Override
564         public ClassLoader getClassLoader()
565         {
566             return applicationContext.getClassLoader();
567         }
568     }
569
570     protected Servlet findServlet( String name )
571         throws Exception
572     {
573         return unauthenticatedRepositoryServlet;
574
575     }
576
577     protected String getSpringConfigLocation()
578     {
579         return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
580     }
581
582
583     protected static WebClient newClient()
584     {
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() );
591         return webClient;
592     }
593
594
595     protected WebResponse getWebResponse( String path )
596         throws Exception
597     {
598         return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
599     }
600
601     protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
602         throws Exception
603     {
604
605         MockHttpServletRequest request = new MockHttpServletRequest();
606         request.setRequestURI( webRequest.getUrl().getPath() );
607         request.addHeader( "User-Agent", "Apache Archiva unit test" );
608
609         request.setMethod( webRequest.getHttpMethod().name() );
610
611         if ( webRequest.getHttpMethod() == HttpMethod.PUT )
612         {
613             PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
614             request.setContentType( putRequest.contentType );
615             request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
616         }
617
618         if ( webRequest instanceof MkColMethodWebRequest )
619         {
620             request.setMethod( "MKCOL" );
621         }
622
623         final MockHttpServletResponse response = execute( request );
624
625         if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
626             || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
627         {
628             String location = response.getHeader( "Location" );
629             log.debug( "follow redirect to {}", location );
630             return getWebResponse( new GetMethodWebRequest( location ) );
631         }
632
633         return new WebResponse( null, null, 1 )
634         {
635             @Override
636             public String getContentAsString()
637             {
638                 try
639                 {
640                     return response.getContentAsString();
641                 }
642                 catch ( UnsupportedEncodingException e )
643                 {
644                     throw new RuntimeException( e.getMessage(), e );
645                 }
646             }
647
648             @Override
649             public int getStatusCode()
650             {
651                 return response.getStatus();
652             }
653
654             @Override
655             public String getResponseHeaderValue( String headerName )
656             {
657                 return response.getHeader( headerName );
658             }
659         };
660     }
661
662     protected MockHttpServletResponse execute( HttpServletRequest request )
663         throws Exception
664     {
665         MockHttpServletResponse response = new MockHttpServletResponse()
666         {
667             @Override
668             public String getContentAsString()
669                 throws UnsupportedEncodingException
670             {
671                 String errorMessage = getErrorMessage();
672                 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
673             }
674         };
675         this.unauthenticatedRepositoryServlet.service( request, response );
676         return response;
677     }
678
679     public static class GetMethodWebRequest
680         extends WebRequest
681     {
682         String url;
683
684         public GetMethodWebRequest( String url )
685             throws Exception
686         {
687             super( new URL( url ) );
688             this.url = url;
689
690         }
691     }
692
693     public static class PutMethodWebRequest
694         extends WebRequest
695     {
696         String url;
697
698         InputStream inputStream;
699
700         String contentType;
701
702         public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
703             throws Exception
704         {
705             super( new URL( url ), HttpMethod.PUT );
706             this.url = url;
707             this.inputStream = inputStream;
708             this.contentType = contentType;
709         }
710
711
712     }
713
714     public static class ServletUnitClient
715     {
716
717         AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
718
719         public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
720         {
721             this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
722         }
723
724         public WebResponse getResponse( WebRequest request )
725             throws Exception
726         {
727             return getResponse( request, false );
728         }
729
730         public WebResponse getResponse( WebRequest request, boolean followRedirect )
731             throws Exception
732         {
733             // alwasy following redirect as it's normal
734             return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
735         }
736
737         public WebResponse getResource( WebRequest request )
738             throws Exception
739         {
740             return getResponse( request );
741         }
742     }
743
744     public ServletUnitClient getServletUnitClient()
745     {
746         return new ServletUnitClient( this );
747     }
748
749     @Override
750     @After
751     public void tearDown()
752         throws Exception
753     {
754         repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
755
756         if ( Files.exists(repoRootInternal) )
757         {
758             org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootInternal );
759         }
760
761         if ( Files.exists(repoRootLegacy) )
762         {
763             org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootLegacy );
764         }
765
766         String appserverBase = System.getProperty( "appserver.base" );
767         if ( StringUtils.isNotEmpty( appserverBase ) )
768         {
769             org.apache.archiva.common.utils.FileUtils.deleteQuietly( Paths.get( appserverBase ) );
770         }
771
772     }
773
774
775     protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
776         throws IOException
777     {
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 ) );
783
784         String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
785         assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
786     }
787
788     protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
789         throws Exception
790     {
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) );
796     }
797
798     protected void assertResponseOK( WebResponse response )
799     {
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() );
804     }
805
806     protected void assertResponseOK( WebResponse response, String path )
807     {
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() );
811     }
812
813     protected void assertResponseNotFound( WebResponse response )
814     {
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() );
818     }
819
820     protected void assertResponseInternalServerError( WebResponse response )
821     {
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() );
825     }
826
827     protected void assertResponseConflictError( WebResponse response )
828     {
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() );
832     }
833
834     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
835                                                                       boolean blockRedeployments )
836     {
837         ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
838         repo.setId( id );
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");
845
846         return repo;
847     }
848
849     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
850                                                                       String layout, boolean blockRedeployments )
851     {
852         ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
853         repo.setLayout( layout );
854         return repo;
855     }
856
857     protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
858     {
859         RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
860         repo.setId( id );
861         repo.setName( name );
862         repo.setUrl( url );
863         return repo;
864     }
865
866     protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
867         throws Exception
868     {
869         repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
870         // repositoryRegistry.reload();
871         archivaConfiguration.save( archivaConfiguration.getConfiguration() );
872
873     }
874
875
876     protected void setupCleanRepo( Path repoRootDir )
877         throws IOException
878     {
879         org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
880         if ( !Files.exists(repoRootDir) )
881         {
882             Files.createDirectories( repoRootDir );
883         }
884     }
885
886     protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
887     {
888         Path repoFile =  repoRootInternal.resolve( resourcePath );
889         assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
890                      Files.exists(repoFile) );
891     }
892
893     protected void setupCleanInternalRepo()
894         throws Exception
895     {
896         setupCleanRepo( repoRootInternal );
897     }
898
899     protected Path populateRepo( Path repoRootManaged, String path, String contents )
900         throws Exception
901     {
902         Path destFile = repoRootManaged.resolve( path );
903         Files.createDirectories( destFile.getParent() );
904         org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );
905         return destFile;
906     }
907 }