OAuth2 Google Api java/eclipse

529 views Asked by At

I'm looking at [this example]https://developers.google.com/admin-sdk/directory/v1/quickstart/quickstart-java).

But I don't want to use that url copy/paste version to auth so I've read that I should use serviceaccount.

I downloaded the p12 key and placed it in my source folder. And I'm rebuilding the Google Example with some code I found on stackoverflow

So here's how far I get:

public class DirectoryCommandLine {

    HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();

    // Build service account credential.
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId("[email protected]")
        .setServiceAccountScopes(DirectoryScopes.all())
       .setServiceAccountPrivateKeyFromP12File(new java.io.File("eclipsejava-d6675et3ab71.p12"))
        .build();


    // Create a new authorized API client
    Directory service = new Directory.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("DirectoryCommandLine")
        .build();

    List<User> allUsers = new ArrayList<User>();
    Directory.Users.List request = service.users().list().setCustomer("my_customer");

    // Get all users
    do {
      try {
        Users currentPage = request.execute();
        allUsers.addAll(currentPage.getUsers());
        request.setPageToken(currentPage.getNextPageToken());
      } catch (IOException e) {
        System.out.println("An error occurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0 );

    // Print all users
    for (User currentUser : allUsers) {
      System.out.println(currentUser.getPrimaryEmail());
    }
  }
}

If I run this I get this error:

Error: Main method not found in class DirectoryCommandLine, please define the main method as:
   public static void main(String[] args)

I guess i need to add

public static void main(String[] args) throws IOException {

Infront/Before:

  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();

But then it all gets a mess: enter image description here

1

There are 1 answers

1
Cimballi On

This has nothing to do with Google APIs but Java class structure. Considering you are a beginner in Java you should start with more simple exercises.

Oracle and Internet provide a lot of documentation about Java. You can start looking at these links for example : https://docs.oracle.com/javase/tutorial/getStarted/application/ https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html