Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package utils;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.Collections;
- import java.util.List;
- 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.AbstractInputStreamContent;
- import com.google.api.client.http.FileContent;
- import com.google.api.client.http.HttpTransport;
- import com.google.api.client.json.JsonFactory;
- import com.google.api.client.json.jackson2.JacksonFactory;
- import com.google.api.client.util.store.FileDataStoreFactory;
- import com.google.api.services.drive.Drive;
- import com.google.api.services.drive.DriveScopes;
- import com.google.api.services.drive.model.File;
- import java.io.BufferedReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.Arrays;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class GoogleDriveUtils {
- private static final String APPLICATION_NAME = "SWD Workspace synchronizer";
- private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
- // Directory to store user credentials for this application.
- private static final java.io.File CREDENTIALS_FOLDER //
- = new java.io.File("src/main/resources");
- private static final String CLIENT_SECRET_FILE_NAME = "credentials.json";
- static final String[] scopes = {"email", DriveScopes.DRIVE};
- private static final List<String> SCOPES = Arrays.asList(scopes);
- // Global instance of the {@link FileDataStoreFactory}.
- private static FileDataStoreFactory DATA_STORE_FACTORY;
- // Global instance of the HTTP transport.
- private static HttpTransport HTTP_TRANSPORT;
- private static Drive driveService;
- static {
- try {
- HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
- DATA_STORE_FACTORY = new FileDataStoreFactory(CREDENTIALS_FOLDER);
- driveService = getDriveService();
- } catch (Throwable t) {
- t.printStackTrace();
- System.exit(1);
- }
- }
- private static Credential getCredentials() throws IOException {
- java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
- if (!clientSecretFilePath.exists()) {
- throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
- + " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
- }
- InputStream in = new FileInputStream(clientSecretFilePath);
- 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");
- String accessToken = credential.getAccessToken();
- getUserInfo(accessToken);
- return credential;
- }
- private static void getUserInfo(String accessToken){
- try {
- String url = "https://openidconnect.googleapis.com/v1/userinfo";
- URL obj = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
- conn.setRequestProperty("Authorization", "Bearer " + accessToken);
- BufferedReader in = new BufferedReader(
- new InputStreamReader(conn.getInputStream()));
- String inputLine;
- StringBuilder response = new StringBuilder();
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- in.close();
- //print result
- System.out.println(response.toString());
- } catch (Exception ex) {
- Logger.getLogger(GoogleDriveUtils.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public static Drive getDriveService() throws IOException {
- if (driveService != null) {
- return driveService;
- }
- Credential credential = getCredentials();
- //
- driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
- .setApplicationName(APPLICATION_NAME).build();
- return driveService;
- }
- public static final File createGoogleFolder(String folderName, String retmoteParentId) throws IOException {
- // Create a folder in google drive using id of parent folder
- // Arguments:
- // - remoteParentId (String): id of parent folder in drive
- // - folderName (String): name of folder to be created
- // Returns:
- // - com.google.api.services.drive.model.File object representing created folder
- File fileMetadata = new File();
- fileMetadata.setName(folderName);
- fileMetadata.setMimeType("application/vnd.google-apps.folder");
- if (retmoteParentId != null) {
- List<String> parents = Arrays.asList(retmoteParentId);
- fileMetadata.setParents(parents);
- }
- // Create a Folder.
- // Returns File object with id & name fields will be assigned values
- File file = driveService.files().create(fileMetadata).setFields("id, name").execute();
- return file;
- }
- // PRIVATE
- private static File _createGoogleFile(String googleFolderIdParent,
- String customFileName, AbstractInputStreamContent uploadStreamContent) throws IOException {
- File fileMetadata = new File();
- fileMetadata.setName(customFileName);
- List<String> parents = Arrays.asList(googleFolderIdParent);
- fileMetadata.setParents(parents);
- File file = driveService.files().create(fileMetadata, uploadStreamContent)
- .setFields("id, webContentLink, webViewLink, parents").execute();
- System.out.println("Also delete file with ID: " + file.getId());
- return file;
- }
- public static File uploadFile(String filePath, String remoteParentId) throws IOException {
- // Create a file in google drive from local file under a folder in drive
- // Arguments:
- // - remoteParentId (String): id of parent folder in drive
- // - folderName (String): name of folder to be created
- // Returns:
- // - com.google.api.services.drive.model.File object representing created folder
- File fileMetadata = new File();
- java.io.File uploadFile = new java.io.File(filePath);
- // set mimeType
- fileMetadata.setName(uploadFile.getName());
- fileMetadata.setMimeType("application/vnd.google-apps.file");
- // set parent
- List<String> parents = Arrays.asList(remoteParentId);
- fileMetadata.setParents(parents);
- FileContent mediaContent = new FileContent(fileMetadata.getMimeType(), uploadFile);
- File file = driveService.files().create(fileMetadata, mediaContent)
- .setFields("id, webContentLink, webViewLink, parents")
- .execute();
- System.out.println("File ID: " + file.getId());
- return file;
- }
- public static void deleteFile(String remoteFileId) throws IOException {
- driveService.files().delete(remoteFileId).execute();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement