Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Использование
Google Drive API
для управления хранилищем отчетов
Presented by Владимир Виноградов
(uladzimir_vinahradau@epam.com)
Agenda
1. История
2. Возможности Google Drive API
3. Применение Google Drive API
Взгляд в прошлое
Постановка задачи
Варианты решения
Возможности
Google Drive API
ВозможностиGoogle Drive API
Управление метаданными файлов
Загрузка файлов с сервера
Передача файлов на сервер
Работа с папками
Совместное использование файлов
Управление ревизиями файлов
Поиск папок/файлов
Применение
Google Drive API
Информация о Google Drive
About about = drive.about().get().execute();
//ROOT folder ID
about.getRootFolderId();
();
Создание папок/файлов
import com.google.api.services.drive.model.File;
……
File file = new File();
file.setMimeType("application/vnd.google-apps.folder");
file.setTitle(folderName);
ParentReference parent = new ParentReference();
parent.setId(parentId);
file.setParents(Arrays.asList(parent));
file = drive.files().insert(file).execute();
……
Создание папок/файлов
Загрузка файлов на сервер
Drive.Files.Insert insert = drive.files()
.insert(file, mediaContent)
.setConvert(Boolean.TRUE);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setProgressListener(new FileUploadProgressListener());
insert.execute();
Загрузка файлов на сервер
InputStreamContent mediaContent =
new InputStreamContent("text/plain;charset=UTF-8",
new ByteArrayInputStream(text.getBytes()));
mediaContent.setLength(text.length());
Поиск папки/файла
…
List<String> itemIds = new ArrayList<String>();
for (ChildReference item : children.getItems()) {
File file = drive.files().get(item.getId()).execute();
if (BooleanUtils.isFalse(file.getExplicitlyTrashed())
&& StringUtils.equalsIgnoreCase(itemName, file.getTitle())) {
itemIds.add(file.getId());
}
}
…
Потомки объектов
Children.List request = drive.children().list(parent.getFolderId());
do {
ChildList children = request.execute();
// обработка списка children
……
request.setPageToken(children.getNextPageToken());
} while (StringUtils.isNotEmpty(request.getPageToken()));
Поделиться файлом
Permission permission = new Permission();
permission.setValue(USER_NAME);
permission.setType("user");
permission.setRole("writer");
drive.permissions().insert(itemId, permission).execute;();
Итоги за год работы
();Количество отчетов более 5500
Объем отчетов более 10G
Количество пользователей 10+
Использование Google Drive API для управления хранилищем отчетов
Приложение
1. Необходимые зависимости
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.14.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>1.14.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.14.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v2-rev70-1.14.1-beta</version>
</dependency>
2. Подключение к Google Drive
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final MemoryCredentialStore CREDENTIAL_STORE = new MemoryCredentialStore();
………………….
public Drive getInstance() {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, IOUtils.toInputStream(CLIENT_SECRET_JSON));
GoogleCredential credential = new Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY).setClientSecrets(clientSecrets).build();
if (!credentialStore.load(userId, credential)) {
credential.setRefreshToken(refresh_token);
credential.setAccessToken(access_token);
credentialStore.store(userId, credential);
}
AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT,
JSON_FACTORY,
clientSecrets,
Collections.singleton(DriveScopes.DRIVE_FILE)
).setCredentialStore(CREDENTIAL_STORE).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(client.getUserId());
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("Application Name").build();
}
2. Подключение к Google Drive
CLIENT_SECRET_JSON:
{
"web": {
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"redirect_uris":[
"https://developers.google.com/oauthplayground",
"https://localhost"
],
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_email":"client email",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/clientID",
"client_id":"clientID",
"client_secret":"client_secret"
}
}
3. Источники
https://developers.google.com/drive
https://developers.google.com/drive/v2/reference/

More Related Content

Использование Google Drive API для управления хранилищем отчетов