@Test public void call_request_with_defaults() throws Exception { // no parameters, no media type WsRequest wsRequest = new GetRequest("api/issues/search"); answer(new DumbLocalResponse(200, MediaTypes.JSON, "".getBytes(UTF_8), Collections.<String>emptyList())); WsResponse wsResponse = underTest.call(wsRequest); verifyRequested("GET", "api/issues/search", MediaTypes.JSON, Collections.<String, String>emptyMap()); assertThat(wsResponse.code()).isEqualTo(200); assertThat(wsResponse.content()).isEqualTo(""); assertThat(IOUtils.toString(wsResponse.contentReader())).isEqualTo(""); assertThat(IOUtils.toString(wsResponse.contentStream())).isEqualTo(""); assertThat(wsResponse.contentType()).isEqualTo(MediaTypes.JSON); }
private void failIfUnauthorized(WsResponse response) { int code = response.code(); if (code == HTTP_UNAUTHORIZED) { response.close(); if (hasCredentials) { // credentials are not valid throw MessageException.of(format("Not authorized. Please check the properties %s and %s.", CoreProperties.LOGIN, CoreProperties.PASSWORD)); } // not authenticated - see https://jira.sonarsource.com/browse/SONAR-4048 throw MessageException.of(format("Not authorized. Analyzing this project requires to be authenticated. " + "Please provide the values of the properties %s and %s.", CoreProperties.LOGIN, CoreProperties.PASSWORD)); } if (code == HTTP_FORBIDDEN) { throw MessageException.of("You're not authorized to run analysis. Please contact the project administrator."); } if (code == HTTP_BAD_REQUEST) { String jsonMsg = tryParseAsJsonError(response.content()); if (jsonMsg != null) { throw MessageException.of(jsonMsg); } } // if failed, throws an HttpException response.failIfNotSuccessful(); }
/** * If an exception is not thrown, the response needs to be closed by either calling close() directly, or closing the * body content's stream/reader. * * @throws IllegalStateException if the request could not be executed due to a connectivity problem or timeout. Because networks can * fail during an exchange, it is possible that the remote server accepted the request before the failure * @throws MessageException if there was a problem with authentication or if a error message was parsed from the response. * @throws HttpException if the response code is not in range [200..300). Consider using {@link #createErrorMessage(HttpException)} to create more relevant messages for the users. */ public WsResponse call(WsRequest request) { Preconditions.checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode"); Profiler profiler = Profiler.createIfDebug(LOG).start(); WsResponse response = target.wsConnector().call(request); profiler.stopDebug(format("%s %d %s", request.getMethod(), response.code(), response.requestUrl())); failIfUnauthorized(response); return response; }
public static <T extends Message> T convert(WsResponse response, Parser<T> parser) { try (InputStream byteStream = response.contentStream()) { byte[] bytes = IOUtils.toByteArray(byteStream); // HTTP header "Content-Type" is not verified. It may be different than protobuf. return parser.parseFrom(bytes); } catch (Exception e) { throw new IllegalStateException("Fail to parse protobuf response of " + response.requestUrl(), e); } }
/** * * This is part of the internal API. * This is a GET request. * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/installed">Further information about this action online (including a response example)</a> * @since 5.2 */ public String installed(InstalledRequest request) { return call( new GetRequest(path("installed")) .setParam("f", request.getF() == null ? null : request.getF().stream().collect(Collectors.joining(","))) .setMediaType(MediaTypes.JSON) ).content(); }
@Test public void test_ws_parameters() throws Exception { when(properties.organizationKey()).thenReturn(Optional.of("MyOrg")); WsResponse response = mock(WsResponse.class); PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out); Ce.SubmitResponse.newBuilder().build().writeTo(out); out.close(); when(response.failIfNotSuccessful()).thenReturn(response); when(response.contentStream()).thenReturn(in); when(wsClient.call(any(WsRequest.class))).thenReturn(response); underTest.upload(temp.newFile()); ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class); verify(wsClient).call(capture.capture()); WsRequest wsRequest = capture.getValue(); assertThat(wsRequest.getParameters().getKeys()).containsOnly("organization", "projectKey"); assertThat(wsRequest.getParameters().getValue("organization")).isEqualTo("MyOrg"); assertThat(wsRequest.getParameters().getValue("projectKey")).isEqualTo("org.sonarsource.sonarqube:sonarqube"); }
private static void downloadBinaryTo(InstalledPlugin plugin, File downloadedFile, WsResponse response) { try (InputStream stream = response.contentStream()) { FileUtils.copyInputStreamToFile(stream, downloadedFile); } catch (IOException e) { throw new IllegalStateException(format("Fail to download plugin [%s] into %s", plugin.key, downloadedFile), e); } }
private Rules.ShowResponse showRule(String ruleKey) { GetRequest getRequest = new GetRequest("api/rules/show").setParam("key", ruleKey).setMediaType(MediaTypes.PROTOBUF); WsResponse wsResponse = wsClient.wsConnector().call(getRequest); if (wsResponse.code() != 200) { throw new HttpException(wsClient.wsConnector().baseUrl() + toString(getRequest), wsResponse.code(), wsResponse.content()); } try { return Rules.ShowResponse.parseFrom(wsResponse.contentStream()); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } }
private void failIfUnauthorized(WsResponse response) { if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) { if (hasCredentials) { // credentials are not valid throw MessageException.of(format("Not authorized. Please check the properties %s and %s.", CoreProperties.LOGIN, CoreProperties.PASSWORD)); } // not authenticated - see https://jira.sonarsource.com/browse/SONAR-4048 throw MessageException.of(format("Not authorized. Analyzing this project requires to be authenticated. " + "Please provide the values of the properties %s and %s.", CoreProperties.LOGIN, CoreProperties.PASSWORD)); } if (response.code() == HttpURLConnection.HTTP_FORBIDDEN) { // SONAR-4397 Details are in response content throw MessageException.of(tryParseAsJsonError(response.content())); } response.failIfNotSuccessful(); }
/** * Gets information about the plugins installed on server (filename, checksum) */ private InstalledPlugin[] listInstalledPlugins() { Profiler profiler = Profiler.create(LOG).startInfo("Load plugins index"); GetRequest getRequest = new GetRequest(PLUGINS_WS_URL); InstalledPlugins installedPlugins; try (Reader reader = wsClient.call(getRequest).contentReader()) { installedPlugins = new Gson().fromJson(reader, InstalledPlugins.class); } catch (Exception e) { throw new IllegalStateException("Fail to parse response of " + PLUGINS_WS_URL, e); } profiler.stopInfo(); return installedPlugins.plugins; }
public String getHttp(String url, @Nullable String token) { String baseUrl = StringUtils.substringBeforeLast(url, "/"); String path = StringUtils.substringAfterLast(url, "/"); HttpConnector httpConnector = HttpConnector.newBuilder() .userAgent("Scanner for Jenkins") .url(baseUrl) .credentials(token, null) .build(); WsResponse response = httpConnector.call(new GetRequest(path)); response.failIfNotSuccessful(); return response.content(); } }
protected WsResponse call(WsRequest request) { return wsConnector.call(request).failIfNotSuccessful(); }
@Test public void support_base_url_with_context() { // just to be sure assertThat(serverUrl).endsWith("/"); underTest = HttpConnector.newBuilder().url(serverUrl + "sonar").build(); GetRequest request = new GetRequest("api/issues/search"); answerHelloWorld(); assertThat(underTest.call(request).requestUrl()).isEqualTo(serverUrl + "sonar/api/issues/search"); request = new GetRequest("/api/issues/search"); answerHelloWorld(); assertThat(underTest.call(request).requestUrl()).isEqualTo(serverUrl + "sonar/api/issues/search"); }
@Test public void http_error() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); PostRequest request = new PostRequest("api/issues/search"); underTest = HttpConnector.newBuilder().url(serverUrl).build(); WsResponse wsResponse = underTest.call(request); assertThat(wsResponse.code()).isEqualTo(404); }
/** * * This is part of the internal API. * This is a GET request. * @see <a href="https://next.sonarqube.com/sonarqube/web_api/batch/index">Further information about this action online (including a response example)</a> * @since 4.4 */ public String index() { return call( new GetRequest(path("index")) .setMediaType(MediaTypes.JSON) ).content(); }
@Test public void test_send_branches_characteristics() throws Exception { String orgName = "MyOrg"; when(properties.organizationKey()).thenReturn(Optional.of(orgName)); String branchName = "feature"; when(branchConfiguration.branchName()).thenReturn(branchName); when(branchConfiguration.branchType()).thenReturn(SHORT); WsResponse response = mock(WsResponse.class); PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out); Ce.SubmitResponse.newBuilder().build().writeTo(out); out.close(); when(response.failIfNotSuccessful()).thenReturn(response); when(response.contentStream()).thenReturn(in); when(wsClient.call(any(WsRequest.class))).thenReturn(response); underTest.upload(temp.newFile()); ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class); verify(wsClient).call(capture.capture()); WsRequest wsRequest = capture.getValue(); assertThat(wsRequest.getParameters().getKeys()).hasSize(3); assertThat(wsRequest.getParameters().getValues("organization")).containsExactly(orgName); assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube"); assertThat(wsRequest.getParameters().getValues("characteristic")) .containsExactlyInAnyOrder("branch=" + branchName, "branchType=" + SHORT.name()); }
private Map<String, QualityProfile> call(String url) throws IOException { GetRequest getRequest = new GetRequest(url); try (InputStream is = wsClient.call(getRequest).contentStream()) { SearchWsResponse profiles = SearchWsResponse.parseFrom(is); List<QualityProfile> profilesList = profiles.getProfilesList(); return profilesList.stream().collect(toMap(QualityProfile::getLanguage, identity(), throwingMerger(), LinkedHashMap::new)); } }
public static <T extends Message> T convert(WsResponse response, Parser<T> parser) { try (InputStream byteStream = response.contentStream()) { byte[] bytes = IOUtils.toByteArray(byteStream); // HTTP header "Content-Type" is not verified. It may be different than protobuf. return parser.parseFrom(bytes); } catch (Exception e) { throw new IllegalStateException("Fail to parse protobuf response of " + response.requestUrl(), e); } }
public static void mockReader(ScannerWsClient mock, Reader reader) { WsResponse response = mock(WsResponse.class); when(response.contentReader()).thenReturn(reader); when(mock.call(any(WsRequest.class))).thenReturn(response); }
@Test public void parse_upload_error_message() throws IOException { HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}"); WsResponse response = mock(WsResponse.class); when(response.failIfNotSuccessful()).thenThrow(ex); when(wsClient.call(any(WsRequest.class))).thenReturn(response); exception.expect(MessageException.class); exception.expectMessage("Failed to upload report - Organization with key 'MyOrg' does not exist"); underTest.upload(temp.newFile()); }