|
27 | 27 | import com.google.gcloud.spi.ServiceRpcFactory; |
28 | 28 |
|
29 | 29 | import java.io.BufferedReader; |
| 30 | +import java.io.File; |
| 31 | +import java.io.FileReader; |
30 | 32 | import java.io.IOException; |
| 33 | +import java.io.InputStream; |
31 | 34 | import java.io.InputStreamReader; |
32 | 35 | import java.io.Serializable; |
33 | 36 | import java.lang.reflect.Method; |
| 37 | +import java.net.HttpURLConnection; |
34 | 38 | import java.net.URL; |
35 | | -import java.net.URLConnection; |
36 | 39 | import java.util.Objects; |
37 | 40 | import java.util.Set; |
| 41 | +import java.util.regex.Matcher; |
| 42 | +import java.util.regex.Pattern; |
38 | 43 |
|
39 | 44 | public abstract class ServiceOptions<R, O extends ServiceOptions<R, O>> implements Serializable { |
40 | 45 |
|
@@ -168,16 +173,36 @@ protected static String appEngineAppId() { |
168 | 173 | protected static String googleCloudProjectId() { |
169 | 174 | try { |
170 | 175 | URL url = new URL("http://metadata/computeMetadata/v1/project/project-id"); |
171 | | - URLConnection connection = url.openConnection(); |
| 176 | + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
172 | 177 | connection.setRequestProperty("X-Google-Metadata-Request", "True"); |
173 | | - try (BufferedReader reader = |
174 | | - new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8))) { |
175 | | - return reader.readLine(); |
| 178 | + InputStream input = connection.getInputStream(); |
| 179 | + if (connection.getResponseCode() == 200) { |
| 180 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) { |
| 181 | + return reader.readLine(); |
| 182 | + } |
176 | 183 | } |
177 | 184 | } catch (IOException ignore) { |
178 | | - // return null if can't determine |
179 | | - return null; |
| 185 | + // ignore |
| 186 | + } |
| 187 | + String configDir = System.getenv("CLOUDSDK_CONFIG"); |
| 188 | + if (configDir == null) { |
| 189 | + configDir = new File(System.getProperty("user.home"), "/.config/gcloud/").getPath(); |
| 190 | + } |
| 191 | + try (BufferedReader reader = |
| 192 | + new BufferedReader(new FileReader(new File(configDir, "properties")))) { |
| 193 | + String line; |
| 194 | + Pattern pattern = Pattern.compile("^\\s*project\\s*=\\s*(.*?)\\s*$"); |
| 195 | + while((line = reader.readLine()) != null) { |
| 196 | + Matcher matcher = pattern.matcher(line); |
| 197 | + if (matcher.matches()) { |
| 198 | + return matcher.group(1); |
| 199 | + } |
| 200 | + } |
| 201 | + } catch (IOException ex) { |
| 202 | + // ignore |
180 | 203 | } |
| 204 | + // return null if can't determine |
| 205 | + return null; |
181 | 206 | } |
182 | 207 |
|
183 | 208 | protected static String getAppEngineProjectId() { |
|
0 commit comments