Hi Dave
This is my code:-
Code:
public class APIService {
private String apiUrl;
private final Logger LOGGER = LoggerFactory.getLogger(APIService.class);
private static final String API_TOKEN_ENDPOINT = "/oauth/token";
private static final String RESOURCE_ENDPOINT = "/photo";
private OAuth2RestTemplate restTemplate;
private OAuth2AccessToken userAccessToken;
/**
* Authenticates the user against the API and receives an access token back.
* @param uid
* @param pwd
*/
public void authenticateUser(String uid, String pwd){
ResourceOwnerPasswordResourceDetails resource = getResourceDetails(uid, pwd);
restTemplate = new OAuth2RestTemplate(resource);
userAccessToken = restTemplate.getAccessToken();
LOGGER.debug("Access Token value ->"+userAccessToken.getValue());
LOGGER.debug("Token type ->"+userAccessToken.getTokenType());
}
public String getPhotoDetails(String id){
return restTemplate.getForObject(apiUrl + RESOURCE_ENDPOINT + "/" + id, String.class);
}
private ResourceOwnerPasswordResourceDetails getResourceDetails(String uid, String pwd){
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(apiUrl + API_TOKEN_ENDPOINT);
resource.setClientId("api-client");
resource.setUsername(uid);
resource.setPassword(pwd);
resource.setScope(Arrays.asList("trust"));
return resource;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
}
In authenticateUser() I create and initialise the restTemplate. This works just fine and retrieves the access token. In a subsequent request getPhotoDetails() attempts to get a resource from the web service using the same restTemplate. But for some reason the restTemplate is null and so is userAccessToken. How could that be? These are member variables of the APIService instance. I notice the other member variable apiUrl is just fine.