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