Skip to content

Commit 111ea91

Browse files
authored
Merge pull request #17 from IBM/new-thread-iam-token
Make IAM API call on separate thread
2 parents 459626e + 4478639 commit 111ea91

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

src/main/java/com/ibm/cloud/sdk/core/service/security/IamTokenManager.java

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@
1919
import com.ibm.cloud.sdk.core.http.ResponseConverter;
2020
import com.ibm.cloud.sdk.core.util.CredentialUtils;
2121
import com.ibm.cloud.sdk.core.util.ResponseConverterUtils;
22-
2322
import okhttp3.Call;
2423
import okhttp3.FormBody;
2524
import okhttp3.Request;
2625

2726
import java.io.IOException;
27+
import java.util.logging.Logger;
2828

2929
/**
3030
* Retrieves, stores, and refreshes IAM tokens.
@@ -35,6 +35,8 @@ public class IamTokenManager {
3535
private String url;
3636
private IamToken tokenData;
3737

38+
private static final Logger LOG = Logger.getLogger(IamTokenManager.class.getName());
39+
private static final String ERROR_MESSAGE = "Error getting IAM token from API";
3840
private static final String DEFAULT_AUTHORIZATION = "Basic Yng6Yng=";
3941
private static final String DEFAULT_IAM_URL = "https://iam.bluemix.net/identity/token";
4042
private static final String GRANT_TYPE = "grant_type";
@@ -181,14 +183,32 @@ private boolean isRefreshTokenExpired() {
181183
* @return object containing requested IAM token information
182184
*/
183185
private IamToken callIamApi(Request request) {
184-
Call call = HttpClientSingleton.getInstance().createHttpClient().newCall(request);
185-
ResponseConverter<IamToken> converter = ResponseConverterUtils.getObject(IamToken.class);
186+
final IamToken[] returnToken = new IamToken[1];
187+
188+
Thread iamApiCall = new Thread(new Runnable() {
189+
@Override
190+
public void run() {
191+
Call call = HttpClientSingleton.getInstance().createHttpClient().newCall(request);
192+
ResponseConverter<IamToken> converter = ResponseConverterUtils.getObject(IamToken.class);
193+
194+
try {
195+
okhttp3.Response response = call.execute();
196+
returnToken[0] = converter.convert(response);
197+
} catch (IOException e) {
198+
LOG.severe(ERROR_MESSAGE);
199+
e.printStackTrace();
200+
throw new RuntimeException(e);
201+
}
202+
}
203+
});
186204

205+
iamApiCall.start();
187206
try {
188-
okhttp3.Response response = call.execute();
189-
return converter.convert(response);
190-
} catch (IOException e) {
191-
throw new RuntimeException(e);
207+
iamApiCall.join();
208+
} catch (InterruptedException e) {
209+
LOG.severe(ERROR_MESSAGE);
210+
e.printStackTrace();
192211
}
212+
return returnToken[0];
193213
}
194214
}

0 commit comments

Comments
 (0)