Singleton类,用于全局访问App Engine中的GoogleCredentials

时间:2015-06-02 07:34:51

标签: java google-app-engine

在我的App Engine项目中,我希望在整个生命周期内为应用程序实例提供全局可用的云存储有效访问令牌。这就是我想要做的事情:

public class GoogleCredentialsHolder
{
    private static GoogleCredentialsHolder instance = null;
    private GoogleCredential credentials;

    public static synchronized GoogleCredentialsHolder getInstance() throws GeneralSecurityException, IOException
    {
        if(instance == null)
            instance = new GoogleCredentialsHolder();
        return instance;
    }

    private GoogleCredentialsHolder() throws GeneralSecurityException, IOException
    {
        credentials = getGoogleCredential();
        credentials.refreshToken();
    }

    private GoogleCredential getGoogleCredential() throws GeneralSecurityException, IOException
    {
        JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(Constants.SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(Constants.CLOUD_STORAGE_KEY))
            .setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/devstorage.read_write"))
            .build();
        return credential;
    }

    public String getAccessToken() throws IOException
    {
        if(Calendar.getInstance().after(credentials.getExpirationTimeMilliseconds()))
            credentials.refreshToken();

        return credentials.getAccessToken();
    }
}

这会起作用,还是这种方法会导致任何问题?

0 个答案:

没有答案