1 package org.codehaus.mojo.sonar;
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 import org.apache.maven.plugin.MojoExecutionException;
28 import org.apache.maven.plugin.logging.Log;
29 import org.codehaus.plexus.util.IOUtil;
30
31 import java.io.*;
32 import java.net.HttpURLConnection;
33 import java.net.URL;
34
35 public class ServerMetadata
36 {
37
38 public static final int CONNECT_TIMEOUT_MILLISECONDS = 30000;
39 public static final int READ_TIMEOUT_MILLISECONDS = 60000;
40
41 private String url;
42 private String version;
43
44 public ServerMetadata( String url )
45 {
46 if ( url.endsWith( "/" ) )
47 {
48 this.url = url.substring( 0, url.length() - 1 );
49 }
50 else
51 {
52 this.url = url;
53 }
54 }
55
56 public String getVersion() throws IOException
57 {
58 if ( version == null )
59 {
60 version = remoteContent( "/api/server/version" );
61 }
62 return version;
63 }
64
65 public String getUrl()
66 {
67 return url;
68 }
69
70 public void logSettings( Log log ) throws MojoExecutionException
71 {
72 try
73 {
74 log.info( "Sonar version: " + getVersion() );
75
76 }
77 catch ( IOException e )
78 {
79 throw new MojoExecutionException( "Sonar server can not be reached at " + url
80 + ". Please check the parameter 'sonar.host.url'." );
81 }
82 }
83
84 protected String remoteContent( String path ) throws IOException
85 {
86 String fullUrl = url + path;
87 HttpURLConnection conn = getConnection( fullUrl, "GET" );
88 InputStream input = (InputStream) conn.getContent();
89 try
90 {
91 int statusCode = conn.getResponseCode();
92 if ( statusCode != HttpURLConnection.HTTP_OK )
93 {
94 throw new IOException( "Status returned by url : '" + fullUrl + "' is invalid : " + statusCode );
95 }
96 return IOUtil.toString( input );
97
98 }
99 finally
100 {
101 IOUtil.close( input );
102 conn.disconnect();
103 }
104 }
105
106 static HttpURLConnection getConnection( String url, String method ) throws IOException
107 {
108 URL page = new URL( url );
109 HttpURLConnection conn = (HttpURLConnection) page.openConnection();
110 conn.setConnectTimeout( CONNECT_TIMEOUT_MILLISECONDS );
111 conn.setReadTimeout( READ_TIMEOUT_MILLISECONDS );
112 conn.setRequestMethod( method );
113 conn.connect();
114 return conn;
115 }
116
117 protected boolean supportsMaven3() throws IOException
118 {
119 return !isVersionPriorTo2Dot4( getVersion() );
120 }
121
122 protected static boolean isVersionPriorTo2Dot4( String version )
123 {
124 return version.startsWith( "1." ) || version.startsWith( "2.0." ) || version.equals( "2.1" )
125 || version.equals( "2.2" ) || version.startsWith( "2.1." ) || version.startsWith( "2.3." )
126 || version.equals( "2.3" ) ;
127 }
128 }