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