mercredi 19 juin 2019

How to implement a client that has to login in every 30 min?

I am writing an application which uses the JiraRestClient by atlassian. I cannot create this client on every Jira interaction so I thought of caching this client.

This client performs login in every 35 minutes so I thought of caching it for 30 min and then perform login again.

For that purpose I need a single instance of this client so that all the threads for the Jira interactions can use it. I created a provider class which will keep the time track and will perform the login, if the creation time of the instance is over 30 min, insuring that the instance is always logged in.

public class JiraRestClientProvider {
private static JiraRestClient jiraRestClient;
private static final long EXPIRATION_TIME = 1800L;
private static long creationTime = Instant.now().getEpochSecond();

public static synchronized JiraRestClient getJiraRestClient() {
    if (jiraRestClient == null || Instant.now().getEpochSecond() > creationTime + EXPIRATION_TIME) {
        return createJiraRestClient();
    }
    return jiraRestClient;
}

where createJiraRestClient is a private method that reads the credentials, updates the creation time, and updates the private static variable jiraRestClient.

Another class uses this JiraRestClientProvider class to perform the Jira actions like creating issues or commenting on a issue, etc as follows:

JiraRestClientProvider.getJiraRestClient().
getIssueClient().createIssue(issueInput).claim().getKey();

or

JiraRestClientProvider.getJiraRestClient().getIssueClient()
            .getIssue(issueKey).claim().getCommentsUri().toString();

Now, while writing unit test for the class that's using this I can not mock the static method getJiraRestClient and therefore unable to write unit tests. (Also, I cannot use PowerMock).

My question is, is there a way that I can write my provider class such that I will only have single and fresh instance of JiraRestClient for all threads and I can also unit test it?

Aucun commentaire:

Enregistrer un commentaire