]> source.dussan.org Git - archiva.git/blob
c4247c0f088ec063f60cbd98b2cc8816980b579f
[archiva.git] /
1 package org.apache.archiva.rest.services;
2 /*
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  */
20
21
22 import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
25 import org.apache.archiva.redback.rest.services.AbstractRestServicesTest;
26 import org.apache.archiva.rest.api.services.*;
27 import org.apache.archiva.security.common.ArchivaRoleConstants;
28 import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
29 import org.apache.commons.io.FileUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
32 import org.apache.cxf.jaxrs.client.WebClient;
33 import org.junit.Assume;
34 import org.junit.Before;
35 import org.junit.BeforeClass;
36 import org.junit.runner.RunWith;
37 import org.slf4j.LoggerFactory;
38
39 import javax.ws.rs.core.MediaType;
40 import java.io.IOException;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.Paths;
44 import java.util.Collections;
45 import java.util.Date;
46 import java.util.Locale;
47
48 /**
49  * @author Olivier Lamy
50  */
51 @RunWith(ArchivaBlockJUnit4ClassRunner.class)
52 public abstract class AbstractArchivaRestTest
53     extends AbstractRestServicesTest
54 {
55
56     // START SNIPPET: authz-header
57     // guest with an empty password
58     public static String guestAuthzHeader =
59         "Basic " + org.apache.cxf.common.util.Base64Utility.encode( ( "guest" + ":" ).getBytes() );
60
61     // with an other login/password
62     //public String authzHeader =
63     //    "Basic " + org.apache.cxf.common.util.Base64Utility.encode( ( "login" + ":password" ).getBytes() );
64
65     // END SNIPPET: authz-header
66
67
68     @BeforeClass
69     public static void chekRepo()
70     {
71         Assume.assumeTrue( !System.getProperty( "appserver.base" ).contains( " " ) );
72         LoggerFactory.getLogger( AbstractArchivaRestTest.class.getName() ).
73             error( "Rest services unit test must be run in a folder with no space" );
74         // skygo: was not possible to fix path in this particular module
75         // Skip test if not in proper folder , otherwise test are not fair coz repository
76         // cannot have space in their name.
77     }
78
79     @Override
80     @Before
81     public void startServer()
82         throws Exception
83     {
84         Path appServerBase = Paths.get( System.getProperty( "appserver.base" ) );
85
86         removeAppsubFolder( appServerBase, "jcr" );
87         removeAppsubFolder( appServerBase, "conf" );
88         removeAppsubFolder( appServerBase, "data" );
89
90         super.startServer();
91     }
92
93
94     private void removeAppsubFolder( Path appServerBase, String folder )
95         throws Exception
96     {
97         Path directory = appServerBase.resolve( folder );
98         if ( Files.exists(directory) )
99         {
100             org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory );
101         }
102     }
103
104     @Override
105     protected String getSpringConfigLocation()
106     {
107         return "classpath*:META-INF/spring-context.xml,classpath:META-INF/spring-context-test.xml";
108     }
109
110     @Override
111     protected String getRestServicesPath()
112     {
113         return "restServices";
114     }
115
116     protected RepositoriesService getRepositoriesService()
117     {
118         return getRepositoriesService( null );
119     }
120
121     protected <T> T getService( Class<T> clazz, String authzHeader )
122     {
123         T service = JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/", clazz,
124                                                Collections.singletonList( new JacksonJaxbJsonProvider() ) );
125
126         if ( authzHeader != null )
127         {
128             WebClient.client( service ).header( "Authorization", authzHeader );
129         }
130         WebClient.client(service).header("Referer","http://localhost:"+port);
131         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000000 );
132         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
133         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
134         return service;
135     }
136
137     protected ProxyConnectorRuleService getProxyConnectorRuleService( String authzHeader )
138     {
139         return getService( ProxyConnectorRuleService.class, authzHeader );
140     }
141
142     protected MergeRepositoriesService getMergeRepositoriesService( String authzHeader )
143     {
144         return getService( MergeRepositoriesService.class, authzHeader );
145     }
146
147     protected RepositoriesService getRepositoriesService( String authzHeader )
148     {
149         return getService( RepositoriesService.class, authzHeader );
150
151     }
152
153     protected ManagedRepositoriesService getManagedRepositoriesService( String authzHeader )
154     {
155         return getService( ManagedRepositoriesService.class, authzHeader );
156     }
157
158     protected PingService getPingService()
159     {
160         return getService( PingService.class, null );
161     }
162     
163     protected PluginsService getPluginsService()
164     {
165         PluginsService service = getService( PluginsService.class, null );
166         WebClient.client( service ).accept( MediaType.TEXT_PLAIN );
167         WebClient.client( service ).type( MediaType.TEXT_PLAIN );
168         return service;
169     }
170
171     protected RemoteRepositoriesService getRemoteRepositoriesService()
172     {
173         return getService( RemoteRepositoriesService.class, null );
174
175
176     }
177
178     protected RepositoryGroupService getRepositoryGroupService()
179     {
180         return JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
181                                           RepositoryGroupService.class,
182                                           Collections.singletonList( new JacksonJaxbJsonProvider() ) );
183     }
184
185     protected ProxyConnectorService getProxyConnectorService()
186     {
187         ProxyConnectorService service =
188             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
189                                        ProxyConnectorService.class,
190                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
191
192         WebClient.client( service ).header( "Authorization", authorizationHeader );
193         WebClient.client(service).header("Referer","http://localhost:"+port);
194         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000 );
195         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
196         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
197         return service;
198     }
199
200     protected NetworkProxyService getNetworkProxyService()
201     {
202         NetworkProxyService service =
203             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
204                                        NetworkProxyService.class,
205                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
206
207         WebClient.client( service ).header( "Authorization", authorizationHeader );
208         WebClient.client(service).header("Referer","http://localhost:"+port);
209         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000 );
210         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
211         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
212         return service;
213     }
214
215     protected ArchivaAdministrationService getArchivaAdministrationService()
216     {
217         ArchivaAdministrationService service =
218             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
219                                        ArchivaAdministrationService.class,
220                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
221
222         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
223         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
224
225         WebClient.client( service ).header( "Authorization", authorizationHeader );
226         WebClient.client(service).header("Referer","http://localhost:"+port);
227
228         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000 );
229         return service;
230     }
231
232     protected RedbackRuntimeConfigurationService getRedbackRuntimeConfigurationService()
233     {
234         RedbackRuntimeConfigurationService service =
235             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
236                                        RedbackRuntimeConfigurationService.class,
237                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
238
239         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
240         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
241
242         WebClient.client( service ).header( "Authorization", authorizationHeader );
243         WebClient.client(service).header("Referer","http://localhost:"+port);
244         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 300000 );
245         return service;
246     }
247
248     protected BrowseService getBrowseService( String authzHeader, boolean useXml )
249     {
250         // START SNIPPET: cxf-browseservice-creation
251         BrowseService service =
252             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
253                                        BrowseService.class,
254                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
255         // to add authentification
256         if ( authzHeader != null )
257         {
258             WebClient.client( service ).header( "Authorization", authzHeader );
259         }
260         // Set the Referer header to your archiva server url
261         WebClient.client(service).header("Referer","http://localhost:"+port);
262
263         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000000 );
264         if ( useXml )
265         {
266             WebClient.client( service ).accept( MediaType.APPLICATION_XML_TYPE );
267             WebClient.client( service ).type( MediaType.APPLICATION_XML_TYPE );
268         }
269         else
270         {
271             WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
272             WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
273         }
274         return service;
275         // END SNIPPET: cxf-browseservice-creation
276
277     }
278
279     protected SearchService getSearchService( String authzHeader )
280     {
281         // START SNIPPET: cxf-searchservice-creation        
282         SearchService service =
283             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
284                                        SearchService.class,
285                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
286         // to add authentification
287         if ( authzHeader != null )
288         {
289             WebClient.client( service ).header( "Authorization", authzHeader );
290         }
291         // Set the Referer header to your archiva server url
292         WebClient.client(service).header("Referer","http://localhost:"+port);
293         // to configure read timeout
294         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000000 );
295         // if you want to use json as exchange format xml is supported too
296         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
297         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
298         return service;
299         // END SNIPPET: cxf-searchservice-creation
300
301     }
302
303     protected CommonServices getCommonServices( String authzHeader )
304     {
305         CommonServices service =
306             JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
307                                        CommonServices.class,
308                                        Collections.singletonList( new JacksonJaxbJsonProvider() ) );
309
310         if ( authzHeader != null )
311         {
312             WebClient.client( service ).header( "Authorization", authzHeader );
313         }
314         WebClient.client(service).header("Referer","http://localhost:"+port);
315         WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000000 );
316         WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
317         WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
318         return service;
319     }
320
321     protected ManagedRepository getTestManagedRepository()
322     {
323         String location = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repo" ).toAbsolutePath().toString();
324         return new ManagedRepository( Locale.getDefault(),  "TEST", "test", location, "default", true, true, false, "2 * * * * ?", null,
325                                       false, 2, 3, true, false, "my nice repo", false );
326
327     }
328
329     protected String getBaseUrl()
330     {
331         String baseUrlSysProps = System.getProperty( "archiva.baseRestUrl" );
332         return StringUtils.isBlank( baseUrlSysProps ) ? "http://localhost:" + port : baseUrlSysProps;
333     }
334
335     //-----------------------------------------------------
336     // utilities to create repos for testing
337     //-----------------------------------------------------
338
339     static final String TARGET_REPO_ID = "test-copy-target";
340
341     static final String SOURCE_REPO_ID = "test-origin-repo";
342
343     protected void initSourceTargetRepo()
344         throws Exception
345     {
346         Path targetRepo = Paths.get( "target/test-repo-copy" );
347         if ( Files.exists(targetRepo) )
348         {
349             org.apache.archiva.common.utils.FileUtils.deleteDirectory( targetRepo );
350         }
351         assertFalse( Files.exists(targetRepo) );
352         Files.createDirectories( targetRepo );
353
354         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( TARGET_REPO_ID ) != null )
355         {
356             getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( TARGET_REPO_ID, true );
357             assertNull( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( TARGET_REPO_ID ) );
358         }
359         ManagedRepository managedRepository = getTestManagedRepository();
360         managedRepository.setId( TARGET_REPO_ID );
361         managedRepository.setLocation( targetRepo.toAbsolutePath().toString() );
362         managedRepository.setCronExpression( "* * * * * ?" );
363         getManagedRepositoriesService( authorizationHeader ).addManagedRepository( managedRepository );
364         assertNotNull( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( TARGET_REPO_ID ) );
365
366         Path originRepo = Paths.get( "target/test-origin-repo" );
367         if ( Files.exists(originRepo) )
368         {
369             org.apache.archiva.common.utils.FileUtils.deleteDirectory( originRepo );
370         }
371         assertFalse( Files.exists(originRepo) );
372         FileUtils.copyDirectory( Paths.get( "src/test/repo-with-osgi" ).toAbsolutePath().toFile(), originRepo.toAbsolutePath().toFile() );
373
374         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( SOURCE_REPO_ID ) != null )
375         {
376             getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( SOURCE_REPO_ID, true );
377             assertNull( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( SOURCE_REPO_ID ) );
378         }
379
380         managedRepository = getTestManagedRepository();
381         managedRepository.setId( SOURCE_REPO_ID );
382         managedRepository.setLocation( originRepo.toAbsolutePath().toString() );
383
384         getManagedRepositoriesService( authorizationHeader ).addManagedRepository( managedRepository );
385         assertNotNull( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( SOURCE_REPO_ID ) );
386
387         getArchivaAdministrationService().enabledKnownContentConsumer( "create-missing-checksums" );
388         getArchivaAdministrationService().enabledKnownContentConsumer( "metadata-updater" );
389
390     }
391
392     protected void cleanRepos()
393         throws Exception
394     {
395
396         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( TARGET_REPO_ID ) != null )
397         {
398             try
399             {
400                 getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( TARGET_REPO_ID, true );
401                 assertNull(
402                     getManagedRepositoriesService( authorizationHeader ).getManagedRepository( TARGET_REPO_ID ) );
403             }
404             catch ( Exception e )
405             {
406                 log.warn( "skip issue while cleaning test repository: this can cause test failure", e );
407             }
408         }
409         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( SOURCE_REPO_ID ) != null )
410         {
411             try
412             {
413                 getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( SOURCE_REPO_ID, true );
414                 assertNull(
415                     getManagedRepositoriesService( authorizationHeader ).getManagedRepository( SOURCE_REPO_ID ) );
416             }
417             catch ( Exception e )
418             {
419                 log.warn( "skip issue while cleaning test repository: this can cause test failure", e );
420             }
421         }
422
423     }
424
425     protected void createAndIndexRepo( String testRepoId, String repoPath, boolean stageNeeded )
426         throws ArchivaRestServiceException, IOException, RedbackServiceException
427     {
428         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( testRepoId ) != null )
429         {
430             getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( testRepoId, false );
431         }
432
433         ManagedRepository managedRepository = new ManagedRepository(Locale.getDefault());
434         managedRepository.setId( testRepoId );
435         managedRepository.setName( "test repo" );
436
437         Path badContent = Paths.get( repoPath, "target" );
438         if ( Files.exists(badContent) )
439         {
440             org.apache.archiva.common.utils.FileUtils.deleteDirectory( badContent );
441         }
442
443         Path file = Paths.get( repoPath );
444         if ( !file.isAbsolute() )
445         {
446             repoPath = getBasedir() + "/" + repoPath;
447         }
448
449         managedRepository.setLocation( Paths.get( repoPath ).toString() );
450         managedRepository.setIndexDirectory(
451             System.getProperty( "java.io.tmpdir" ) + "/.index-" + Long.toString( new Date().getTime() ) );
452
453         managedRepository.setStageRepoNeeded( stageNeeded );
454         managedRepository.setSnapshots( true );
455
456         //managedRepository.setScanned( scanned );
457
458         ManagedRepositoriesService service = getManagedRepositoriesService( authorizationHeader );
459         service.addManagedRepository( managedRepository );
460
461         getRoleManagementService( authorizationHeader ).assignTemplatedRole(
462             ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, testRepoId, "admin" );
463
464         getRoleManagementService( authorizationHeader ).assignTemplatedRole(
465             ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, testRepoId, "guest" );
466     }
467
468     protected void scanRepo( String testRepoId )
469         throws ArchivaRestServiceException
470     {
471         getRepositoriesService( authorizationHeader ).scanRepositoryNow( testRepoId, true );
472     }
473
474     protected void createAndIndexRepo( String testRepoId, String repoPath )
475         throws Exception
476     {
477         createAndIndexRepo( testRepoId, repoPath, false );
478         scanRepo( testRepoId );
479     }
480
481     protected void createStagedNeededRepo( String testRepoId, String repoPath, boolean scan )
482         throws Exception
483     {
484         createAndIndexRepo( testRepoId, repoPath, true );
485         if ( scan )
486         {
487             scanRepo( testRepoId );
488         }
489
490         RepositoriesService repositoriesService = getRepositoriesService( authorizationHeader );
491         repositoriesService.scanRepositoryDirectoriesNow( testRepoId );
492         if ( scan )
493         {
494             repositoriesService.scanRepositoryNow( testRepoId + "-stage", true );
495             repositoriesService.scanRepositoryDirectoriesNow( testRepoId + "-stage" );
496         }
497     }
498
499
500     protected void deleteTestRepo( String id )
501         throws Exception
502     {
503         if ( getManagedRepositoriesService( authorizationHeader ).getManagedRepository( id ) != null )
504         {
505             getManagedRepositoriesService( authorizationHeader ).deleteManagedRepository( id, false );
506         }
507     }
508
509     public Path getBasedir()
510     {
511         return Paths.get(System.getProperty( "basedir" ));
512     }
513
514     protected void waitForScanToComplete( String repoId )
515         throws ArchivaRestServiceException, InterruptedException
516     {
517         while ( getRepositoriesService( authorizationHeader ).alreadyScanning( repoId ) ) {
518             // Would be better to cancel, if we had that capacity
519             Thread.sleep( 100 );
520         }
521     }
522 }