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 30KB

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