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