2014-10-10 3 views
0

Я хотел бы позвонить в конечные точки Java для API приложений Google Calendar API. Это мой (неполный) класс утилиты для вызова Календаря Google. Я пытаюсь получить или создать Календар Google Google, определенный для моего приложения «Zeppa», с аутентифицированной конечной точки. Я делаю это, вызывая zeppaCalendarEntry (Пользователь), где пользователь является экземпляром пользователя из аутентифицированного вызова. Консоль API имеет API календаря, а файл client_secrets.json - для App Engine и учетных записей служб.Доступ к API Google из конечных точек приложения (Java)

Ошибка возникает в Get Client Credential, возвращается null InputStream. Любые ссылки на стандартную процедуру или исправления были бы замечательными.

class ZeppaCalendarUtils { 

private ZeppaCalendarUtils() { 
} 

/** 
* Global instance of the {@link DataStoreFactory}. The best practice is to 
* make it a single globally shared instance across your application. 
*/ 
private static final AppEngineDataStoreFactory DATA_STORE_FACTORY = AppEngineDataStoreFactory 
     .getDefaultInstance(); 

/** Global instance of the HTTP transport. */ 
static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport(); 

/** Global instance of the JSON factory. */ 
static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 

private static GoogleClientSecrets clientSecrets = null; 

/** 
* Creates a new Google Calendar for user 
* @param calendarClient 
* @return 
* @throws GeneralSecurityException 
* @throws IOException 
*/ 
private static CalendarListEntry createZeppaCalendarEntry(
     Calendar calendarClient) throws GeneralSecurityException, 
     IOException { 

    CalendarListEntry content = new CalendarListEntry(); 
    content.setAccessRole(Constants.CALENDAR_ACCESS_ROLE); 
    content.setBackgroundColor(Constants.CALENDAR_COLOR_BACKGROUND); 
    content.setForegroundColor(Constants.CALENDAR_COLOR_FOREGROUND); 
    content.setDefaultReminders(Constants.CALENDAR_DEFAULT_REMINDERS); 
    content.setSelected(Constants.CALENDAR_SELECTED); 
    content.setSummary("Zeppa"); 
    content.setId(Constants.CALENDAR_ID); 

    CalendarListEntry result = calendarClient.calendarList() 
      .insert(content).execute(); 

    return result; 

} 

/** 
* Retrieve or create a Users calendar 
* @param user 
* @return 
* @throws GeneralSecurityException 
* @throws IOException 
*/ 
public static CalendarListEntry zeppaCalendarEntry(User user) 
     throws GeneralSecurityException, IOException { 

    Calendar calendarClient = loadCalendarClient(user.getUserId()); 
    CalendarListEntry result = calendarClient.calendarList() 
      .get(Constants.CALENDAR_ID).execute(); 

    if (result == null) { 
     result = createZeppaCalendarEntry(calendarClient); 
    } 

    return result; 
} 

/** 
* Retrieve a Client Secrets 
* @return 
* @throws IOException 
*/ 
static GoogleClientSecrets getClientCredential() throws IOException { 
    if (clientSecrets == null) { 

     InputStream stream = ZeppaCalendarUtils.class 
       .getResourceAsStream("client_secrets.json"); 

     Reader clientSecretReader = new InputStreamReader(stream); 
     clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, 
       clientSecretReader); 
    } 
    return clientSecrets; 
} 

/** 
* Generate the calendar client for calls to the API 
* @param userId 
* @return 
* @throws IOException 
*/ 
private static Calendar loadCalendarClient(String userId) 
     throws IOException { 
    Credential credential = newAuthFlow().loadCredential(userId); 
    return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
      .build(); 
} 


/** 
* Create an auth flow 
* @return 
* @throws IOException 
*/ 
private static GoogleAuthorizationCodeFlow newAuthFlow() throws IOException { 
    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, 
      JSON_FACTORY, getClientCredential(), 
      Collections.singleton(CalendarScopes.CALENDAR)) 
      .setDataStoreFactory(DATA_STORE_FACTORY) 
      .setAccessType("offline").build(); 
} 

}

ответ

0

Если вы check the docs recommended method подключиться к API Google из App Engine, вы можете увидеть, что он не использует загрузчик классов-х getResourceAsStream, он использует FileInputStream на File объекта. Попытайтесь использовать это вместо этого и посмотрите, не прекратит ли он возвращать null.

Смежные вопросы