aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerClient.java
blob: 0fcc09bcf3d671f618ba7f17b76c2f26d562c55a (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
/*
 * 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.batch.bootstrap;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.BatchComponent;
import org.sonar.api.CoreProperties;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.batch.bootstrapper.EnvironmentInformation;

import javax.annotation.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

/**
 * Replace the deprecated org.sonar.batch.ServerMetadata
 * TODO extends Server when removing the deprecated org.sonar.batch.ServerMetadata
 *
 * @since 3.4
 */
public class ServerClient implements BatchComponent {

  private BootstrapProperties props;
  private HttpDownloader.BaseHttpDownloader downloader;

  public ServerClient(BootstrapProperties settings, EnvironmentInformation env) {
    this.props = settings;
    this.downloader = new HttpDownloader.BaseHttpDownloader(settings.properties(), env.toString());
  }

  public String getURL() {
    return StringUtils.removeEnd(StringUtils.defaultIfBlank(props.property("sonar.host.url"), "http://localhost:9000"), "/");
  }

  public void download(String pathStartingWithSlash, File toFile) {
    download(pathStartingWithSlash, toFile, null);
  }

  public void download(String pathStartingWithSlash, File toFile, @Nullable Integer readTimeoutMillis) {
    try {
      InputSupplier<InputStream> inputSupplier = doRequest(pathStartingWithSlash, readTimeoutMillis);
      Files.copy(inputSupplier, toFile);
    } catch (HttpDownloader.HttpException he) {
      throw handleHttpException(he);
    } catch (IOException e) {
      throw new IllegalStateException(String.format("Unable to download '%s' to: %s", pathStartingWithSlash, toFile), e);
    }
  }

  public String request(String pathStartingWithSlash) {
    return request(pathStartingWithSlash, true);
  }

  public String request(String pathStartingWithSlash, boolean wrapHttpException) {
    return request(pathStartingWithSlash, wrapHttpException, null);
  }

  public String request(String pathStartingWithSlash, boolean wrapHttpException, @Nullable Integer timeoutMillis) {
    InputSupplier<InputStream> inputSupplier = doRequest(pathStartingWithSlash, timeoutMillis);
    try {
      return IOUtils.toString(inputSupplier.getInput(), "UTF-8");
    } catch (HttpDownloader.HttpException e) {
      throw wrapHttpException ? handleHttpException(e) : e;
    } catch (IOException e) {
      throw new IllegalStateException(String.format("Unable to request: %s", pathStartingWithSlash), e);
    }
  }

  private InputSupplier<InputStream> doRequest(String pathStartingWithSlash, @Nullable Integer timeoutMillis) {
    Preconditions.checkArgument(pathStartingWithSlash.startsWith("/"), "Path must start with slash /");
    String path = StringEscapeUtils.escapeHtml(pathStartingWithSlash);

    URI uri = URI.create(getURL() + path);
    try {
      InputSupplier<InputStream> inputSupplier;
      if (Strings.isNullOrEmpty(getLogin())) {
        inputSupplier = downloader.newInputSupplier(uri, timeoutMillis);
      } else {
        inputSupplier = downloader.newInputSupplier(uri, getLogin(), getPassword(), timeoutMillis);
      }
      return inputSupplier;
    } catch (Exception e) {
      throw new IllegalStateException(String.format("Unable to request: %s", uri), e);
    }
  }

  private RuntimeException handleHttpException(HttpDownloader.HttpException he) {
    if (he.getResponseCode() == 401) {
      return new IllegalStateException(String.format(getMessageWhenNotAuthorized(), CoreProperties.LOGIN, CoreProperties.PASSWORD));
    }
    if (he.getResponseCode() == 403) {
      // SONAR-4397 Details are in response content
      return new IllegalStateException(he.getResponseContent());
    }
    return new IllegalStateException(String.format("Fail to execute request [code=%s, url=%s]", he.getResponseCode(), he.getUri()), he);
  }

  private String getMessageWhenNotAuthorized() {
    if (Strings.isNullOrEmpty(getLogin()) && Strings.isNullOrEmpty(getPassword())) {
      return "Not authorized. Analyzing this project requires to be authenticated. Please provide the values of the properties %s and %s.";
    }
    return "Not authorized. Please check the properties %s and %s.";
  }

  private String getLogin() {
    return props.property(CoreProperties.LOGIN);
  }

  private String getPassword() {
    return props.property(CoreProperties.PASSWORD);
  }

  public static String encodeForUrl(String url) {
    try {
      return URLEncoder.encode(url, "UTF-8");

    } catch (UnsupportedEncodingException e) {
      throw new IllegalStateException("Encoding not supported", e);
    }
  }
}