0

Я пытаюсь использовать API доменов, предлагаемый в Google +, я пытаюсь сделать работу с Quick Start для java, используя делегирование домена. Я выполнил эти шаги, также Я попросил моего администратора домена, чтобы предоставить доступ к проекту я создал в консоли, возобновляя я могу скомпилировать файл Java, но когда я бегу, я получаю ошибку 404, вот код:Google + Домены API Быстрый старт для java не работает

/* 
* Copyright 2013 Google Inc. All Rights Reserved. 
* 
* 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 com.google.plus.samples.quickstart.domains; 

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.http.HttpTransport; 
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.plusDomains.PlusDomains; 
import com.google.api.services.plusDomains.model.Acl; 
import com.google.api.services.plusDomains.model.Activity; 
import com.google.api.services.plusDomains.model.PlusDomainsAclentryResource; 
import com.google.api.services.plusDomains.model.Person; 

import java.io.IOException; 
import java.security.GeneralSecurityException; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 


/** 
* Simple program to demonstrate the Google+ Domains API. 
* 
* This program shows how to authenticate an app for domain-wide delegation and how 
* to complete an activities.insert API call. For details on how to authenticate on 
* a per-user basis using OAuth 2.0, or for examples of other API calls, please see 
* the documentation at https://developers.google.com/+/domains/. 
* 
* @author [email protected] (Joanna Smith) 
*/ 
public class DomainDelegation { 
    /** 
    * Update SERVICE_ACCOUNT_EMAIL with the email address of the service account for the client ID 
    * created in the developer console. 
    */ 
    private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]"; 

    /** 
    * Update SERVICE_ACCOUNT_PKCS12_FILE_PATH with the file path to the private key file downloaded 
    * from the developer console. 
    */ 
    private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = 
     "file-privatekey.p12"; 

    /** 
    * Update USER_EMAIL with the email address of the user within your domain that you would like 
    * to act on behalf of. 
    */ 
    private static final String USER_EMAIL = "[email protected]"; 


    /** 
    * plus.me and plus.stream.write are the scopes required to perform the tasks in this quickstart. 
    * For a full list of available scopes and their uses, please see the documentation. 
    */ 
    private static final List<String> SCOPE = Arrays.asList(
     "https://www.googleapis.com/auth/plus.me", 
     "https://www.googleapis.com/auth/plus.stream.write", 
     "https://www.googleapis.com/auth/plus.circles.read", 
     "https://www.googleapis.com/auth/plus.profiles.read", 
     "https://www.googleapis.com/auth/plus.stream.read", 
     "https://www.googleapis.com/auth/userinfo.profile"); 


    /** 
    * Builds and returns a Plus service object authorized with the service accounts 
    * that act on behalf of the given user. 
    * 
    * @return Plus service object that is ready to make requests. 
    * @throws GeneralSecurityException if authentication fails. 
    * @throws IOException if authentication fails. 
    */ 
    private static PlusDomains authenticate() throws GeneralSecurityException, IOException { 

    System.out.println(String.format("Authenticate the domain for %s", USER_EMAIL)); 

    HttpTransport httpTransport = new NetHttpTransport(); 
    JsonFactory jsonFactory = new JacksonFactory(); 

    // Setting the sub field with USER_EMAIL allows you to make API calls using the special keyword 
    // 'me' in place of a user id for that user. 
    GoogleCredential credential = new GoogleCredential.Builder() 
     .setTransport(httpTransport) 
     .setJsonFactory(jsonFactory) 
     .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
     .setServiceAccountScopes(SCOPE) 
     .setServiceAccountUser(USER_EMAIL) 
     .setServiceAccountPrivateKeyFromP12File(
      new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) 
     .build(); 

    System.out.println("credential " + credential); 
    // Create and return the Plus service object 
    PlusDomains service = new PlusDomains.Builder(httpTransport, jsonFactory, credential).build(); 

    return service; 
    } 

    /** 
    * Create a new post on behalf of the user associated with the credential object of the service, 
    * restricted to the domain. 
    * 
    * @param service Plus service object that is ready to make requests. 
    * @throws IOException if the insert operation fails or if authentication fails. 
    * @throws GeneralSecurityException if authentication fails. 
    */ 
    public static void main(String[] args) throws Exception { 
    // Create an authorized API client 
    PlusDomains service = authenticate(); 

    // Set the user's ID to 'me': requires the plus.me scope 
    String userId = "me"; 
    String msg = "Happy Monday! #caseofthemondays"; 

    System.out.println("Inserting activity " + service); 

    // Create the audience of the post 
    PlusDomainsAclentryResource res = new PlusDomainsAclentryResource(); 

    // Share to the domain 
    res.setType("domain"); 


    List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>(); 
    aclEntries.add(res); 

    Acl acl = new Acl(); 
    acl.setItems(aclEntries); 

    // Required, this does the domain restriction 
    acl.setDomainRestricted(true); 

    Activity activity = new Activity() 
     .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)) 
     .setAccess(acl); 
    //System.out.println("ativity " + activity); 

    activity = service.activities().insert(userId, activity).execute(); 

    System.out.println(activity); 
    } 
} 

Obviusly данные, такие как электронная почта и ключевой файл, у меня есть правильный код, это ошибка, которую я получаю:

Authenticate the domain for [email protected] 
credential [email protected]275d39 
04-dic-2013 8:59:50 com.google.api.client.googleapis.services.AbstractGoogleClient <init> 
ADVERTENCIA: Application name is not set. Call Builder#setApplicationName. 
Inserting activity [email protected] 
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found 
Not Found 
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145) 
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113) 
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312) 
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1045) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343) 
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460) 
    at com.google.plus.samples.quickstart.domains.DomainDelegation.main(DomainDelegation.java:154) 

Я потерян, пожалуйста, если кто-нибудь может мне помочь, я был бы благодарен.

+0

ли вы создать свой идентификатор клиента в Google Cloud Console или в старой консоли API Google? – BrettJ

+0

Ссылка в Quick Start для Java, похоже, является старой консолью API Google, когда я нахожу ссылку на ссылку, это адрес: http://developer.google.com/console, но я не нажал ссылку, Я пошел на более старую консоль, после вашего комментария я щелкнул по ссылке, и меня взяли на другую консоль, которую я не использовал, есть разница? –

+0

Недавно я слышал о проблеме, когда учетные данные учетной записи службы с новой консоли работают неправильно. Не уверен, что это все еще так. – BrettJ

ответ

1

Оказывается, что линия, которая содержит PlusDomains.builder теперь требует, чтобы setApplicationName называться:

PlusDomains service = new PlusDomains.Builder(httpTransport, jsonFactory, credential) 
    .setApplicationName('MyDomainsDemo') 
    .build(); 
+0

Я сделал ваше предложение, но все-таки у меня такая же проблема, я должен что-то добавить, учетная запись службы, которую я использовал для генерации идентификатора клиента, электронной почты и файла с секретным ключом, - это точно служебная учетная запись моей компании, так что это не связал учетную запись G +, тогда я не знаю, может ли эта функция повлиять, я также прочитал раздел часто задаваемых вопросов в документе и упоминал о порядке областей в моем java-файле и в разрешениях, предоставленных моим администратором, это говорит, что он должен быть в том же порядке, я думаю, что это не причина, но что вы думаете о том, что упоминалось? –

+0

Для создания учетных данных учетным записям не требуется учетная запись Google+. Посмотрим, сможем ли мы воссоздать проблему. – BrettJ

+0

Спасибо, я был бы очень признателен, если вы поможете мне. –

0

Я тестировал образец Java сегодня, и это работает. В инструкциях требуется несколько небольших обновлений, связанных с заменой ярлыков в консоли API, но если вы правильно настроите приложение, вы сможете начать работу.

Ошибка 404, скорее всего, вызвана неверно сконфигурированным клиентом и не является проблемой в выборке. Следующий скриншот должен помочь в получении правильных учетных данных. При создании учетной записи службы, вы получите новый регион выделен ниже:

Sources for Java Quickstart credentials

Убедитесь, что идентификатор клиента под обслуживание счетов тот же идентификатор клиента добавляется, когда вы выполнили общедоменную делегацию консоли администратора. Следующий скриншот показывает, где идентификатор клиента (первое поле в предыдущем скриншоте) идет:

enter image description here

Наконец, убедитесь, что адрес электронной почты настроен в src/com/google/plus/samples/quickstart/domains/DomainDelegation.java соответствует письмо от вашей учетной записи службы.

Если вы используете классическую консоль API, вам нужно будет добавить учетную запись службы в свой проект. Сделайте это из API Access -> Создать другой идентификатор клиента ... -> Учетная запись службы. Затем значения будут поступать из добавленного раздела:

enter image description here

+0

Хорошо, я постараюсь проверить все на месте, почему на вашем первом снимке экрана появляется идентификатор клиента для веб-приложения? не связано с учетной записью службы? и у меня есть другой вопрос: учетная запись, которую я использую для создания учетной записи службы, не имеет значения, это не учетная запись администратора, верно? или я должен использовать учетную запись администратора для создания учетной записи службы. –

+0

. Учетная запись, в которой я тестировалась, была учетной записью администратора, я не уверен, требуется ли это, но это может быть вашей проблемой. Дайте мне знать, помогает ли вам изменение учетной записи администратору, поэтому я могу соответствующим образом пересмотреть свой ответ. – class

+0

На скриншоте, который вы приложили, я вижу, что вы используете новую консоль Google для проектов, в моем случае я получил учетные данные со старой консоли, как вы думаете, это может сделать какую-то проблему этой функции? –

0

это работает!

с баночках

ANTLR-2.7.7.jar ДЖЕКСОНА-ядро-ASL-1.9.11.jar aopalliance-1.0.jar Javassist-3.15.0-GA.jar Обще-почта-1,3 .2.jar jboss-logging-3.1.0.GA.jar commons-logging-1.1.1.jar jboss-transaction-api_1.1_spec-1.0.0.Final.jar dom4j-1.6.1.jar jsr305- 1.3.9.jar google-api-client-1.17.0-rc.jar jstl-1.2.jar google-api-client-jackson2-1.17.0-rc-sources.jar mail-1.4.1.jar google-api-services-calendar-v3-rev87-1.19.0.jar mysql-connector-java-5.1.22.jar google-collections-1.0-rc2.jar spring-aop-3.2.2.RELEAS E.jar google-http-client-1.17.0-rc.jar spring-beans-3.2.2.RELEASE.jar google-http-client-jackson-1.17.0-rc.jar spring-context-3.2. 2.RELEASE.jar google-oauth-client-1.17.0-rc.jar spring-core-3.2.2.RELEASE.jar google-oauth-client-servlet-1.17.0-rc.jar spring-expression-3.2.2. RELEASE.jar hibernate-commons-annotations-4.0.1.Final.jar spring-jdbc-3.2.2.RELEASE.jar hibernate-core-4.1.10.Final.jar spring-orm-3.2.2.RELEASE. jar hibernate-jpa-2.0-api-1.0.1.Final.jar spring-tx-3.2.2.RELEASE.jar hsqldb-2.2.9.jar spring-web-3.2.2.RELEASE.jar httpclient- 4.0.1.jar весна-webmvc-3.2.2.RELEASE.jar httpcore-4.0.1.jar транзакций апи-1.1.jar ДЖЕКСОНА-ядро-2.1.3.jar

...

import java.io.File; 
import java.io.IOException; 
import java.security.GeneralSecurityException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Date; 
import java.util.TimeZone; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.jackson.JacksonFactory; 
import com.google.api.client.util.DateTime; 
import com.google.api.services.calendar.Calendar; 
import com.google.api.services.calendar.model.Event; 
import com.google.api.services.calendar.model.EventAttendee; 
import com.google.api.services.calendar.model.EventDateTime; 

..

public class GoogleCalNotificator { 
public static void addEvent(TurnosRepository repo, String fecha, 
      String inicio, String fin, String paciente, String cliente) { 

    HttpTransport httpTransport = new NetHttpTransport(); 
    JacksonFactory jsonFactory = new JacksonFactory(); 
    String scope = "https://www.googleapis.com/auth/calendar"; 

    GoogleCredential credential = null; 
    try { 
     credential = new GoogleCredential.Builder() 
       .setTransport(httpTransport) 
       .setJsonFactory(jsonFactory) 
       .setServiceAccountId(
         "[email protected]") 
       .setServiceAccountUser("[email protected]") 
       .setServiceAccountScopes(Arrays.asList(scope)) 
       .setServiceAccountPrivateKeyFromP12File(
         new File(repo.getParameter("P12_FILE"))) //p12 from gooleapiuser 

       .build(); 
    } catch (GeneralSecurityException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    Calendar service = new Calendar.Builder(httpTransport, jsonFactory, 
      credential).setApplicationName("appname").build(); 

    // ----------------- 
    Event event = new Event(); 

    event.setSummary("text "); 
    event.setLocation("loc "); 

    ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>(); 
    attendees.add(new EventAttendee().setEmail("[email protected]")); 
    // ... 
    event.setAttendees(attendees); 

    Date startDate = null; 
    Date endDate = null; 
    try { 
     startDate = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(fecha 
       + " " + inicio); 
     endDate = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(fecha 
       + " " + fin); 

    } catch (ParseException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    DateTime start = new DateTime(startDate, TimeZone.getTimeZone("America/Argentina/Buenos_Aires")); 
    event.setStart(new EventDateTime().setDateTime(start)); 
    DateTime end = new DateTime(endDate, TimeZone.getTimeZone("America/Argentina/Buenos_Aires")); 
    event.setEnd(new EventDateTime().setDateTime(end)); 

    // lo pongo en el calendario de julia 
    try { 
     Event createdEvent = service 
       .events() 
       .insert("[email protected]", 
         event).execute(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 
} 
+0

Я попытался запустить код с моими учетными данными и получил: «com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized». Ты знаешь почему? – YuriR

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