자바 빠른 시작

빠른 시작에서는 Google Workspace API

Google Workspace 빠른 시작에서는 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 세부 정보를 확인하세요. 따라서 자체 앱에 클라이언트 라이브러리를 사용합니다. 이 빠른 시작에서는 테스트에 적합한 간소화된 인증 접근 방식 환경입니다 프로덕션 환경의 경우 인증 및 승인 이전 액세스 사용자 인증 정보 선택 선택할 수 있습니다.

Google Meet API에 요청하는 Java 명령줄 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google Meet이 사용 설정된 Google Workspace 계정.

환경 설정

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Google Meet API를 사용 설정합니다.

    API 사용 설정

새 Google Cloud 프로젝트를 사용하여 이 빠른 시작을 완료하는 경우 본인을 테스트 사용자로 추가합니다. 이미 계정을 이 단계를 완료한 경우에는 다음 섹션으로 건너뛰세요.

  1. Google Cloud 콘솔에서 메뉴 로 이동합니다. > API 및 서비스 > OAuth 동의 화면.

    OAuth 동의 화면으로 이동

  2. 사용자 유형으로 내부를 선택한 다음 만들기를 클릭합니다.
  3. 앱 등록 양식을 작성한 다음 저장하고 계속하기를 클릭합니다.
  4. 지금은 범위 추가를 건너뛰고 저장 후 계속을 클릭할 수 있습니다. 나중에 외부에서 사용하기 위해 앱을 만들 때 Google Workspace 조직에서 사용하는 경우 사용자 유형외부로 변경한 다음 앱에 필요한 승인 범위를 추가합니다.

  5. 앱 등록 요약을 검토합니다. 변경하려면 수정을 클릭합니다. 앱이 등록이 확인되면 대시보드로 돌아가기를 클릭합니다.

데스크톱 애플리케이션의 사용자 인증 정보 승인

최종 사용자를 인증하고 앱의 사용자 데이터에 액세스하려면 다음을 실행해야 합니다. 하나 이상의 OAuth 2.0 클라이언트 ID를 만듭니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  4. 이름 필드에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 만들기를 클릭합니다. OAuth 클라이언트 생성 화면이 표시되고 새 클라이언트 ID와 클라이언트 비밀번호가 표시됩니다.
  6. 확인을 클릭합니다. 새로 생성된 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  7. 다운로드한 JSON 파일을 credentials.json로 저장하고 작업 디렉터리로 이동합니다

작업공간 준비

  1. 작업 디렉터리에서 새 프로젝트 구조를 만듭니다.

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. src/main/resources/ 디렉터리에서 credentials.json 파일을 복사합니다. 다운로드해 볼 수 있습니다

  3. 기본 build.gradle 파일을 열고 콘텐츠를 다음 코드를 참조하세요.

    meet/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'MeetQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.cloud:google-cloud-meet:0.3.0'
        implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
    }
    

샘플 설정

  1. src/main/java/ 디렉터리에서 build.gradle 파일의 mainClassName 값과 일치합니다.

  2. 새 Java 파일에 다음 코드를 포함합니다.

    meet/quickstart/src/main/java/MeetQuickstart.java
    import java.awt.Desktop;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URI;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Collections;
    import java.util.List;
    
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.apps.meet.v2.CreateSpaceRequest;
    import com.google.apps.meet.v2.Space;
    import com.google.apps.meet.v2.SpacesServiceClient;
    import com.google.apps.meet.v2.SpacesServiceSettings;
    import com.google.auth.Credentials;
    import com.google.auth.oauth2.ClientId;
    import com.google.auth.oauth2.DefaultPKCEProvider;
    import com.google.auth.oauth2.TokenStore;
    import com.google.auth.oauth2.UserAuthorizer;
    
    /* class to demonstrate use of Drive files list API */
    public class MeetQuickstart {
      /**
       * Directory to store authorization tokens for this application.
       */
      private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
      /**
       * Global instance of the scopes required by this quickstart.
       * If modifying these scopes, delete your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES = Collections
          .singletonList("https://www.googleapis.com/auth/meetings.space.created");
    
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      private static final String USER = "default";
    
      // Simple file-based token storage for storing oauth tokens
      private static final TokenStore TOKEN_STORE = new TokenStore() {
        private Path pathFor(String id) {
          return Paths.get(".", TOKENS_DIRECTORY_PATH, id + ".json");
        }
    
        @Override
        public String load(String id) throws IOException {
          if (!Files.exists(pathFor(id))) {
            return null;
          }
          return Files.readString(pathFor(id));
        }
    
        @Override
        public void store(String id, String token) throws IOException {
          Files.createDirectories(Paths.get(".", TOKENS_DIRECTORY_PATH));
          Files.writeString(pathFor(id), token);
        }
    
        @Override
        public void delete(String id) throws IOException {
          if (!Files.exists(pathFor(id))) {
            return;
          }
          Files.delete(pathFor(id));
        }
      };
    
      /**
       * Initialize a UserAuthorizer for local authorization.
       * 
       * @param callbackUri
       * @return
       */
      private static UserAuthorizer getAuthorizer(URI callbackUri) throws IOException {
        // Load client secrets.
        try (InputStream in = MeetQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH)) {
          if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
          }
    
          ClientId clientId = ClientId.fromStream(in);
    
          UserAuthorizer authorizer = UserAuthorizer.newBuilder()
              .setClientId(clientId)
              .setCallbackUri(callbackUri)
              .setScopes(SCOPES)
              .setPKCEProvider(new DefaultPKCEProvider() {
                // Temporary fix for https://github.com/googleapis/google-auth-library-java/issues/1373
                @Override
                public String getCodeChallenge() {
                  return super.getCodeChallenge().split("=")[0];
                }
              })
              .setTokenStore(TOKEN_STORE).build();
          return authorizer;
        }
      }
    
      /**
       * Run the OAuth2 flow for local/installed app.
       * 
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credentials getCredentials()
          throws Exception {
    
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().build();
        try {
          URI callbackUri = URI.create(receiver.getRedirectUri());
          UserAuthorizer authorizer = getAuthorizer(callbackUri);
    
          Credentials credentials = authorizer.getCredentials(USER);
          if (credentials != null) {
            return credentials;
          }
    
          URL authorizationUrl = authorizer.getAuthorizationUrl(USER, "", null);
          if (Desktop.isDesktopSupported() && 
              Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            Desktop.getDesktop().browse(authorizationUrl.toURI());
          } else {
            System.out.printf("Open the following URL to authorize access: %s\n",
                authorizationUrl.toExternalForm());
          }
    
          String code = receiver.waitForCode();
          credentials = authorizer.getAndStoreCredentialsFromCode(USER, code, callbackUri);
          return credentials;
        } finally {
          receiver.stop();
        }
      }
    
      public static void main(String... args) throws Exception {
        // Override default service settings to supply user credentials.
        Credentials credentials = getCredentials();
        SpacesServiceSettings settings = SpacesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();
    
        try (SpacesServiceClient spacesServiceClient = SpacesServiceClient.create(settings)) {
          CreateSpaceRequest request = CreateSpaceRequest.newBuilder()
              .setSpace(Space.newBuilder().build())
              .build();
          Space response = spacesServiceClient.createSpace(request);
          System.out.printf("Space created: %s\n", response.getMeetingUri());
        } catch (IOException e) {
          // TODO(developer): Handle errors
          e.printStackTrace();
        }
      }
    }

샘플 실행

  1. 샘플을 실행합니다.

    gradle run
    
  1. 샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다. <ph type="x-smartling-placeholder">
      </ph>
    1. 아직 Google 계정에 로그인하지 않은 경우 메시지가 표시되면 로그인합니다. 만약 여러 계정에 로그인한 경우 승인에 사용할 계정 1개를 선택하세요.
    2. 수락을 클릭합니다.

    Java 애플리케이션이 실행되고 Google Meet API를 호출합니다.

    승인 정보는 파일 시스템에 저장되므로 다음에 샘플을 실행할 때 승인하라는 메시지가 표시되지 않습니다.

다음 단계