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