You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractRepositoryServletTestCase.java 29KB

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