]> source.dussan.org Git - archiva.git/blob
de735140875a1b039acb179e9781a0551325dc9e
[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.mock.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 <A extends Annotation> A findAnnotationOnBean( String s, Class<A> aClass, boolean b ) throws NoSuchBeanDefinitionException
442         {
443             throw new UnsupportedOperationException( "No supported yet." );
444         }
445
446         @Override
447         public <T> T getBean( Class<T> aClass, Object... objects )
448             throws BeansException
449         {
450             return applicationContext.getBean( aClass, objects );
451         }
452
453         @Override
454         public <T> ObjectProvider<T> getBeanProvider( Class<T> aClass )
455         {
456             return null;
457         }
458
459         @Override
460         public <T> ObjectProvider<T> getBeanProvider( ResolvableType resolvableType )
461         {
462             return null;
463         }
464
465         @Override
466         public Object getBean( String s )
467             throws BeansException
468         {
469             return applicationContext.getBean( s );
470         }
471
472         @Override
473         public <T> T getBean( String s, Class<T> tClass )
474             throws BeansException
475         {
476             return applicationContext.getBean( s, tClass );
477         }
478
479         @Override
480         public <T> T getBean( Class<T> tClass )
481             throws BeansException
482         {
483             return applicationContext.getBean( tClass );
484         }
485
486         @Override
487         public Object getBean( String s, Object... objects )
488             throws BeansException
489         {
490             return applicationContext.getBean( s, objects );
491         }
492
493         @Override
494         public boolean containsBean( String s )
495         {
496             return applicationContext.containsBean( s );
497         }
498
499         @Override
500         public boolean isSingleton( String s )
501             throws NoSuchBeanDefinitionException
502         {
503             return applicationContext.isSingleton( s );
504         }
505
506         @Override
507         public boolean isPrototype( String s )
508             throws NoSuchBeanDefinitionException
509         {
510             return applicationContext.isPrototype( s );
511         }
512
513         @Override
514         public boolean isTypeMatch( String s, Class<?> aClass )
515             throws NoSuchBeanDefinitionException
516         {
517             return applicationContext.isTypeMatch( s, aClass );
518         }
519
520         @Override
521         public Class<?> getType( String s )
522             throws NoSuchBeanDefinitionException
523         {
524             return applicationContext.getType( s );
525         }
526
527         @Override
528         public Class<?> getType( String s, boolean b ) throws NoSuchBeanDefinitionException
529         {
530             return null;
531         }
532
533         @Override
534         public String[] getAliases( String s )
535         {
536             return applicationContext.getAliases( s );
537         }
538
539         @Override
540         public String getMessage( String s, Object[] objects, String s2, Locale locale )
541         {
542             return applicationContext.getMessage( s, objects, s2, locale );
543         }
544
545         @Override
546         public String getMessage( String s, Object[] objects, Locale locale )
547             throws NoSuchMessageException
548         {
549             return applicationContext.getMessage( s, objects, locale );
550         }
551
552         @Override
553         public String getMessage( MessageSourceResolvable messageSourceResolvable, Locale locale )
554             throws NoSuchMessageException
555         {
556             return applicationContext.getMessage( messageSourceResolvable, locale );
557         }
558
559         @Override
560         public Resource[] getResources( String s )
561             throws IOException
562         {
563             return applicationContext.getResources( s );
564         }
565
566         @Override
567         public void publishEvent( Object o )
568         {
569             // no op
570         }
571
572         @Override
573         public String[] getBeanNamesForType( ResolvableType resolvableType )
574         {
575             return new String[0];
576         }
577
578         @Override
579         public String[] getBeanNamesForType( ResolvableType resolvableType, boolean b, boolean b1 )
580         {
581             return new String[0];
582         }
583
584         @Override
585         public boolean isTypeMatch( String s, ResolvableType resolvableType )
586             throws NoSuchBeanDefinitionException
587         {
588             return false;
589         }
590
591         @Override
592         public Resource getResource( String s )
593         {
594             return applicationContext.getResource( s );
595         }
596
597         @Override
598         public ClassLoader getClassLoader()
599         {
600             return applicationContext.getClassLoader();
601         }
602     }
603
604     protected Servlet findServlet( String name )
605         throws Exception
606     {
607         return unauthenticatedRepositoryServlet;
608
609     }
610
611     protected String getSpringConfigLocation()
612     {
613         return "classpath*:/META-INF/spring-context.xml,classpath*:spring-context.xml";
614     }
615
616
617     protected static WebClient newClient()
618     {
619         final WebClient webClient = new WebClient();
620         webClient.getOptions().setJavaScriptEnabled( false );
621         webClient.getOptions().setCssEnabled( false );
622         webClient.getOptions().setAppletEnabled( false );
623         webClient.getOptions().setThrowExceptionOnFailingStatusCode( false );
624         webClient.setAjaxController( new NicelyResynchronizingAjaxController() );
625         return webClient;
626     }
627
628
629     protected WebResponse getWebResponse( String path )
630         throws Exception
631     {
632         return getWebResponse( new GetMethodWebRequest( "http://localhost" + path ) );//, false );
633     }
634
635     protected WebResponse getWebResponse( WebRequest webRequest ) //, boolean followRedirect )
636         throws Exception
637     {
638
639         MockHttpServletRequest request = new MockHttpServletRequest();
640         request.setRequestURI( webRequest.getUrl().getPath() );
641         request.addHeader( "User-Agent", "Apache Archiva unit test" );
642
643         request.setMethod( webRequest.getHttpMethod().name() );
644
645         if ( webRequest.getHttpMethod() == HttpMethod.PUT )
646         {
647             PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast( webRequest );
648             request.setContentType( putRequest.contentType );
649             request.setContent( IOUtils.toByteArray( putRequest.inputStream ) );
650         }
651
652         if ( webRequest instanceof MkColMethodWebRequest )
653         {
654             request.setMethod( "MKCOL" );
655         }
656
657         final MockHttpServletResponse response = execute( request );
658
659         if ( response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
660             || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY )
661         {
662             String location = response.getHeader( "Location" );
663             log.debug( "follow redirect to {}", location );
664             return getWebResponse( new GetMethodWebRequest( location ) );
665         }
666
667         return new WebResponse( null, null, 1 )
668         {
669             @Override
670             public String getContentAsString()
671             {
672                 try
673                 {
674                     return response.getContentAsString();
675                 }
676                 catch ( UnsupportedEncodingException e )
677                 {
678                     throw new RuntimeException( e.getMessage(), e );
679                 }
680             }
681
682             @Override
683             public int getStatusCode()
684             {
685                 return response.getStatus();
686             }
687
688             @Override
689             public String getResponseHeaderValue( String headerName )
690             {
691                 return response.getHeader( headerName );
692             }
693         };
694     }
695
696     protected MockHttpServletResponse execute( HttpServletRequest request )
697         throws Exception
698     {
699         MockHttpServletResponse response = new MockHttpServletResponse()
700         {
701             @Override
702             public String getContentAsString()
703                 throws UnsupportedEncodingException
704             {
705                 String errorMessage = getErrorMessage();
706                 return ( errorMessage != null ) ? errorMessage : super.getContentAsString();
707             }
708         };
709         this.unauthenticatedRepositoryServlet.service( request, response );
710         return response;
711     }
712
713     public static class GetMethodWebRequest
714         extends WebRequest
715     {
716         String url;
717
718         public GetMethodWebRequest( String url )
719             throws Exception
720         {
721             super( new URL( url ) );
722             this.url = url;
723
724         }
725     }
726
727     public static class PutMethodWebRequest
728         extends WebRequest
729     {
730         String url;
731
732         InputStream inputStream;
733
734         String contentType;
735
736         public PutMethodWebRequest( String url, InputStream inputStream, String contentType )
737             throws Exception
738         {
739             super( new URL( url ), HttpMethod.PUT );
740             this.url = url;
741             this.inputStream = inputStream;
742             this.contentType = contentType;
743         }
744
745
746     }
747
748     public static class ServletUnitClient
749     {
750
751         AbstractRepositoryServletTestCase abstractRepositoryServletTestCase;
752
753         public ServletUnitClient( AbstractRepositoryServletTestCase abstractRepositoryServletTestCase )
754         {
755             this.abstractRepositoryServletTestCase = abstractRepositoryServletTestCase;
756         }
757
758         public WebResponse getResponse( WebRequest request )
759             throws Exception
760         {
761             return getResponse( request, false );
762         }
763
764         public WebResponse getResponse( WebRequest request, boolean followRedirect )
765             throws Exception
766         {
767             // alwasy following redirect as it's normal
768             return abstractRepositoryServletTestCase.getWebResponse( request );//, followRedirect );
769         }
770
771         public WebResponse getResource( WebRequest request )
772             throws Exception
773         {
774             return getResponse( request );
775         }
776     }
777
778     public ServletUnitClient getServletUnitClient()
779     {
780         return new ServletUnitClient( this );
781     }
782
783     @Override
784     @After
785     public void tearDown()
786         throws Exception
787     {
788         repositoryRegistry.getRepositories().stream().forEach(r -> r.close());
789
790         if ( Files.exists(repoRootInternal) )
791         {
792             org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootInternal );
793         }
794
795         if ( Files.exists(repoRootLegacy) )
796         {
797             org.apache.archiva.common.utils.FileUtils.deleteQuietly( repoRootLegacy );
798         }
799
800         String appserverBase = System.getProperty( "appserver.base" );
801         if ( StringUtils.isNotEmpty( appserverBase ) )
802         {
803             org.apache.archiva.common.utils.FileUtils.deleteQuietly( Paths.get( appserverBase ) );
804         }
805
806     }
807
808
809     protected void assertFileContents( String expectedContents, Path repoRoot, String subpath )
810         throws IOException
811     {
812         String path = Paths.get(subpath).isAbsolute() ? subpath.substring( 1,subpath.length() ) : subpath;
813         Path actualFile = repoRoot.resolve( path );
814         assertTrue( "File <" + actualFile.toAbsolutePath() + "> should exist.", Files.exists(actualFile) );
815         assertTrue( "File <" + actualFile.toAbsolutePath() + "> should be a file (not a dir/link/device/etc).",
816                     Files.isRegularFile( actualFile ) );
817
818         String actualContents = org.apache.archiva.common.utils.FileUtils.readFileToString( actualFile, Charset.defaultCharset() );
819         assertEquals( "File Contents of <" + actualFile.toAbsolutePath() + ">", expectedContents, actualContents );
820     }
821
822     protected void assertRepositoryValid( RepositoryServlet servlet, String repoId )
823         throws Exception
824     {
825         ManagedRepository repository = servlet.getRepository( repoId );
826         assertNotNull( "Archiva Managed Repository id:<" + repoId + "> should exist.", repository );
827         Path repoRoot = Paths.get( repository.getLocation() );
828         assertTrue( "Archiva Managed Repository id:<" + repoId + "> should have a valid location on disk.",
829                     Files.exists(repoRoot) && Files.isDirectory(repoRoot) );
830     }
831
832     protected void assertResponseOK( WebResponse response )
833     {
834         assertNotNull( "Should have recieved a response", response );
835         Assert.assertEquals( "Should have been an OK response code", //
836                              HttpServletResponse.SC_OK, //
837                              response.getStatusCode() );
838     }
839
840     protected void assertResponseOK( WebResponse response, String path )
841     {
842         assertNotNull( "Should have recieved a response", response );
843         Assert.assertEquals( "Should have been an OK response code for path: " + path, HttpServletResponse.SC_OK,
844                              response.getStatusCode() );
845     }
846
847     protected void assertResponseNotFound( WebResponse response )
848     {
849         assertNotNull( "Should have recieved a response", response );
850         Assert.assertEquals( "Should have been an 404/Not Found response code.", HttpServletResponse.SC_NOT_FOUND,
851                              response.getStatusCode() );
852     }
853
854     protected void assertResponseInternalServerError( WebResponse response )
855     {
856         assertNotNull( "Should have recieved a response", response );
857         Assert.assertEquals( "Should have been an 500/Internal Server Error response code.",
858                              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatusCode() );
859     }
860
861     protected void assertResponseConflictError( WebResponse response )
862     {
863         assertNotNull( "Should have received a response", response );
864         Assert.assertEquals( "Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
865                              response.getStatusCode() );
866     }
867
868     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
869                                                                       boolean blockRedeployments )
870     {
871         ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
872         repo.setId( id );
873         repo.setName( name );
874         repo.setLocation( location.toAbsolutePath().toString() );
875         repo.setBlockRedeployments( blockRedeployments );
876         repo.setType( "MAVEN" );
877         repo.setIndexDir(location.resolve( ".indexer" ).toAbsolutePath().toString());
878         repo.setPackedIndexDir( location.resolve( ".index" ).toAbsolutePath( ).toString( ) );
879
880         return repo;
881     }
882
883     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location,
884                                                                       String layout, boolean blockRedeployments )
885     {
886         ManagedRepositoryConfiguration repo = createManagedRepository( id, name, location, blockRedeployments );
887         repo.setLayout( layout );
888         return repo;
889     }
890
891     protected RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String url )
892     {
893         RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
894         repo.setId( id );
895         repo.setName( name );
896         repo.setUrl( url );
897         return repo;
898     }
899
900     protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
901         throws Exception
902     {
903         repositoryRegistry.setArchivaConfiguration(archivaConfiguration);
904         // repositoryRegistry.reload();
905         archivaConfiguration.save( archivaConfiguration.getConfiguration() );
906
907     }
908
909
910     protected void setupCleanRepo( Path repoRootDir )
911         throws IOException
912     {
913         if (repoRootDir!=null)
914         {
915             org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
916             if ( !Files.exists( repoRootDir ) )
917             {
918                 Files.createDirectories( repoRootDir );
919             }
920         }
921     }
922
923     protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
924     {
925         Path repoFile =  repoRootInternal.resolve( resourcePath );
926         assertFalse( "Managed Repository File <" + repoFile.toAbsolutePath() + "> should not exist.",
927                      Files.exists(repoFile) );
928     }
929
930     protected void setupCleanInternalRepo()
931         throws Exception
932     {
933         setupCleanRepo( repoRootInternal );
934     }
935
936     protected Path populateRepo( Path repoRootManaged, String path, String contents )
937         throws Exception
938     {
939         Path destFile = repoRootManaged.resolve( path );
940         Files.createDirectories( destFile.getParent() );
941         org.apache.archiva.common.utils.FileUtils.writeStringToFile( destFile, Charset.defaultCharset(), contents );
942         return destFile;
943     }
944 }