aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-plugin-api/src/test/java/org/sonar/api/utils/HttpDownloaderTest.java
blob: 5978438e8c61c33bfa747e7fe07b334ecfab88ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
 * SonarQube, open source software quality management tool.
 * Copyright (C) 2008-2014 SonarSource
 * mailto:contact AT sonarsource DOT com
 *
 * SonarQube is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * SonarQube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.api.utils;

import com.google.common.base.Charsets;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.transport.connect.SocketConnection;
import org.sonar.api.config.Settings;
import org.sonar.api.platform.Server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class HttpDownloaderTest {

  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  private static SocketConnection socketConnection;
  private static String baseUrl;

  @BeforeClass
  public static void startServer() throws IOException {
    socketConnection = new SocketConnection(new Container() {
      public void handle(Request req, Response resp) {
        try {
          if (req.getPath().getPath().contains("/redirect/")) {
            resp.setCode(303);
            resp.add("Location", "/");
          }
          else {
            if (req.getPath().getPath().contains("/timeout/")) {
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
            if (req.getPath().getPath().contains("/gzip/")) {
              if (!"gzip".equals(req.getValue("Accept-Encoding"))) {
                throw new IllegalStateException("Should accept gzip");
              }
              resp.set("Content-Encoding", "gzip");
              GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream());
              gzipOutputStream.write("GZIP response".getBytes());
              gzipOutputStream.close();
            }
            else {
              resp.getPrintStream().append("agent=" + req.getValues("User-Agent").get(0));
            }
          }
        } catch (IOException e) {
          throw new IllegalStateException(e);
        } finally {
          try {
            resp.close();
          } catch (IOException e) {
          }
        }
      }
    });
    SocketAddress address = socketConnection.connect(new InetSocketAddress(0));

    baseUrl = "http://localhost:" + ((InetSocketAddress) address).getPort();
  }

  @AfterClass
  public static void stopServer() throws IOException {
    if (null != socketConnection) {
      socketConnection.close();
    }
  }

  @Test
  public void downloadBytes() throws URISyntaxException {
    byte[] bytes = new HttpDownloader(new Settings()).readBytes(new URI(baseUrl));
    assertThat(bytes.length).isGreaterThan(10);
  }

  @Test
  public void readString() throws URISyntaxException {
    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl), Charsets.UTF_8);
    assertThat(text.length()).isGreaterThan(10);
  }

  @Test
  public void readGzipString() throws URISyntaxException {
    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/gzip/"), Charsets.UTF_8);
    assertThat(text).isEqualTo("GZIP response");
  }

  @Test
  public void readStringWithDefaultTimeout() throws URISyntaxException {
    String text = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
    assertThat(text.length()).isGreaterThan(10);
  }

  @Test
  public void readStringWithTimeout() throws URISyntaxException {
    String text = new HttpDownloader(new Settings(), 2000).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
    assertThat(text.length()).isGreaterThan(10);

    thrown.expect(new BaseMatcher<Exception>() {
      @Override
      public boolean matches(Object ex) {
        return ex instanceof SonarException && ((SonarException) ex).getCause() instanceof SocketTimeoutException;
      }

      @Override
      public void describeTo(Description arg0) {
      }
    });
    new HttpDownloader(new Settings(), 100).readString(new URI(baseUrl + "/timeout/"), Charsets.UTF_8);
  }

  @Test(expected = SonarException.class)
  public void failIfServerDown() throws URISyntaxException {
    // I hope that the port 1 is not used !
    new HttpDownloader(new Settings()).readBytes(new URI("http://localhost:1/unknown"));
  }

  @Test
  public void downloadToFile() throws URISyntaxException, IOException {
    File toDir = temporaryFolder.newFolder();
    File toFile = new File(toDir, "downloadToFile.txt");

    new HttpDownloader(new Settings()).download(new URI(baseUrl), toFile);
    assertThat(toFile).exists();
    assertThat(toFile.length()).isGreaterThan(10l);
  }

  @Test
  public void shouldNotCreateFileIfFailToDownload() throws Exception {
    File toDir = temporaryFolder.newFolder();
    File toFile = new File(toDir, "downloadToFile.txt");

    try {
      // I hope that the port 1 is not used !
      new HttpDownloader(new Settings()).download(new URI("http://localhost:1/unknown"), toFile);
    } catch (SonarException e) {
      assertThat(toFile).doesNotExist();
    }
  }

  @Test
  public void userAgentIsSonarVersion() throws URISyntaxException, IOException {
    Server server = mock(Server.class);
    when(server.getVersion()).thenReturn("2.2");

    InputStream stream = new HttpDownloader(server, new Settings()).openStream(new URI(baseUrl));
    Properties props = new Properties();
    props.load(stream);
    stream.close();

    assertThat(props.getProperty("agent")).isEqualTo("SonarQube 2.2");
  }

  @Test
  public void followRedirect() throws URISyntaxException {
    String content = new HttpDownloader(new Settings()).readString(new URI(baseUrl + "/redirect/"), Charsets.UTF_8);
    assertThat(content).contains("agent");
  }

  @Test
  public void shouldGetDirectProxySynthesis() throws URISyntaxException {
    ProxySelector proxySelector = mock(ProxySelector.class);
    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.asList(Proxy.NO_PROXY));
    assertThat(HttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("no proxy");
  }

  @Test
  public void shouldGetProxySynthesis() throws URISyntaxException {
    ProxySelector proxySelector = mock(ProxySelector.class);
    when(proxySelector.select(any(URI.class))).thenReturn(Arrays.<Proxy>asList(new FakeProxy()));
    assertThat(HttpDownloader.BaseHttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector)).isEqualTo("proxy: http://proxy_url:4040");
  }

  @Test
  public void supported_schemes() {
    assertThat(new HttpDownloader(new Settings()).getSupportedSchemes()).contains("http");
  }

  @Test
  public void uri_description() throws URISyntaxException {
    String description = new HttpDownloader(new Settings()).description(new URI("http://sonarsource.org"));
    assertThat(description).matches("http://sonarsource.org \\(.*\\)");
  }
}

class FakeProxy extends Proxy {
  public FakeProxy() {
    super(Type.HTTP, new InetSocketAddress("http://proxy_url", 4040));
  }
}