package io.gapi.vgen;

import com.google.api.Authentication;
import com.google.api.AuthenticationRule;
import com.google.api.Service;
import com.google.api.tools.framework.model.Interface;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Utility class that provides service configuration data from an Interface.
 */
public class ServiceConfig {
  /**
   * Return the service address.
   */
  public String getServiceAddress(Interface service) {
    return service.getModel().getServiceConfig().getName();
  }

  /**
   * Return the service port.
   * TODO(cbao): Read the port from config.
   */
  public Integer getServicePort() {
    return 443;
  }

  /**
   * Return a list of scopes for authentication.
   */
  public Iterable<String> getAuthScopes(Interface service) {
    List<String> result = new ArrayList<>();
    Service config = service.getModel().getServiceConfig();
    Authentication auth = config.getAuthentication();
    for (AuthenticationRule rule : auth.getRulesList()) {
      List<String> scopes = Arrays.asList(rule.getOauth().getCanonicalScopes().split(", "));
      result.addAll(scopes);
    }
    return result;
  }
}

@@ -205,20 +205,17 @@
 il.Array
-List
+s
 ;%0Aimport
@@ -217,38 +217,39 @@
 mport java.util.
-Arrays
+HashSet
 ;%0Aimport java.ut
@@ -256,16 +256,38 @@
 il.List;
+%0Aimport java.util.Set;
 %0A%0A/**%0A *
@@ -824,27 +824,26 @@
 vice) %7B%0A    
-Lis
+Se
 t%3CString%3E re
@@ -857,16 +857,14 @@
 new 
-ArrayLis
+HashSe
 t%3C%3E(
@@ -1048,80 +1048,435 @@
     
-List%3CString%3E scopes = Arrays.asList(rule.getOauth().getCanonicalScopes()
+// Scopes form a union and the union is used for down-scoping, so adding more scopes that%0A      // are subsets of the others already in the union essentially has no effect.%0A      // We are doing this for implementation simplicity so we don't have to compute which scopes%0A      // are subsets of the others.%0A      String scopesString = rule.getOauth().getCanonicalScopes();%0A      List%3CString%3E scopes = Arrays.asList(scopesString
 .spl
@@ -1484,14 +1484,51 @@
 t(%22,
- 
 %22));%0A
+      for (String scope : scopes) %7B%0A  
     
@@ -1543,20 +1543,31 @@
 .add
-All
 (scope
-s);
+.trim());%0A      %7D
 %0A   

Use hashset to avoid duplicate scopes.