Home > Software engineering >  Is there a better approach to call a Java method multiple times conditionally?
Is there a better approach to call a Java method multiple times conditionally?

Time:01-27

I have a method that generates an access token that is passed as an authorisation bearer for API requests:

private void generateAccessToken() {
    try {
      OAuthClientRequest request = OAuthClientRequest
              .tokenLocation(uri)
              .setGrantType(GrantType.CLIENT_CREDENTIALS)
              .buildBodyMessage();

      request.addHeader("Authorization", "Basic "   Base64.getEncoder()
                                                          .encodeToString((clientId   ":"   clientSecret).getBytes(StandardCharsets.UTF_8)));

      OAuthClient client = new OAuthClient(new URLConnectionClient());

      OAuthJSONAccessTokenResponse oAuthResponse = client
              .accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);

      accessToken = oAuthResponse.getAccessToken();
    }
    catch (OAuthSystemException | OAuthProblemException e) {
      logger.error(e::getMessage);
    }

  }

I call the method whenever required and it generates an access token:

generateAccessToken();

Now, the identity server for some reason randomly fails to generate a token on the first attempt and returns null. It's taking 2 or 3 attempts for it to do so. A workaround for this issue is to call generateAccessToken(); 3 times so that if the first call returns a null, the second one will generate it and if that is null, the third one would generate it. So, this workaround fixes the issue:

generateAccessToken();
generateAccessToken();
generateAccessToken();

Instead of forcing the call 3 times whenever an API request is sent, I applied a basic condition that would only call the subsequent methods only when the first call generates null.

generateAccessToken();

if (accessToken == null) {
  generateAccessToken();
}

if (accessToken == null) {
  generateAccessToken();

} else {
  String s = ("Access token could not be generated");

}

The condition works fine but I am thinking perhaps there is a better approach out there for the structuring of the condition. Instead of this basic if condition, is there a better, more strongly-typed, Java-best-practice way to call the generateAccessToken(); only if it initially generates a null value?

CodePudding user response:

Why don't you just use a while loop?

while (accessToken == null) {
  generateAccessToken();
}

And eventually add a condition that checks for a certain amount of attempts:

int attempts = 0;
while (accessToken == null && attempts < 3) {
  generateAccessToken();
  attempts  ;
}

With the error message:

int attempts = 0;
while (accessToken == null && attempts < 3) {
  generateAccessToken();
  attempts  ;
}
if(accessToken == null) {
  // Access token could not be generated
}
  •  Tags:  
  • java
  • Related