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