Friday, September 25, 2015

Java Singleton

Singleton is a POJO java class which is just having a nice name. It is used when one resource is shared within one application.

Example: write an access code in a singleton class then call it from other class

1. Singleton class

public class DirectorySingleton {
    private static DirectorySingleton authSingleton = new DirectorySingleton();
    public static  Directory dir= null;

   /* A private Constructor prevents any other   class from instantiating. */
   static{

        if (dir == null){
            try{
                 HttpTransport httpTransport = new NetHttpTransport();
                JsonFactory jsonFactory = new JacksonFactory();

                GoogleCredential credential = new GoogleCredential.Builder()
                .setClientSecrets(GmailConstants.CLIENT_ID, GmailConstants.CLIENT_SECRET)
                .setJsonFactory(jsonFactory).setTransport(httpTransport).build()
                .setRefreshToken(GmailConstants.REFRESH_TOKEN).setAccessToken(GmailConstants.ACCESS_TOKEN);

                Directory service = new Directory.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName(GmailConstants.APPLICATION_NAME)
                .build();
               // System.out.println("called once");

                dir = service;
            }catch(Exception e){

            }

        }

   }
}

2, used it from other class:

    Boolean userExisted = DirectoryUtils.validateUser(DirectorySingleton.dir,
                     GmailConstants.DOMAIN_NAME, primaryGmailID);

No comments: