Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.99 KB | None | 0 0
  1. package utils;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.Collections;
  9. import java.util.List;
  10.  
  11. import com.google.api.client.auth.oauth2.Credential;
  12. import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
  13. import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
  14. import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
  15. import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
  16. import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
  17. import com.google.api.client.http.AbstractInputStreamContent;
  18. import com.google.api.client.http.FileContent;
  19. import com.google.api.client.http.HttpTransport;
  20. import com.google.api.client.json.JsonFactory;
  21. import com.google.api.client.json.jackson2.JacksonFactory;
  22. import com.google.api.client.util.store.FileDataStoreFactory;
  23. import com.google.api.services.drive.Drive;
  24. import com.google.api.services.drive.DriveScopes;
  25. import com.google.api.services.drive.model.File;
  26. import java.io.BufferedReader;
  27. import java.net.HttpURLConnection;
  28. import java.net.MalformedURLException;
  29. import java.net.URL;
  30. import java.util.Arrays;
  31. import java.util.logging.Level;
  32. import java.util.logging.Logger;
  33.  
  34. public class GoogleDriveUtils {
  35.  
  36. private static final String APPLICATION_NAME = "SWD Workspace synchronizer";
  37.  
  38. private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
  39.  
  40. // Directory to store user credentials for this application.
  41. private static final java.io.File CREDENTIALS_FOLDER //
  42. = new java.io.File("src/main/resources");
  43.  
  44. private static final String CLIENT_SECRET_FILE_NAME = "credentials.json";
  45.  
  46. static final String[] scopes = {"email", DriveScopes.DRIVE};
  47.  
  48. private static final List<String> SCOPES = Arrays.asList(scopes);
  49.  
  50. // Global instance of the {@link FileDataStoreFactory}.
  51. private static FileDataStoreFactory DATA_STORE_FACTORY;
  52.  
  53. // Global instance of the HTTP transport.
  54. private static HttpTransport HTTP_TRANSPORT;
  55.  
  56. private static Drive driveService;
  57.  
  58. static {
  59. try {
  60. HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
  61. DATA_STORE_FACTORY = new FileDataStoreFactory(CREDENTIALS_FOLDER);
  62. driveService = getDriveService();
  63. } catch (Throwable t) {
  64. t.printStackTrace();
  65. System.exit(1);
  66. }
  67. }
  68.  
  69. private static Credential getCredentials() throws IOException {
  70.  
  71. java.io.File clientSecretFilePath = new java.io.File(CREDENTIALS_FOLDER, CLIENT_SECRET_FILE_NAME);
  72.  
  73. if (!clientSecretFilePath.exists()) {
  74. throw new FileNotFoundException("Please copy " + CLIENT_SECRET_FILE_NAME //
  75. + " to folder: " + CREDENTIALS_FOLDER.getAbsolutePath());
  76. }
  77.  
  78. InputStream in = new FileInputStream(clientSecretFilePath);
  79.  
  80. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
  81.  
  82. // Build flow and trigger user authorization request.
  83. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
  84. clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
  85. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  86. String accessToken = credential.getAccessToken();
  87. getUserInfo(accessToken);
  88. return credential;
  89. }
  90.  
  91. private static void getUserInfo(String accessToken){
  92. try {
  93. String url = "https://openidconnect.googleapis.com/v1/userinfo";
  94. URL obj = new URL(url);
  95. HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
  96. conn.setRequestProperty("Authorization", "Bearer " + accessToken);
  97.  
  98. BufferedReader in = new BufferedReader(
  99. new InputStreamReader(conn.getInputStream()));
  100. String inputLine;
  101. StringBuilder response = new StringBuilder();
  102.  
  103. while ((inputLine = in.readLine()) != null) {
  104. response.append(inputLine);
  105. }
  106. in.close();
  107.  
  108. //print result
  109. System.out.println(response.toString());
  110. } catch (Exception ex) {
  111. Logger.getLogger(GoogleDriveUtils.class.getName()).log(Level.SEVERE, null, ex);
  112. }
  113. }
  114.  
  115. public static Drive getDriveService() throws IOException {
  116. if (driveService != null) {
  117. return driveService;
  118. }
  119. Credential credential = getCredentials();
  120. //
  121. driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) //
  122. .setApplicationName(APPLICATION_NAME).build();
  123. return driveService;
  124. }
  125.  
  126. public static final File createGoogleFolder(String folderName, String retmoteParentId) throws IOException {
  127. // Create a folder in google drive using id of parent folder
  128. // Arguments:
  129. // - remoteParentId (String): id of parent folder in drive
  130. // - folderName (String): name of folder to be created
  131. // Returns:
  132. // - com.google.api.services.drive.model.File object representing created folder
  133. File fileMetadata = new File();
  134.  
  135. fileMetadata.setName(folderName);
  136. fileMetadata.setMimeType("application/vnd.google-apps.folder");
  137.  
  138. if (retmoteParentId != null) {
  139. List<String> parents = Arrays.asList(retmoteParentId);
  140. fileMetadata.setParents(parents);
  141. }
  142.  
  143. // Create a Folder.
  144. // Returns File object with id & name fields will be assigned values
  145. File file = driveService.files().create(fileMetadata).setFields("id, name").execute();
  146.  
  147. return file;
  148. }
  149.  
  150. // PRIVATE
  151. private static File _createGoogleFile(String googleFolderIdParent,
  152. String customFileName, AbstractInputStreamContent uploadStreamContent) throws IOException {
  153.  
  154. File fileMetadata = new File();
  155. fileMetadata.setName(customFileName);
  156.  
  157. List<String> parents = Arrays.asList(googleFolderIdParent);
  158. fileMetadata.setParents(parents);
  159.  
  160. File file = driveService.files().create(fileMetadata, uploadStreamContent)
  161. .setFields("id, webContentLink, webViewLink, parents").execute();
  162.  
  163. System.out.println("Also delete file with ID: " + file.getId());
  164. return file;
  165. }
  166.  
  167. public static File uploadFile(String filePath, String remoteParentId) throws IOException {
  168. // Create a file in google drive from local file under a folder in drive
  169. // Arguments:
  170. // - remoteParentId (String): id of parent folder in drive
  171. // - folderName (String): name of folder to be created
  172. // Returns:
  173. // - com.google.api.services.drive.model.File object representing created folder
  174. File fileMetadata = new File();
  175. java.io.File uploadFile = new java.io.File(filePath);
  176.  
  177. // set mimeType
  178. fileMetadata.setName(uploadFile.getName());
  179. fileMetadata.setMimeType("application/vnd.google-apps.file");
  180.  
  181. // set parent
  182. List<String> parents = Arrays.asList(remoteParentId);
  183. fileMetadata.setParents(parents);
  184.  
  185. FileContent mediaContent = new FileContent(fileMetadata.getMimeType(), uploadFile);
  186. File file = driveService.files().create(fileMetadata, mediaContent)
  187. .setFields("id, webContentLink, webViewLink, parents")
  188. .execute();
  189. System.out.println("File ID: " + file.getId());
  190.  
  191. return file;
  192. }
  193.  
  194. public static void deleteFile(String remoteFileId) throws IOException {
  195. driveService.files().delete(remoteFileId).execute();
  196. }
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement