Skip to content

Commit 767fe7c

Browse files
SK-2519: extract hard coded strings to constants and update linting rules
1 parent 6c28b9a commit 767fe7c

20 files changed

+372
-117
lines changed

checkstyle.xml

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,48 @@
1616
<module name="StaticVariableName"/>
1717
<module name="ConstantName"/>
1818
<module name="TypeName"/>
19+
20+
<module name="MultipleStringLiterals">
21+
<property name="allowedDuplicates" value="1"/>
22+
<property name="ignoreOccurrenceContext" value="ANNOTATION"/>
23+
<property name="ignoreStringsRegexp" value='^""$|^"."$'/>
24+
</module>
25+
26+
<module name="StringLiteralEquality"/>
27+
28+
<module name="MagicNumber">
29+
<property name="ignoreNumbers" value="-1,0,1,2,3,64,200,201,204,299,400,401,403,404,500,1000,60000"/>
30+
<property name="ignoreFieldDeclaration" value="true"/>
31+
<property name="ignoreAnnotation" value="true"/>
32+
</module>
33+
34+
<!-- Detect common hardcoded JSON field names in .get() calls -->
35+
<module name="RegexpSinglelineJava">
36+
<property name="format" value='\.get\("(error|message|tokens|records|fields|details|grpc_code|http_status|Body|exp|skyflow_id|privateKey|clientID|keyID|tokenURI)"\)'/>
37+
<property name="message" value="Use Constants.JsonFieldNames or Constants.CredentialFields instead of hardcoded field names. Use IDE search-replace for: error, message, tokens, records, fields, details, grpc_code, http_status, Body, exp, skyflow_id, privateKey, clientID, keyID, tokenURI"/>
38+
<property name="ignoreComments" value="true"/>
39+
</module>
40+
41+
<!-- Detect common hardcoded JSON field names in .put() calls -->
42+
<module name="RegexpSinglelineJava">
43+
<property name="format" value='\.put\("(error|value|token|type|requestIndex|requestId)"\s*,'/>
44+
<property name="message" value="Use Constants.JsonFieldNames instead of hardcoded field names. Use IDE search-replace for: error, value, token, type, requestIndex, requestId"/>
45+
<property name="ignoreComments" value="true"/>
46+
</module>
47+
48+
<!-- Detect common hardcoded JSON field names in .add() and .addProperty() calls -->
49+
<module name="RegexpSinglelineJava">
50+
<property name="format" value='\.(add|addProperty)\("(errors|tokens|value|token|type|error|updatedField)"\s*,'/>
51+
<property name="message" value="Use Constants.JsonFieldNames instead of hardcoded field names. Use IDE search-replace for: errors, tokens, value, token, type, error, updatedField"/>
52+
<property name="ignoreComments" value="true"/>
53+
</module>
54+
55+
<!-- Detect hardcoded RSA algorithm -->
56+
<module name="RegexpSinglelineJava">
57+
<property name="format" value='getInstance\("RSA"\)'/>
58+
<property name="message" value="Use Constants.CryptoAlgorithm.RSA instead of hardcoded 'RSA'"/>
59+
<property name="ignoreComments" value="true"/>
60+
</module>
61+
1962
</module>
20-
</module>
63+
</module>

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@
200200
<failsOnError>false</failsOnError>
201201
<consoleOutput>true</consoleOutput>
202202

203-
<excludes>**/generated/**</excludes>
203+
<excludes>**/generated/**,**/logs/**</excludes>
204204
</configuration>
205205
<executions>
206206
<execution>

src/main/java/com/skyflow/VaultClient.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -808,9 +808,9 @@ private TokenTypeMapping buildTokenType(TokenFormat tokenFormat,
808808

809809
private FileDataDeidentifyAudioDataFormat mapAudioDataFormat(String dataFormat) throws SkyflowException {
810810
switch (dataFormat) {
811-
case "mp3":
811+
case Constants.FileFormatType.MP3:
812812
return FileDataDeidentifyAudioDataFormat.MP_3;
813-
case "wav":
813+
case Constants.FileFormatType.WAV:
814814
return FileDataDeidentifyAudioDataFormat.WAV;
815815
default:
816816
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAudioFileType.getMessage());

src/main/java/com/skyflow/errors/ErrorMessage.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.skyflow.utils.Constants;
44

5+
@SuppressWarnings("checkstyle:MultipleStringLiterals")
56
public enum ErrorMessage {
67
// Client initialization
78
VaultIdAlreadyInConfigList("%s0 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."),

src/main/java/com/skyflow/errors/SkyflowException.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public SkyflowException(int httpCode, Throwable cause, Map<String, List<String>>
5757

5858
private void setResponseBody(String responseBody, Map<String, List<String>> responseHeaders) {
5959
this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject();
60-
if (this.responseBody.get("error") != null) {
60+
if (this.responseBody.get(Constants.JsonFieldNames.ERROR) != null) {
6161
setGrpcCode();
6262
setHttpStatus();
6363
setMessage();
@@ -75,17 +75,17 @@ private void setRequestId(Map<String, List<String>> responseHeaders) {
7575
}
7676

7777
private void setMessage() {
78-
JsonElement messageElement = ((JsonObject) responseBody.get("error")).get("message");
78+
JsonElement messageElement = ((JsonObject) responseBody.get(Constants.JsonFieldNames.ERROR)).get(Constants.JsonFieldNames.MESSAGE);
7979
this.message = messageElement == null ? null : messageElement.getAsString();
8080
}
8181

8282
private void setGrpcCode() {
83-
JsonElement grpcElement = ((JsonObject) responseBody.get("error")).get("grpc_code");
83+
JsonElement grpcElement = ((JsonObject) responseBody.get(Constants.JsonFieldNames.ERROR)).get(Constants.JsonFieldNames.GRPC_CODE);
8484
this.grpcCode = grpcElement == null ? null : grpcElement.getAsInt();
8585
}
8686

8787
private void setHttpStatus() {
88-
JsonElement statusElement = ((JsonObject) responseBody.get("error")).get("http_status");
88+
JsonElement statusElement = ((JsonObject) responseBody.get(Constants.JsonFieldNames.ERROR)).get(Constants.JsonFieldNames.HTTP_STATUS);
8989
this.httpStatus = statusElement == null ? null : statusElement.getAsString();
9090
}
9191

@@ -98,7 +98,7 @@ public JsonArray getDetails() {
9898
}
9999

100100
private void setDetails(Map<String, List<String>> responseHeaders) {
101-
JsonElement detailsElement = ((JsonObject) responseBody.get("error")).get("details");
101+
JsonElement detailsElement = ((JsonObject) responseBody.get(Constants.JsonFieldNames.ERROR)).get(Constants.JsonFieldNames.DETAILS);
102102
List<String> errorFromClientHeader = responseHeaders.get(Constants.ERROR_FROM_CLIENT_HEADER_KEY);
103103
if (detailsElement != null) {
104104
this.details = detailsElement.getAsJsonArray();

src/main/java/com/skyflow/serviceaccount/util/BearerToken.java

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -92,25 +92,25 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials(
9292
JsonObject credentials, String context, ArrayList<String> roles
9393
) throws SkyflowException {
9494
try {
95-
JsonElement privateKey = credentials.get("privateKey");
95+
JsonElement privateKey = credentials.get(Constants.CredentialFields.PRIVATE_KEY);
9696
if (privateKey == null) {
9797
LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog());
9898
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage());
9999
}
100100

101-
JsonElement clientID = credentials.get("clientID");
101+
JsonElement clientID = credentials.get(Constants.CredentialFields.CLIENT_ID);
102102
if (clientID == null) {
103103
LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog());
104104
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage());
105105
}
106106

107-
JsonElement keyID = credentials.get("keyID");
107+
JsonElement keyID = credentials.get(Constants.CredentialFields.KEY_ID);
108108
if (keyID == null) {
109109
LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog());
110110
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage());
111111
}
112112

113-
JsonElement tokenURI = credentials.get("tokenURI");
113+
JsonElement tokenURI = credentials.get(Constants.CredentialFields.TOKEN_URI);
114114
if (tokenURI == null) {
115115
LogUtil.printErrorLog(ErrorLogs.TOKEN_URI_IS_REQUIRED.getLog());
116116
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingTokenUri.getMessage());
@@ -123,7 +123,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials(
123123

124124
String basePath = Utils.getBaseURL(tokenURI.getAsString());
125125
API_CLIENT_BUILDER.url(basePath);
126-
ApiClient apiClient = API_CLIENT_BUILDER.token("token").build();
126+
ApiClient apiClient = API_CLIENT_BUILDER.token(Constants.ApiToken.TOKEN).build();
127127
AuthenticationClient authenticationApi = apiClient.authentication();
128128

129129
V1GetAuthTokenRequest._FinalStage authTokenBuilder = V1GetAuthTokenRequest.builder().grantType(Constants.GRANT_TYPE).assertion(signedUserJWT);
@@ -149,11 +149,11 @@ private static String getSignedToken(
149149
final Date createdDate = new Date();
150150
final Date expirationDate = new Date(createdDate.getTime() + (3600 * 1000));
151151
return Jwts.builder()
152-
.claim("iss", clientID)
153-
.claim("key", keyID)
154-
.claim("aud", tokenURI)
155-
.claim("sub", clientID)
156-
.claim("ctx", context)
152+
.claim(Constants.JwtClaims.ISS, clientID)
153+
.claim(Constants.JwtClaims.KEY, keyID)
154+
.claim(Constants.JwtClaims.AUD, tokenURI)
155+
.claim(Constants.JwtClaims.SUB, clientID)
156+
.claim(Constants.JwtClaims.CTX, context)
157157
.expiration(expirationDate)
158158
.signWith(pvtKey, Jwts.SIG.RS256)
159159
.compact();
@@ -163,7 +163,7 @@ private static String getScopeUsingRoles(ArrayList<String> roles) {
163163
StringBuilder scope = new StringBuilder();
164164
if (roles != null) {
165165
for (String role : roles) {
166-
scope.append(" role:").append(role);
166+
scope.append(Constants.ApiToken.ROLE_PREFIX).append(role);
167167
}
168168
}
169169
return scope.toString();
@@ -173,10 +173,10 @@ public synchronized String getBearerToken() throws SkyflowException {
173173
LogUtil.printInfoLog(InfoLogs.GET_BEARER_TOKEN_TRIGGERED.getLog());
174174
V1GetAuthTokenResponse response;
175175
String accessToken = null;
176-
if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) {
176+
if (this.credentialsFile != null && Objects.equals(this.credentialsType, Constants.CredentialTypeValues.FILE)) {
177177
response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles);
178178
accessToken = response.getAccessToken().get();
179-
} else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) {
179+
} else if (this.credentialsString != null && Objects.equals(this.credentialsType, Constants.CredentialTypeValues.STRING)) {
180180
response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles);
181181
accessToken = response.getAccessToken().get();
182182
}
@@ -200,13 +200,13 @@ private void setCredentialsType(String credentialsType) {
200200
}
201201

202202
public BearerTokenBuilder setCredentials(File credentialsFile) {
203-
setCredentialsType("FILE");
203+
setCredentialsType(Constants.CredentialTypeValues.FILE);
204204
this.credentialsFile = credentialsFile;
205205
return this;
206206
}
207207

208208
public BearerTokenBuilder setCredentials(String credentialsString) {
209-
setCredentialsType("STRING");
209+
setCredentialsType(Constants.CredentialTypeValues.STRING);
210210
this.credentialsString = credentialsString;
211211
return this;
212212
}

src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.skyflow.errors.SkyflowException;
1010
import com.skyflow.logs.ErrorLogs;
1111
import com.skyflow.logs.InfoLogs;
12+
import com.skyflow.utils.Constants;
1213
import com.skyflow.utils.Utils;
1314
import com.skyflow.utils.logger.LogUtil;
1415
import io.jsonwebtoken.Jwts;
@@ -93,19 +94,19 @@ private static List<SignedDataTokenResponse> generateSignedTokensFromCredentials
9394
) throws SkyflowException {
9495
List<SignedDataTokenResponse> signedDataTokens = null;
9596
try {
96-
JsonElement privateKey = credentials.get("privateKey");
97+
JsonElement privateKey = credentials.get(Constants.CredentialFields.PRIVATE_KEY);
9798
if (privateKey == null) {
9899
LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog());
99100
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage());
100101
}
101102

102-
JsonElement clientID = credentials.get("clientID");
103+
JsonElement clientID = credentials.get(Constants.CredentialFields.CLIENT_ID);
103104
if (clientID == null) {
104105
LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog());
105106
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage());
106107
}
107108

108-
JsonElement keyID = credentials.get("keyID");
109+
JsonElement keyID = credentials.get(Constants.CredentialFields.KEY_ID);
109110
if (keyID == null) {
110111
LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog());
111112
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage());
@@ -136,12 +137,12 @@ private static List<SignedDataTokenResponse> getSignedToken(
136137
List<SignedDataTokenResponse> list = new ArrayList<>();
137138
for (String dataToken : dataTokens) {
138139
String eachSignedDataToken = Jwts.builder()
139-
.claim("iss", "sdk")
140-
.claim("iat", (createdDate.getTime() / 1000))
141-
.claim("key", keyID)
142-
.claim("sub", clientID)
143-
.claim("ctx", context)
144-
.claim("tok", dataToken)
140+
.claim(Constants.JwtClaims.ISS, Constants.JwtClaims.SDK)
141+
.claim(Constants.JwtClaims.IAT, (createdDate.getTime() / 1000))
142+
.claim(Constants.JwtClaims.KEY, keyID)
143+
.claim(Constants.JwtClaims.SUB, clientID)
144+
.claim(Constants.JwtClaims.CTX, context)
145+
.claim(Constants.JwtClaims.TOK, dataToken)
145146
.expiration(expirationDate)
146147
.signWith(pvtKey, Jwts.SIG.RS256)
147148
.compact();
@@ -154,9 +155,9 @@ private static List<SignedDataTokenResponse> getSignedToken(
154155
public synchronized List<SignedDataTokenResponse> getSignedDataTokens() throws SkyflowException {
155156
LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKENS_TRIGGERED.getLog());
156157
List<SignedDataTokenResponse> signedToken = new ArrayList<>();
157-
if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) {
158+
if (this.credentialsFile != null && Objects.equals(this.credentialsType, Constants.CredentialTypeValues.FILE)) {
158159
signedToken = generateSignedTokenFromCredentialsFile(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx);
159-
} else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) {
160+
} else if (this.credentialsString != null && Objects.equals(this.credentialsType, Constants.CredentialTypeValues.STRING)) {
160161
signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, this.timeToLive, this.ctx);
161162
}
162163
LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKEN_SUCCESS.getLog());
@@ -179,13 +180,13 @@ private void setCredentialsType(String credentialsType) {
179180
}
180181

181182
public SignedDataTokensBuilder setCredentials(File credentialsFile) {
182-
setCredentialsType("FILE");
183+
setCredentialsType(Constants.CredentialTypeValues.FILE);
183184
this.credentialsFile = credentialsFile;
184185
return this;
185186
}
186187

187188
public SignedDataTokensBuilder setCredentials(String credentialsString) {
188-
setCredentialsType("STRING");
189+
setCredentialsType(Constants.CredentialTypeValues.STRING);
189190
this.credentialsString = credentialsString;
190191
return this;
191192
}

src/main/java/com/skyflow/serviceaccount/util/Token.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import com.skyflow.errors.SkyflowException;
99
import com.skyflow.logs.ErrorLogs;
1010
import com.skyflow.logs.InfoLogs;
11+
import com.skyflow.utils.Constants;
1112
import com.skyflow.utils.logger.LogUtil;
1213
import org.apache.commons.codec.binary.Base64;
1314

@@ -25,7 +26,7 @@ public static boolean isExpired(String token) {
2526
}
2627

2728
currentTime = new Date().getTime() / 1000;
28-
expiryTime = decoded(token).get("exp").getAsLong();
29+
expiryTime = decoded(token).get(Constants.JsonFieldNames.EXP).getAsLong();
2930

3031
} catch (JsonSyntaxException | SkyflowException e) {
3132
LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog());

0 commit comments

Comments
 (0)