1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package org.sonar.mojo.bootstrap;
25
26 import org.apache.commons.io.IOUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.maven.plugin.MojoExecutionException;
29 import org.apache.maven.plugin.logging.Log;
30
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.Reader;
35 import java.net.HttpURLConnection;
36 import java.net.URL;
37
38 public class ServerMetadata {
39
40 public static final int CONNECT_TIMEOUT_MILLISECONDS = 30000;
41 public static final int READ_TIMEOUT_MILLISECONDS = 60000;
42 public static final String MAVEN_PATH = "/deploy/maven";
43
44 private String url;
45
46 public ServerMetadata(String url) {
47 this.url = StringUtils.chomp(url, "/");
48 }
49
50 public String getVersion() throws IOException {
51 return remoteContent("/api/server/version");
52 }
53
54 public String getKey() throws IOException {
55 return remoteContent("/api/server/key");
56 }
57
58 public String getMavenRepositoryUrl() {
59 return getUrl() + MAVEN_PATH;
60 }
61
62 public String getUrl() {
63 return url;
64 }
65
66 public void logSettings(Log log) throws MojoExecutionException {
67 try {
68 log.info("Sonar host: " + getUrl());
69 log.info("Sonar version: " + getVersion());
70
71 } catch (IOException e) {
72 throw new MojoExecutionException("Sonar server can not be reached at " + getUrl() + ". Please check the parameter 'sonar.host.url'.");
73 }
74 }
75
76 protected String remoteContent(String path) throws IOException {
77 String fullUrl = url + path;
78 HttpURLConnection conn = getConnection(fullUrl + path, "GET");
79 Reader reader = new InputStreamReader((InputStream) conn.getContent());
80 try {
81 int statusCode = conn.getResponseCode();
82 if (statusCode != HttpURLConnection.HTTP_OK) {
83 throw new IOException("Status returned by url : '" + fullUrl + "' is invalid : " + statusCode);
84 }
85 return IOUtils.toString(reader);
86
87 } finally {
88 IOUtils.closeQuietly(reader);
89 conn.disconnect();
90 }
91 }
92
93 protected HttpURLConnection getConnection(String url, String method) throws IOException {
94 URL page = new URL(url);
95 HttpURLConnection conn = (HttpURLConnection) page.openConnection();
96 conn.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS);
97 conn.setReadTimeout(READ_TIMEOUT_MILLISECONDS);
98 conn.setRequestMethod(method);
99 conn.connect();
100 return conn;
101 }
102
103 }