GoogleConfig.java 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
package web.multitask.trismegistoservices.config;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

@Configuration
public class GoogleConfig {

    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    private static final String CREDENTIALS_FILE_PATH = "/trimegistro-mongo-3e687dba9acb.json";
    private static final String CREDENTIALS_FOLDER_PATH = "/tokens";
    
    @Bean
    public Drive getDrive() {
        try {
            String APPLICATION_NAME = "FullService Application";
            JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
33
            return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY,
34 35 36 37 38 39 40 41 42 43 44 45 46
                    new HttpCredentialsAdapter(getCredentials(HTTP_TRANSPORT)))
                    .setApplicationName(APPLICATION_NAME)
                    .build();
        } catch (GeneralSecurityException | IOException e) {
            System.out.println("Error: " + e);
            return null;
        }
    }

    GoogleCredentials getCredentials(final NetHttpTransport HTTP_TRANSPORT)
            throws IOException {
        InputStream in = GoogleConfig.class.getResourceAsStream(CREDENTIALS_FOLDER_PATH+CREDENTIALS_FILE_PATH);
        if (in == null) throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FOLDER_PATH+CREDENTIALS_FILE_PATH);
47
        return GoogleCredentials.fromStream(in).createScoped(SCOPES);
48
    }
49
}