Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java Google Admin SDK API删除用户_Java_Google Admin Sdk - Fatal编程技术网

如何使用Java Google Admin SDK API删除用户

如何使用Java Google Admin SDK API删除用户,java,google-admin-sdk,Java,Google Admin Sdk,我进行了Java快速启动,得到了一个可以工作的应用程序,它只显示与登录帐户连接的所有用户的完整列表。我浏览了Java文档,发现唯一与删除用户相关的是user类中的“setDeletionTime”,但我用一个虚拟帐户尝试了这一点,并将时间设置为“null”,并尝试创建一个设置为今天的时间,但这两个时间都不适用于删除用户。我不知道我错过了什么 我正在使用的代码,大部分都是从google quickstart复制的 import com.google.api.client.auth.oauth2.C

我进行了Java快速启动,得到了一个可以工作的应用程序,它只显示与登录帐户连接的所有用户的完整列表。我浏览了Java文档,发现唯一与删除用户相关的是user类中的“setDeletionTime”,但我用一个虚拟帐户尝试了这一点,并将时间设置为“null”,并尝试创建一个设置为今天的时间,但这两个时间都不适用于删除用户。我不知道我错过了什么

我正在使用的代码,大部分都是从google quickstart复制的

import com.google.api.client.auth.oauth2.Credential;

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledAp;

import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.*;
import com.google.api.services.admin.directory.Directory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;


public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME =
    "Directory API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
    System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
    JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/admin-directory_v1-java-quickstart
 */
private static final List<String> SCOPES =
    Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    /* This does not work as of now
    InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
    */
    InputStream in = new FileInputStream("src/resources/client_secret.json");
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

/**
 * Build and return an authorized Admin SDK Directory client service.
 * @return an authorized Directory client service
 * @throws IOException
 */
public static Directory getDirectoryService() throws IOException {
    Credential credential = authorize();
    return new Directory.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

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


    // Build a new authorized API client service.
    Directory service = getDirectoryService();

    // Print the first 10 users in the domain.
    Users result = service.users().list().setCustomer("my_customer").setOrderBy("email").execute();
    List<User> users = result.getUsers();


    if (users == null || users.size() == 0) {
        System.out.println("No users found.");
    } else {
        for (User user : users) {
            //This is where I tried to delete the users
            //I have also tried using a normal for loop and nothing changes 
            that
            System.out.println();
        }
    }

}
import com.google.api.client.auth.oauth2.Credential;
导入com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledAp;
导入com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
导入com.google.api.client.googleapis.auth.oauth2.googleaauthorizationcodeflow;
导入com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
导入com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.util.store.FileDataStoreFactory;
导入com.google.api.services.admin.directory.DirectoryScopes;
导入com.google.api.services.admin.directory.model.*;
导入com.google.api.services.admin.directory.directory;
导入java.io.FileInputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.array;
导入java.util.List;
公共类快速入门{
/**应用程序名称*/
私有静态最终字符串应用程序\u名称=
“目录API Java快速启动”;
/**用于存储此应用程序的用户凭据的目录*/
private static final java.io.File DATA_STORE_DIR=new java.io.File(
System.getProperty(“user.home”),“.credentials/admin-directory_v1-java-quickstart”);
/**{@link FileDataStoreFactory}的全局实例*/
私有静态文件数据存储工厂数据存储工厂;
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_工厂=
JacksonFactory.getDefaultInstance();
/**HTTP传输的全局实例*/
专用静态HttpTransport HTTP_传输;
/**此快速启动所需作用域的全局实例。
*
*如果修改这些作用域,请删除以前保存的凭据
*位于~/.credentials/admin-directory\u v1-java-quickstart
*/
私有静态最终列表作用域=
Arrays.asList(DirectoryScopes.ADMIN\u DIRECTORY\u USER\u READONLY);
静止的{
试一试{
HTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
DATA\u STORE\u FACTORY=新文件datastorefactory(DATA\u STORE\u DIR);
}捕获(可丢弃的t){
t、 printStackTrace();
系统出口(1);
}
}
/**
*创建授权凭据对象。
*@返回授权凭证对象。
*@抛出异常
*/
公共静态凭据授权()引发IOException{
//加载客户端机密。
/*到目前为止,这不起作用
InputStream in=Quickstart.class.getResourceAsStream(“src/resources/client_secret.json”);
*/
InputStream in=newfileinputstream(“src/resources/client_secret.json”);
谷歌客户机密=
load(JSON_工厂,新的InputStreamReader(in));
//生成流并触发用户授权请求。
GoogleAuthorizationCodeFlow=
新的GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.setAccessType(“脱机”)
.build();
凭证凭证=新授权代码已安装App(
流,新的LocalServerReceiver())。授权(“用户”);
System.out.println(
“凭证保存到”+数据存储\目录getAbsolutePath());
返回凭证;
}
/**
*生成并返回授权的Admin SDK目录客户端服务。
*@返回授权目录客户端服务
*@抛出异常
*/
公共静态目录getDirectoryService()引发IOException{
凭证=授权();
返回新目录.Builder(
HTTP_传输、JSON_工厂、凭证)
.setApplicationName(应用程序名称)
.build();
}
公共静态void main(字符串[]args)引发IOException{
//构建新的授权API客户端服务。
目录服务=getDirectoryService();
//打印域中的前10个用户。
用户结果=service.Users().list().setCustomer(“我的客户”).setOrderBy(“电子邮件”).execute();
List users=result.getUsers();
if(users==null | | users.size()==0){
System.out.println(“未找到用户”);
}否则{
for(用户:用户){
//这就是我试图删除用户的地方
//我也尝试过使用普通for循环,但没有任何变化
那个
System.out.println();
}
}
}

在阅读了谷歌提供的所有信息后,我终于找到了答案……我想。我会在这里解释,并将其作为答案,因为它是有效的;但是,如果我做错了什么,请告诉我。无论如何,我做了以下几点:

所以第一件事是第一件事。每一个动作(据我所知)都通过http作为一个URL和一个命令。这意味着为了让任何事情发生,你必须有一个传输(由
HttpTransport
类给出)和一个工厂(由
HttpRequestFactory
类给出)创建保存操作/命令的
HttpRequest
对象

我们将发出的请求是“删除用户帐户”下显示的删除请求

这一切都可以通过以下方式实现:

HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory();
HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/userkey"));
但是等等!我们缺少一个非常重要的关键元素。我们有
List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);
HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credentials);
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.admin.directory.DirectoryScopes;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class Quickstart {
    /** Application name. */
    private static final String APPLICATION_NAME = "Deleting user example";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    //This creates the factory that is used for the user made requests
    private static HttpRequestFactory HTTP_REQUEST_FACTORY;

    //This is the credentials for the entire application
    private static Credential credential;

    /** Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/admin-directory_v1-java-quickstart
     */
    private static final List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }


    /**
     * Creates an authorized Credential object.
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        /* This does not work as of now
        InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
        */
        InputStream in = new FileInputStream("src/resources/client_secret.json");
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }


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



        System.out.println("Deleting user with email");
        credential = authorize();
        HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credential);
        HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/REPLACEMEWITHEMAILORUSERKEY"));
        deleteRequest.execute();

    }

}