001/* 002 * (C) Copyright 2015-2016 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * 018 * Nelson Silva 019 */ 020package org.nuxeo.ecm.liveconnect.google.drive.credential; 021 022import java.io.File; 023import java.io.IOException; 024import java.security.GeneralSecurityException; 025import java.util.Collections; 026 027import org.nuxeo.ecm.liveconnect.core.CredentialFactory; 028 029import com.google.api.client.auth.oauth2.Credential; 030import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 031import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 032import com.google.api.client.http.HttpTransport; 033import com.google.api.client.json.JsonFactory; 034import com.google.api.client.json.jackson2.JacksonFactory; 035import com.google.api.services.drive.DriveScopes; 036 037/** 038 * Credential factory for Service Accounts. 039 * 040 * @since 7.3 041 */ 042public class ServiceAccountCredentialFactory implements CredentialFactory { 043 044 private final String accountId; 045 046 private final File p12File; 047 048 public ServiceAccountCredentialFactory(String accountId, File p12File) { 049 this.accountId = accountId; 050 this.p12File = p12File; 051 } 052 053 @Override 054 public Credential build(String user) throws IOException { 055 try { 056 return new GoogleCredential.Builder() // 057 .setTransport(getHttpTransport()) // 058 .setJsonFactory(getJsonFactory()) // 059 .setServiceAccountId(accountId) // 060 .setServiceAccountPrivateKeyFromP12File(p12File) // 061 .setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE)) // 062 .setServiceAccountUser(user).build(); 063 } catch (GeneralSecurityException e) { 064 throw new IOException(e); 065 } 066 } 067 068 protected static JsonFactory getJsonFactory() { 069 return JacksonFactory.getDefaultInstance(); 070 } 071 072 protected static HttpTransport getHttpTransport() throws IOException { 073 try { 074 return GoogleNetHttpTransport.newTrustedTransport(); 075 } catch (GeneralSecurityException e) { 076 throw new IOException(e); 077 } 078 } 079}