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

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