Skip to content

Commit bbb974f

Browse files
committed
review feedback removed try-catch-blocks
1 parent 7e60121 commit bbb974f

File tree

10 files changed

+88
-56
lines changed

10 files changed

+88
-56
lines changed

core/src/main/java/cloud/stackit/sdk/core/KeyFlowAuthenticator.java

Lines changed: 28 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cloud.stackit.sdk.core;
22

33
import cloud.stackit.sdk.core.config.CoreConfiguration;
4+
import cloud.stackit.sdk.core.exception.ApiException;
45
import cloud.stackit.sdk.core.model.ServiceAccountKey;
56
import com.auth0.jwt.JWT;
67
import com.auth0.jwt.algorithms.Algorithm;
@@ -63,10 +64,11 @@ public String getAccessToken() {
6364
* Creates the initial service account and refreshes expired access token.
6465
* @param cfg Configuration to set a custom token endpoint and the token expiration leeway.
6566
* @param saKey Service Account Key, which should be used for the authentication
66-
* @throws InvalidKeySpecException Throws, when the private key in the service account can not be parsed
67-
* @throws IOException Throws, when on unexpected responses from the key flow
67+
* @throws InvalidKeySpecException thrown when the private key in the service account can not be parsed
68+
* @throws IOException thrown on unexpected responses from the key flow
69+
* @throws ApiException thrown on unexpected responses from the key flow
6870
*/
69-
public KeyFlowAuthenticator(CoreConfiguration cfg, ServiceAccountKey saKey) throws InvalidKeySpecException, IOException {
71+
public KeyFlowAuthenticator(CoreConfiguration cfg, ServiceAccountKey saKey) throws InvalidKeySpecException, IOException, ApiException {
7072
this.saKey = saKey;
7173
this.gson = new Gson();
7274
this.httpClient = new OkHttpClient.Builder()
@@ -86,50 +88,50 @@ public KeyFlowAuthenticator(CoreConfiguration cfg, ServiceAccountKey saKey) thro
8688
createAccessToken();
8789
}
8890

89-
public synchronized String getAccessToken() throws IOException {
91+
92+
/**
93+
* Returns access token. If the token is expired it creates a new token.
94+
* @throws IOException request for new access token failed
95+
* @throws ApiException response for new access token with bad status code
96+
*/
97+
public synchronized String getAccessToken() throws IOException, ApiException {
9098
if (token == null || token.isExpired()) {
9199
createAccessTokenWithRefreshToken();
92100
}
93101
return token.getAccessToken();
94102
}
95103

96104
/**
97-
* Creates the inital accessToken and stores it in `this.token`
105+
* Creates the initial accessToken and stores it in `this.token`
98106
* @throws InvalidKeySpecException can not parse private key
99107
* @throws IOException request for access token failed
108+
* @throws ApiException response for new access token with bad status code
100109
* @throws JsonSyntaxException parsing of the created access token failed
101110
*/
102-
private void createAccessToken() throws InvalidKeySpecException, IOException, JsonSyntaxException {
111+
private void createAccessToken() throws InvalidKeySpecException, IOException, JsonSyntaxException, ApiException {
103112
String grant = "urn:ietf:params:oauth:grant-type:jwt-bearer";
104113
String assertion;
105114
try {
106115
assertion = generateSelfSignedJWT();
107116
} catch (NoSuchAlgorithmException e) {
108117
throw new RuntimeException("could not find required algorithm for jwt signing. This should not happen and should be reported on https://github.com/stackitcloud/stackit-sdk-java/issues", e);
109118
}
110-
try(Response response = requestToken(grant, assertion).execute()) {
111-
parseTokenResponse(response);
112-
} catch (IOException | ApiException e) {
113-
throw new IOException("request for access token failed", e);
114-
} catch (JsonSyntaxException e) {
115-
throw new JsonSyntaxException("parsing access token failed", e);
119+
Response response = requestToken(grant, assertion).execute();
120+
parseTokenResponse(response);
121+
response.close();
116122
}
117-
}
118123

119124
/**
120125
* Creates a new access token with the existing refresh token
121126
* @throws IOException request for new access token failed
127+
* @throws ApiException response for new access token with bad status code
122128
* @throws JsonSyntaxException can not parse new access token
123129
*/
124-
private synchronized void createAccessTokenWithRefreshToken() throws IOException, JsonSyntaxException {
130+
private synchronized void createAccessTokenWithRefreshToken() throws IOException, JsonSyntaxException, ApiException {
125131
String refreshToken = token.refreshToken;
126-
try (Response response = requestToken(REFRESH_TOKEN, refreshToken).execute()) {
127-
parseTokenResponse(response);
128-
} catch (IOException | ApiException e) {
129-
throw new IOException("request for new access token failed", e);
130-
} catch (JsonSyntaxException e) {
131-
throw new JsonSyntaxException("parsing refreshed access token failed", e);
132-
}
132+
Response response = requestToken(REFRESH_TOKEN, refreshToken).execute();
133+
parseTokenResponse(response);
134+
response.close();
133135
}
134136

135137
private synchronized void parseTokenResponse(Response response) throws ApiException, JsonSyntaxException {
@@ -145,13 +147,9 @@ private synchronized void parseTokenResponse(Response response) throws ApiExcept
145147
throw new JsonSyntaxException("body from token creation is null");
146148
}
147149

148-
try {
149-
token = gson.fromJson(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8), KeyFlowTokenResponse.class);
150-
token.expiresIn = JWT.decode(token.accessToken).getExpiresAt().toInstant().minusSeconds(tokenLeewayInSeconds).getEpochSecond();
151-
response.body().close();
152-
} catch (JsonSyntaxException e) {
153-
throw new JsonSyntaxException("could not parse response of created token", e);
154-
}
150+
token = gson.fromJson(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8), KeyFlowTokenResponse.class);
151+
token.expiresIn = JWT.decode(token.accessToken).getExpiresAt().toInstant().minusSeconds(tokenLeewayInSeconds).getEpochSecond();
152+
response.body().close();
155153
}
156154

157155
private Call requestToken(String grant, String assertionValue) throws IOException {
@@ -171,11 +169,8 @@ private Call requestToken(String grant, String assertionValue) throws IOExceptio
171169

172170
private String generateSelfSignedJWT() throws InvalidKeySpecException, NoSuchAlgorithmException {
173171
RSAPrivateKey prvKey;
174-
try {
175-
prvKey = saKey.getCredentials().getPrivateKeyParsed();
176-
} catch (InvalidKeySpecException e) {
177-
throw new InvalidKeySpecException("could not parse private key", e);
178-
}
172+
173+
prvKey = saKey.getCredentials().getPrivateKeyParsed();
179174
Algorithm algorithm = Algorithm.RSA512(prvKey);
180175

181176
Map<String, Object> jwtHeader = new HashMap<>();

core/src/main/java/cloud/stackit/sdk/core/KeyFlowInterceptor.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package cloud.stackit.sdk.core;
22

3+
import cloud.stackit.sdk.core.exception.ApiException;
34
import okhttp3.Interceptor;
45
import okhttp3.Request;
56
import okhttp3.Response;
@@ -18,7 +19,14 @@ public KeyFlowInterceptor(KeyFlowAuthenticator authenticator) {
1819
@Override
1920
public Response intercept(Chain chain) throws IOException {
2021
Request originalRequest = chain.request();
21-
String accessToken = authenticator.getAccessToken();
22+
String accessToken;
23+
try {
24+
accessToken = authenticator.getAccessToken();
25+
} catch (ApiException e) {
26+
// try-catch required, because ApiException can not be thrown in the implementation
27+
// of Interceptor.intercept(Chain chain)
28+
throw new RuntimeException(e);
29+
}
2230

2331
Request authenticatedRequest = originalRequest.newBuilder()
2432
.header("Authorization", "Bearer " + accessToken)

core/src/main/java/cloud/stackit/sdk/core/auth/SetupAuth.java

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package cloud.stackit.sdk.core.auth;
22

3+
import cloud.stackit.sdk.core.exception.ApiException;
34
import cloud.stackit.sdk.core.KeyFlowAuthenticator;
45
import cloud.stackit.sdk.core.config.CoreConfiguration;
56
import cloud.stackit.sdk.core.config.EnvironmentVariables;
67
import cloud.stackit.sdk.core.KeyFlowInterceptor;
8+
import cloud.stackit.sdk.core.exception.CredentialsInFileNotFoundException;
9+
import cloud.stackit.sdk.core.exception.PrivateKeyNotFoundException;
710
import cloud.stackit.sdk.core.model.ServiceAccountKey;
811
import com.google.gson.Gson;
912
import com.google.gson.reflect.TypeToken;
@@ -32,22 +35,24 @@ public class SetupAuth {
3235
/**
3336
* Set up the KeyFlow Authentication and can be integrated in an OkHttp client, by adding `SetupAuth().getAuthHandler()` as interceptor.
3437
* This relies on the configuration methods via ENVs or the credentials file in `$HOME/.stackit/credentials.json`
35-
* @throws IOException when no file can be found
38+
* @throws IOException when a file can be found
3639
* @throws CredentialNotFoundException when no configuration is set or can be found
3740
* @throws InvalidKeySpecException when the private key can not be parsed
41+
* @throws ApiException when access token creation failed
3842
*/
39-
public SetupAuth() throws IOException, InvalidKeySpecException, CredentialNotFoundException {
43+
public SetupAuth() throws IOException, InvalidKeySpecException, CredentialNotFoundException, ApiException {
4044
this(new CoreConfiguration.Builder().build());
4145
}
4246

4347
/**
4448
* Set up the KeyFlow Authentication and can be integrated in an OkHttp client, by adding `SetupAuth().getAuthHandler()` as interceptor.
4549
* @param cfg Configuration which describes, which service account and token endpoint should be used
46-
* @throws IOException when no file can be found
47-
* @throws CredentialNotFoundException when no configuration is set or can be found
50+
* @throws IOException when a file can be found
51+
* @throws CredentialsInFileNotFoundException when no credentials are set or can be found
4852
* @throws InvalidKeySpecException when the private key can not be parsed
53+
* @throws ApiException when access token creation failed
4954
*/
50-
public SetupAuth(CoreConfiguration cfg) throws IOException, CredentialNotFoundException, InvalidKeySpecException {
55+
public SetupAuth(CoreConfiguration cfg) throws IOException, CredentialsInFileNotFoundException, InvalidKeySpecException, ApiException {
5156
if (cfg == null) {
5257
cfg = new CoreConfiguration.Builder().build();
5358
}
@@ -90,10 +95,10 @@ public Interceptor getAuthHandler() {
9095
* </ol>
9196
* @param cfg
9297
* @return ServiceAccountKey
93-
* @throws CredentialNotFoundException throws error when no service account key or private key can be found
94-
* @throws IOException throws an error if a file can not be found
98+
* @throws CredentialsInFileNotFoundException thrown when no service account key or private key can be found
99+
* @throws IOException thrown when a file can not be found
95100
*/
96-
private ServiceAccountKey setupKeyFlow(CoreConfiguration cfg) throws CredentialNotFoundException, IOException {
101+
private ServiceAccountKey setupKeyFlow(CoreConfiguration cfg) throws CredentialsInFileNotFoundException, IOException {
97102
// Explicit config in code
98103
if (cfg.getServiceAccountKey() != null && !cfg.getServiceAccountKey().trim().isEmpty()) {
99104
ServiceAccountKey saKey = ServiceAccountKey.loadFromJson(cfg.getServiceAccountKey());
@@ -135,13 +140,13 @@ private ServiceAccountKey setupKeyFlow(CoreConfiguration cfg) throws CredentialN
135140
}
136141
}
137142

138-
private void loadPrivateKey(CoreConfiguration cfg, ServiceAccountKey saKey) throws CredentialNotFoundException {
143+
private void loadPrivateKey(CoreConfiguration cfg, ServiceAccountKey saKey) throws PrivateKeyNotFoundException {
139144
if (!saKey.getCredentials().isPrivateKeySet()) {
140145
try {
141146
String privateKey = getPrivateKey(cfg);
142147
saKey.getCredentials().setPrivateKey(privateKey);
143148
} catch (Exception e) {
144-
throw new CredentialNotFoundException("could not find private key\n" + e.getMessage());
149+
throw new PrivateKeyNotFoundException("could not find private key", e);
145150
}
146151
}
147152
}
@@ -175,10 +180,10 @@ private void loadPrivateKey(CoreConfiguration cfg, ServiceAccountKey saKey) thro
175180
* </ol>
176181
* @param cfg
177182
* @return found private key
178-
* @throws CredentialNotFoundException throws if no private key could be found
183+
* @throws CredentialsInFileNotFoundException throws if no private key could be found
179184
* @throws IOException throws if the provided path can not be found or the file within the pathKey can not be found
180185
*/
181-
private String getPrivateKey(CoreConfiguration cfg) throws CredentialNotFoundException, IOException {
186+
private String getPrivateKey(CoreConfiguration cfg) throws CredentialsInFileNotFoundException, IOException {
182187
// Explicit code config
183188
// Set private key
184189
if (cfg.getPrivateKey() != null && !cfg.getPrivateKey().trim().isEmpty()) {
@@ -215,10 +220,10 @@ private String getPrivateKey(CoreConfiguration cfg) throws CredentialNotFoundExc
215220
* @param valueKey key which contains the secret as value
216221
* @param pathKey key which contains a path to a file
217222
* @return Either the value of `valueKey` or the content of the file in `pathKey`
218-
* @throws CredentialNotFoundException throws if no value was found in the credentials file
223+
* @throws CredentialsInFileNotFoundException throws if no value was found in the credentials file
219224
* @throws IOException throws if the provided path can not be found or the file within the pathKey can not be found
220225
*/
221-
private String readValueFromCredentialsFile(String path, String valueKey, String pathKey) throws IOException, CredentialNotFoundException {
226+
private String readValueFromCredentialsFile(String path, String valueKey, String pathKey) throws IOException, CredentialsInFileNotFoundException {
222227
// Read credentials file
223228
String fileContent = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
224229
Type credentialsFileType = new TypeToken<Map<String, Object>>(){}.getType();
@@ -241,6 +246,6 @@ private String readValueFromCredentialsFile(String path, String valueKey, String
241246
if (keyPath != null && !keyPath.trim().isEmpty()) {
242247
return new String(Files.readAllBytes(Paths.get(keyPath)));
243248
}
244-
throw new CredentialNotFoundException("could not find " + valueKey + " or " + pathKey + " in " + path);
249+
throw new CredentialsInFileNotFoundException("could not find " + valueKey + " or " + pathKey + " in " + path);
245250
}
246251
}

core/src/main/java/cloud/stackit/sdk/core/ApiException.java renamed to core/src/main/java/cloud/stackit/sdk/core/exception/ApiException.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cloud.stackit.sdk.core;
1+
package cloud.stackit.sdk.core.exception;
22

33

44
import java.util.List;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cloud.stackit.sdk.core.exception;
2+
3+
public class CredentialsInFileNotFoundException extends RuntimeException {
4+
5+
public CredentialsInFileNotFoundException(String msg) {
6+
super(msg);
7+
}
8+
9+
public CredentialsInFileNotFoundException(String msg, Throwable cause) {
10+
super(msg, cause);
11+
}
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cloud.stackit.sdk.core.exception;
2+
3+
public class PrivateKeyNotFoundException extends RuntimeException {
4+
5+
public PrivateKeyNotFoundException(String msg) {
6+
super(msg);
7+
}
8+
9+
public PrivateKeyNotFoundException(String msg, Throwable cause) {
10+
super(msg, cause);
11+
}
12+
}

core/src/main/java/cloud/stackit/sdk/core/model/ServiceAccountKey.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,10 @@ public RSAPublicKey getPublicKeyParsed() throws NoSuchAlgorithmException, Invali
7878
byte[] publicBytes = Base64.getDecoder().decode(trimmedKey);
7979
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
8080
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
81-
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
82-
return pubKey;
81+
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
8382
}
8483

85-
public static ServiceAccountKey loadFromJson(String json) throws com.google.gson.JsonSyntaxException {
84+
public static ServiceAccountKey loadFromJson(String json) throws JsonSyntaxException {
8685
ServiceAccountKey saKey = new Gson().fromJson(json, ServiceAccountKey.class);
8786
if (!saKey.isCredentialsSet()) {
8887
throw new JsonSyntaxException("required field `credentials` in service account key is missing.");

services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ public ApiClient(OkHttpClient client) {
118118
authentications = Collections.unmodifiableMap(authentications);
119119
}
120120

121-
public ApiClient(CoreConfiguration config) throws IOException, InvalidKeySpecException, CredentialNotFoundException {
121+
public ApiClient(CoreConfiguration config) throws IOException, InvalidKeySpecException, cloud.stackit.sdk.core.exception.ApiException {
122122
init();
123123

124124
if (config.getCustomEndpoint() != null && !config.getCustomEndpoint().trim().isEmpty()) {

services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/api/DefaultApi.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ public DefaultApi(ApiClient apiClient) {
5959
this.localVarApiClient = apiClient;
6060
}
6161

62-
public DefaultApi(CoreConfiguration config) throws IOException, InvalidKeySpecException, CredentialNotFoundException {
62+
// TODO: remove in follow up story the service specific ApiException and use instead the ApiException of core
63+
public DefaultApi(CoreConfiguration config) throws IOException, InvalidKeySpecException, cloud.stackit.sdk.core.exception.ApiException {
6364
if (config.getCustomEndpoint() != null && !config.getCustomEndpoint().trim().isEmpty()) {
6465
localCustomBaseUrl = config.getCustomEndpoint();
6566
}

services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import java.security.spec.InvalidKeySpecException;
1010

1111
public class main {
12-
public static void main(String[] args) {
12+
public static void main(String[] args) throws IOException, InvalidKeySpecException, ApiException, cloud.stackit.sdk.core.exception.ApiException {
1313
String SERVICE_ACCOUNT_KEY_PATH = "/path/to/your/sa/key.json";
1414
String SERIVCE_ACCOUNT_MAIL = "name-1234@sa.stackit.cloud";
1515

0 commit comments

Comments
 (0)