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.

DefaultScannerWsClient.java 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.scanner.bootstrap;
  21. import com.google.gson.JsonArray;
  22. import com.google.gson.JsonElement;
  23. import com.google.gson.JsonObject;
  24. import com.google.gson.JsonParser;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import javax.annotation.CheckForNull;
  28. import org.apache.commons.lang.StringUtils;
  29. import org.sonar.api.CoreProperties;
  30. import org.sonar.api.utils.MessageException;
  31. import org.sonar.api.utils.log.Logger;
  32. import org.sonar.api.utils.log.Loggers;
  33. import org.sonar.api.utils.log.Profiler;
  34. import org.sonarqube.ws.client.HttpException;
  35. import org.sonarqube.ws.client.WsClient;
  36. import org.sonarqube.ws.client.WsConnector;
  37. import org.sonarqube.ws.client.WsRequest;
  38. import org.sonarqube.ws.client.WsResponse;
  39. import static java.lang.String.format;
  40. import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
  41. import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
  42. import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
  43. import static org.sonar.api.utils.Preconditions.checkState;
  44. public class DefaultScannerWsClient implements ScannerWsClient {
  45. private static final int MAX_ERROR_MSG_LEN = 128;
  46. private static final Logger LOG = Loggers.get(DefaultScannerWsClient.class);
  47. private final WsClient target;
  48. private final boolean hasCredentials;
  49. private final GlobalAnalysisMode globalMode;
  50. public DefaultScannerWsClient(WsClient target, boolean hasCredentials, GlobalAnalysisMode globalMode) {
  51. this.target = target;
  52. this.hasCredentials = hasCredentials;
  53. this.globalMode = globalMode;
  54. }
  55. /**
  56. * If an exception is not thrown, the response needs to be closed by either calling close() directly, or closing the
  57. * body content's stream/reader.
  58. *
  59. * @throws IllegalStateException if the request could not be executed due to a connectivity problem or timeout. Because networks can
  60. * fail during an exchange, it is possible that the remote server accepted the request before the failure
  61. * @throws MessageException if there was a problem with authentication or if a error message was parsed from the response.
  62. * @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.
  63. */
  64. public WsResponse call(WsRequest request) {
  65. checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
  66. Profiler profiler = Profiler.createIfDebug(LOG).start();
  67. WsResponse response = target.wsConnector().call(request);
  68. profiler.stopDebug(format("%s %d %s", request.getMethod(), response.code(), response.requestUrl()));
  69. failIfUnauthorized(response);
  70. return response;
  71. }
  72. public String baseUrl() {
  73. return target.wsConnector().baseUrl();
  74. }
  75. WsConnector wsConnector() {
  76. return target.wsConnector();
  77. }
  78. private void failIfUnauthorized(WsResponse response) {
  79. int code = response.code();
  80. if (code == HTTP_UNAUTHORIZED) {
  81. response.close();
  82. if (hasCredentials) {
  83. // credentials are not valid
  84. throw MessageException.of(format("Not authorized. Please check the properties %s and %s.",
  85. CoreProperties.LOGIN, CoreProperties.PASSWORD));
  86. }
  87. // not authenticated - see https://jira.sonarsource.com/browse/SONAR-4048
  88. throw MessageException.of(format("Not authorized. Analyzing this project requires to be authenticated. " +
  89. "Please provide the values of the properties %s and %s.", CoreProperties.LOGIN, CoreProperties.PASSWORD));
  90. }
  91. if (code == HTTP_FORBIDDEN) {
  92. throw MessageException.of("You're not authorized to run analysis. Please contact the project administrator.");
  93. }
  94. if (code == HTTP_BAD_REQUEST) {
  95. String jsonMsg = tryParseAsJsonError(response.content());
  96. if (jsonMsg != null) {
  97. throw MessageException.of(jsonMsg);
  98. }
  99. }
  100. // if failed, throws an HttpException
  101. response.failIfNotSuccessful();
  102. }
  103. /**
  104. * Tries to form a short and relevant error message from the exception, to be displayed in the console.
  105. */
  106. public static String createErrorMessage(HttpException exception) {
  107. String json = tryParseAsJsonError(exception.content());
  108. if (json != null) {
  109. return json;
  110. }
  111. String msg = "HTTP code " + exception.code();
  112. if (isHtml(exception.content())) {
  113. return msg;
  114. }
  115. return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN);
  116. }
  117. @CheckForNull
  118. private static String tryParseAsJsonError(String responseContent) {
  119. try {
  120. JsonParser parser = new JsonParser();
  121. JsonObject obj = parser.parse(responseContent).getAsJsonObject();
  122. JsonArray errors = obj.getAsJsonArray("errors");
  123. List<String> errorMessages = new ArrayList<>();
  124. for (JsonElement e : errors) {
  125. errorMessages.add(e.getAsJsonObject().get("msg").getAsString());
  126. }
  127. return String.join(", ", errorMessages);
  128. } catch (Exception e) {
  129. return null;
  130. }
  131. }
  132. private static boolean isHtml(String responseContent) {
  133. return StringUtils.stripToEmpty(responseContent).startsWith("<!DOCTYPE html>");
  134. }
  135. }