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

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