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