Skip to content

Commit de7bdec

Browse files
committed
Updated to include Permissions, delete file and create folder API demonstration.
1 parent 852dc9b commit de7bdec

File tree

25 files changed

+1474
-6
lines changed

25 files changed

+1474
-6
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ RemoteSystemsTempFiles
2929
**/target
3030
**/.classpath
3131
**/.project
32+
**/client_secret_gd.json
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[[{"location":"D:\\practice\\mvn_local_repo\\com\\google\\apis\\google-api-services-drive\\v3-rev130-1.25.0\\google-api-services-drive-v3-rev130-1.25.0.jar","type":"JAR","hints":{}},"ABSENT"],[{"location":"D:\\practice\\sbt-gd\\workspace\\drive-list-files","type":"PROJECT","hints":{"PROJECT_NAME":"drive-list-files"}},"com.carbonrider.tutorials.gdrive.sbt:drive-list-files:0.0.1"],[{"location":"C:\\Program Files\\Java\\jre1.8.0_171","type":"JRE","hints":{"EXECUTION_ENVIRONMENT":"JavaSE-1.8"}},"jre:jre:1.8.0"]]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
����
2+
coordinate fingerprintssymbolic-names
3+
classifierselfccallovrdselfmovrpovrmstaticsctor

.recommenders/index/http___download_eclipse_org_recommenders_models_oxygen_/_6.frq

+1,018
Large diffs are not rendered by default.

.recommenders/index/http___download_eclipse_org_recommenders_models_oxygen_/_6.nrm

+1
Large diffs are not rendered by default.

.recommenders/index/http___download_eclipse_org_recommenders_models_oxygen_/write.lock

Whitespace-only changes.

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
# tutorial_google_drive_api_spring_boot
22
Features source code from Tutorial series - Google Drive REST API with Spring boot (https://www.youtube.com/playlist?list=PL6staZz89fj_sEJkcwATwSjKTENIkMCAl)
3+
4+
You must create Google Developer Account to run this code. Also make sure to download and place the client secret json file in src/main/resources/keys folder.

credentials/StoredCredential

991 Bytes
Binary file not shown.

drive-list-files/pom.xml

+12
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@
4949
<version>3.3.1-1</version>
5050
</dependency>
5151

52+
<dependency>
53+
<groupId>com.google.api-client</groupId>
54+
<artifactId>google-api-client</artifactId>
55+
<version>1.25.0</version>
56+
</dependency>
57+
58+
<dependency>
59+
<groupId>com.google.apis</groupId>
60+
<artifactId>google-api-services-drive</artifactId>
61+
<version>v3-rev130-1.25.0</version>
62+
</dependency>
63+
5264
<dependency>
5365
<groupId>org.springframework.boot</groupId>
5466
<artifactId>spring-boot-starter-test</artifactId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
/**
2+
*
3+
*/
4+
package com.carbonrider.tutorials.gdrive.sbt.drivelistfiles.controller;
5+
6+
import java.io.InputStreamReader;
7+
import java.util.ArrayList;
8+
import java.util.Arrays;
9+
import java.util.Collections;
10+
import java.util.List;
11+
12+
import javax.annotation.PostConstruct;
13+
import javax.servlet.http.HttpServletRequest;
14+
import javax.servlet.http.HttpServletResponse;
15+
16+
import org.springframework.beans.factory.annotation.Value;
17+
import org.springframework.core.io.Resource;
18+
import org.springframework.stereotype.Controller;
19+
import org.springframework.web.bind.annotation.DeleteMapping;
20+
import org.springframework.web.bind.annotation.GetMapping;
21+
import org.springframework.web.bind.annotation.PathVariable;
22+
import org.springframework.web.bind.annotation.PostMapping;
23+
import org.springframework.web.bind.annotation.ResponseBody;
24+
25+
import com.carbonrider.tutorials.gdrive.sbt.drivelistfiles.dto.FileItemDTO;
26+
import com.google.api.client.auth.oauth2.Credential;
27+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
28+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
29+
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
30+
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
31+
import com.google.api.client.http.FileContent;
32+
import com.google.api.client.http.HttpTransport;
33+
import com.google.api.client.http.javanet.NetHttpTransport;
34+
import com.google.api.client.json.JsonFactory;
35+
import com.google.api.client.json.jackson2.JacksonFactory;
36+
import com.google.api.client.util.store.FileDataStoreFactory;
37+
import com.google.api.services.drive.Drive;
38+
import com.google.api.services.drive.DriveScopes;
39+
import com.google.api.services.drive.model.File;
40+
import com.google.api.services.drive.model.FileList;
41+
import com.google.api.services.drive.model.Permission;
42+
43+
/**
44+
* @author Yogesh Jadhav
45+
*
46+
*/
47+
@Controller
48+
public class HomepageController {
49+
50+
private static HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
51+
private static JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
52+
53+
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
54+
55+
private static final String USER_IDENTIFIER_KEY = "MY_DUMMY_USER";
56+
57+
@Value("${google.oauth.callback.uri}")
58+
private String CALLBACK_URI;
59+
60+
@Value("${google.secret.key.path}")
61+
private Resource gdSecretKeys;
62+
63+
@Value("${google.credentials.folder.path}")
64+
private Resource credentialsFolder;
65+
66+
private GoogleAuthorizationCodeFlow flow;
67+
68+
@PostConstruct
69+
public void init() throws Exception {
70+
GoogleClientSecrets secrets = GoogleClientSecrets.load(JSON_FACTORY,
71+
new InputStreamReader(gdSecretKeys.getInputStream()));
72+
flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, secrets, SCOPES)
73+
.setDataStoreFactory(new FileDataStoreFactory(credentialsFolder.getFile())).build();
74+
}
75+
76+
@GetMapping(value = { "/" })
77+
public String showHomePage() throws Exception {
78+
boolean isUserAuthenticated = false;
79+
80+
Credential credential = flow.loadCredential(USER_IDENTIFIER_KEY);
81+
if (credential != null) {
82+
boolean tokenValid = credential.refreshToken();
83+
if (tokenValid) {
84+
isUserAuthenticated = true;
85+
}
86+
}
87+
88+
return isUserAuthenticated ? "dashboard.html" : "index.html";
89+
}
90+
91+
@GetMapping(value = { "/googlesignin" })
92+
public void doGoogleSignIn(HttpServletResponse response) throws Exception {
93+
GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
94+
String redirectURL = url.setRedirectUri(CALLBACK_URI).setAccessType("offline").build();
95+
response.sendRedirect(redirectURL);
96+
}
97+
98+
@GetMapping(value = { "/oauth" })
99+
public String saveAuthorizationCode(HttpServletRequest request) throws Exception {
100+
String code = request.getParameter("code");
101+
if (code != null) {
102+
saveToken(code);
103+
104+
return "dashboard.html";
105+
}
106+
107+
return "index.html";
108+
}
109+
110+
private void saveToken(String code) throws Exception {
111+
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(CALLBACK_URI).execute();
112+
flow.createAndStoreCredential(response, USER_IDENTIFIER_KEY);
113+
114+
}
115+
116+
@GetMapping(value = { "/create" })
117+
public void createFile(HttpServletResponse response) throws Exception {
118+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
119+
120+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
121+
.setApplicationName("googledrivespringbootexample").build();
122+
123+
File file = new File();
124+
file.setName("profile.jpg");
125+
126+
FileContent content = new FileContent("image/jpeg", new java.io.File("D:\\practice\\sbtgd\\sample.jpg"));
127+
File uploadedFile = drive.files().create(file, content).setFields("id").execute();
128+
129+
String fileReference = String.format("{fileID: '%s'}", uploadedFile.getId());
130+
response.getWriter().write(fileReference);
131+
}
132+
133+
@GetMapping(value = { "/uploadinfolder" })
134+
public void uploadFileInFolder(HttpServletResponse response) throws Exception {
135+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
136+
137+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
138+
.setApplicationName("googledrivespringbootexample").build();
139+
140+
File file = new File();
141+
file.setName("digit.jpg");
142+
file.setParents(Arrays.asList("1_TsS7arQRBMY2t4NYKNdxta8Ty9r6wva"));
143+
144+
FileContent content = new FileContent("image/jpeg", new java.io.File("D:\\practice\\sbtgd\\digit.jpg"));
145+
File uploadedFile = drive.files().create(file, content).setFields("id").execute();
146+
147+
String fileReference = String.format("{fileID: '%s'}", uploadedFile.getId());
148+
response.getWriter().write(fileReference);
149+
}
150+
151+
@GetMapping(value = { "/listfiles" }, produces = { "application/json" })
152+
public @ResponseBody List<FileItemDTO> listFiles() throws Exception {
153+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
154+
155+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
156+
.setApplicationName("googledrivespringbootexample").build();
157+
158+
List<FileItemDTO> responseList = new ArrayList<>();
159+
160+
FileList fileList = drive.files().list().setFields("files(id,name,thumbnailLink)").execute();
161+
for (File file : fileList.getFiles()) {
162+
FileItemDTO item = new FileItemDTO();
163+
item.setId(file.getId());
164+
item.setName(file.getName());
165+
item.setThumbnailLink(file.getThumbnailLink());
166+
responseList.add(item);
167+
}
168+
169+
return responseList;
170+
}
171+
172+
@PostMapping(value= {"/makepublic/{fileId}"}, produces = {"application/json"})
173+
public @ResponseBody Message makePublic(@PathVariable(name="fileId")String fileId) throws Exception {
174+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
175+
176+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
177+
.setApplicationName("googledrivespringbootexample").build();
178+
179+
Permission permission = new Permission();
180+
permission.setType("anyone");
181+
permission.setRole("reader");
182+
183+
drive.permissions().create(fileId, permission).execute();
184+
185+
186+
Message message = new Message();
187+
message.setMessage("Permission has been successfully granted.");
188+
return message;
189+
}
190+
191+
@DeleteMapping(value = { "/deletefile/{fileId}" }, produces = "application/json")
192+
public @ResponseBody Message deleteFile(@PathVariable(name = "fileId") String fileId) throws Exception {
193+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
194+
195+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
196+
.setApplicationName("googledrivespringbootexample").build();
197+
198+
drive.files().delete(fileId).execute();
199+
200+
Message message = new Message();
201+
message.setMessage("File has been deleted.");
202+
return message;
203+
}
204+
205+
@GetMapping(value = { "/createfolder/{folderName}" }, produces = "application/json")
206+
public @ResponseBody Message createFolder(@PathVariable(name = "folderName") String folder) throws Exception {
207+
Credential cred = flow.loadCredential(USER_IDENTIFIER_KEY);
208+
209+
Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, cred)
210+
.setApplicationName("googledrivespringbootexample").build();
211+
212+
File file = new File();
213+
file.setName(folder);
214+
file.setMimeType("application/vnd.google-apps.folder");
215+
216+
drive.files().create(file).execute();
217+
218+
Message message = new Message();
219+
message.setMessage("Folder has been created successfully.");
220+
return message;
221+
}
222+
223+
class Message {
224+
private String message;
225+
226+
public String getMessage() {
227+
return message;
228+
}
229+
230+
public void setMessage(String message) {
231+
this.message = message;
232+
}
233+
234+
}
235+
236+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
*
3+
*/
4+
package com.carbonrider.tutorials.gdrive.sbt.drivelistfiles.dto;
5+
6+
import java.io.Serializable;
7+
8+
/**
9+
* @author Yogesh Jadhav
10+
*
11+
*/
12+
public class FileItemDTO implements Serializable {
13+
14+
/**
15+
*
16+
*/
17+
private static final long serialVersionUID = 1L;
18+
19+
private String name;
20+
21+
private String id;
22+
23+
private String thumbnailLink;
24+
25+
public String getName() {
26+
return name;
27+
}
28+
29+
public void setName(String name) {
30+
this.name = name;
31+
}
32+
33+
public String getId() {
34+
return id;
35+
}
36+
37+
public void setId(String id) {
38+
this.id = id;
39+
}
40+
41+
public String getThumbnailLink() {
42+
return thumbnailLink;
43+
}
44+
45+
public void setThumbnailLink(String thumbnailLink) {
46+
this.thumbnailLink = thumbnailLink;
47+
}
48+
49+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
spring.resources.cache.cachecontrol.max-age=1
2+
3+
google.secret.key.path=classpath:keys/client_secret_gd.json
4+
google.oauth.callback.uri=http://192.168.56.1.nip.io:8080/oauth
5+
google.credentials.folder.path=file:D:\\practice\\sbt-gd\\workspace\\credentials
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
html {
2+
min-height: 100%;
3+
font-family: sans-serif;
4+
-webkit-font-smoothing: antialiased;
5+
}
6+
7+
body {
8+
background: linear-gradient(to bottom right, #3D4258, #6670A0, #9688B4);
9+
line-height: 1.5;
10+
font-size: 18px;
11+
}
12+
13+
#pages {
14+
max-width: 500px;
15+
margin: 0 auto;
16+
}
17+
18+
.page {
19+
background: #cfcfcf;
20+
}
21+

0 commit comments

Comments
 (0)