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
+ }
0 commit comments