]> source.dussan.org Git - archiva.git/blob
88588f653a32928824f136e21f3f3441de7a6eaf
[archiva.git] /
1 package org.apache.archiva.proxy;
2
3 /*
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21
22 import org.apache.archiva.configuration.ArchivaConfiguration;
23 import org.apache.archiva.configuration.NetworkProxyConfiguration;
24 import org.apache.archiva.configuration.ProxyConnectorConfiguration;
25 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
26 import org.apache.archiva.model.ArtifactReference;
27 import org.apache.archiva.policies.CachedFailuresPolicy;
28 import org.apache.archiva.policies.ChecksumPolicy;
29 import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
30 import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
31 import org.apache.archiva.policies.ReleasesPolicy;
32 import org.apache.archiva.policies.SnapshotsPolicy;
33 import org.apache.archiva.proxy.model.RepositoryProxyHandler;
34 import org.apache.archiva.repository.*;
35 import org.apache.archiva.repository.base.BasicManagedRepository;
36 import org.apache.archiva.repository.storage.StorageAsset;
37 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
38 import org.apache.commons.io.FileUtils;
39 import org.apache.maven.wagon.Wagon;
40 import org.apache.maven.wagon.providers.http.HttpWagon;
41 import org.assertj.core.api.Assertions;
42 import org.eclipse.jetty.server.Handler;
43 import org.eclipse.jetty.server.HttpConnectionFactory;
44 import org.eclipse.jetty.server.Request;
45 import org.eclipse.jetty.server.Server;
46 import org.eclipse.jetty.server.ServerConnector;
47 import org.eclipse.jetty.server.handler.AbstractHandler;
48 import org.junit.After;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.springframework.context.ApplicationContext;
53 import org.springframework.test.context.ContextConfiguration;
54
55 import javax.inject.Inject;
56 import javax.servlet.ServletException;
57 import javax.servlet.http.HttpServletRequest;
58 import javax.servlet.http.HttpServletResponse;
59 import java.io.IOException;
60 import java.nio.charset.Charset;
61 import java.nio.file.Files;
62 import java.nio.file.Path;
63 import java.nio.file.Paths;
64
65 import static org.junit.Assert.*;
66
67 /**
68  * Integration test for connecting over a HTTP proxy.
69  *
70  *
71  */
72 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
73 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
74 public class HttpProxyTransferTest
75 {
76     private static final String PROXY_ID = "proxy";
77
78     private static final String MANAGED_ID = "default-managed-repository";
79
80     private static final String PROXIED_ID = "proxied1";
81
82     private static final String PROXIED_BASEDIR = "src/test/repositories/proxied1";
83
84     private RepositoryProxyHandler proxyHandler;
85
86     private ManagedRepositoryContent managedDefaultRepository;
87
88     @Inject
89     private ApplicationContext applicationContext;
90
91     @Inject
92     private RepositoryRegistry repositoryRegistry;
93
94     @Inject
95     private ArchivaConfiguration config;
96
97     @Inject
98     private ProxyRegistry proxyRegistry;
99
100     private Server server;
101
102     protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
103             throws Exception
104     {
105         ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
106         repositoryRegistry.putRepository(repo);
107         return repositoryRegistry.getManagedRepository(id).getContent();
108     }
109
110     @Before
111     public void setUp()
112         throws Exception
113     {
114         proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
115
116         // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
117         // made a complete mock
118         config.getConfiguration().getProxyConnectors().clear();
119
120         // Setup source repository (using default layout)
121         String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
122
123         Path destRepoDir = Paths.get( repoPath );
124
125         // Cleanout destination dirs.
126         if ( Files.exists(destRepoDir))
127         {
128             FileUtils.deleteDirectory( destRepoDir.toFile() );
129         }
130
131         // Make the destination dir.
132         Files.createDirectories(destRepoDir);
133
134
135         Handler handler = new AbstractHandler()
136         {
137             @Override
138             public void handle( String s, Request request, HttpServletRequest httpServletRequest,
139                                 HttpServletResponse response )
140                 throws IOException, ServletException
141             {
142                 response.setContentType( "text/plain" );
143                 response.setStatus( HttpServletResponse.SC_OK );
144                 response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
145                 assertNotNull( request.getHeader( "Proxy-Connection" ) );
146
147                 ( (Request) request ).setHandled( true );
148             }
149
150             public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch )
151                 throws IOException, ServletException
152             {
153                 response.setContentType( "text/plain" );
154                 response.setStatus( HttpServletResponse.SC_OK );
155                 response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
156                 assertNotNull( request.getHeader( "Proxy-Connection" ) );
157
158                 ( (Request) request ).setHandled( true );
159             }
160         };
161
162         server = new Server(  );
163         ServerConnector serverConnector = new ServerConnector( server, new HttpConnectionFactory());
164         server.addConnector( serverConnector );
165         server.setHandler( handler );
166         server.start();
167
168         int port = serverConnector.getLocalPort();
169
170         NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
171         proxyConfig.setHost( "localhost" );
172         proxyConfig.setPort( port );
173         proxyConfig.setProtocol( "http" );
174         proxyConfig.setId( PROXY_ID );
175         config.getConfiguration().addNetworkProxy( proxyConfig );
176         ( (MockConfiguration) config ).triggerChange("networkProxies.networkProxy(0).host", "localhost");
177
178         // Setup target (proxied to) repository.
179         RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
180
181         repoConfig.setId( PROXIED_ID );
182         repoConfig.setName( "Proxied Repository 1" );
183         repoConfig.setLayout( "default" );
184         repoConfig.setUrl( "http://www.example.com/" );
185
186         config.getConfiguration().addRemoteRepository( repoConfig );
187
188         Wagon wagon = new HttpWagon( );
189         WagonDelegate delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
190         delegate.setDelegate( wagon );
191
192         proxyRegistry.reload();
193         repositoryRegistry.reload();
194
195         managedDefaultRepository = createRepository(MANAGED_ID, "Default Managed Repository", repoPath, "default");
196
197     }
198
199     @After
200     public void tearDown()
201         throws Exception
202     {
203         if (server!=null) {
204             server.stop();
205         }
206     }
207
208     @Test
209     public void testGetOverHttpProxy()
210         throws Exception
211     {
212         Assertions.assertThat( System.getProperty( "http.proxyHost", "" ) ).isEmpty();
213         Assertions.assertThat( System.getProperty( "http.proxyPort", "" ) ).isEmpty();
214
215         String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
216
217         // Configure Connector (usually done within archiva.xml configuration)
218         addConnector();
219
220         managedDefaultRepository = repositoryRegistry.getManagedRepository(MANAGED_ID).getContent();
221
222         Path expectedFile = Paths.get( managedDefaultRepository.getRepoRoot() ).resolve( path );
223         Files.deleteIfExists( expectedFile );
224         ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
225
226         // Attempt the proxy fetch.
227         StorageAsset downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository.getRepository(), artifact );
228
229         Path sourceFile = Paths.get( PROXIED_BASEDIR, path );
230         assertNotNull( "Expected File should not be null.", expectedFile );
231         assertNotNull( "Actual File should not be null.", downloadedFile );
232
233         assertTrue( "Check actual file exists.", Files.exists(downloadedFile.getFilePath()));
234         assertTrue( "Check filename path is appropriate.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
235         assertTrue( "Check file path matches.", Files.isSameFile( expectedFile, downloadedFile.getFilePath()));
236
237         String expectedContents = FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
238         String actualContents = FileUtils.readFileToString( downloadedFile.getFilePath().toFile(), Charset.defaultCharset() );
239         assertEquals( "Check file contents.", expectedContents, actualContents );
240
241         Assertions.assertThat( System.getProperty( "http.proxyHost" , "") ).isEmpty();
242         Assertions.assertThat( System.getProperty( "http.proxyPort" , "") ).isEmpty();
243     }
244
245     private void addConnector()
246     {
247         ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
248         connectorConfig.setProxyId( PROXY_ID );
249         connectorConfig.setSourceRepoId( MANAGED_ID );
250         connectorConfig.setTargetRepoId( PROXIED_ID );
251         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, ChecksumPolicy.FIX.getId() );
252         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, ReleasesPolicy.ONCE.getId() );
253         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, SnapshotsPolicy.ONCE.getId() );
254         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, CachedFailuresPolicy.NO.getId() );
255         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS,
256                                    PropagateErrorsDownloadPolicy.QUEUE.getId() );
257         connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE,
258                                    PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT.getId() );
259
260         int count = config.getConfiguration().getProxyConnectors().size();
261         config.getConfiguration().addProxyConnector( connectorConfig );
262
263         // Proper Triggering ...
264         String prefix = "proxyConnectors.proxyConnector(" + count + ")";
265         ( (MockConfiguration) config ).triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
266     }
267 }