/*
* Copyright 2014 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.way.gdrive;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.common.base.Charsets;
import com.google.common.io.CharSource;
import com.google.common.io.Resources;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
class DriveExecProvider implements Provider<DriveExec> {
private static final String CLIENTSECRETS_LOCATION = "/client_secrets.json";
private final GDriveTokens tokens;
@Inject
public DriveExecProvider(GDriveTokens tokens) {
this.tokens = tokens;
}
@Override
public DriveExec get() {
try {
NetHttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
URL url = Resources.getResource(GDrive.class, CLIENTSECRETS_LOCATION);
CharSource charSource = Resources.asCharSource(url, Charsets.UTF_8);
Reader reader = charSource.openStream();
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, reader);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientSecrets)
.build();
credential.setAccessToken(tokens.accessToken);
credential.setRefreshToken(tokens.refreshToken);
Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("GDrive")
.build();
return new DriveExecValid(drive);
} catch (IOException e) {
return new DriveExecError(e);
}
}
}