java - 执行 Google Prediction API 命令行示例时出错

标签 java eclipse nullpointerexception google-api google-prediction

我已经下载了预测 api 的示例命令行程序并导入到 Eclipse 中,如提及 here .

我已经导入了该示例程序,并将 client_secrets.json 的内容替换为我从 api 控制台下载的文件值,如上面的链接所述。

我使用 standalone explorer 构建了模型.

但是我想通过我的java代码进行预测。所以下面我提到了代码。

package com.google.api.services.samples.prediction.cmdline;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.prediction.Prediction;
import com.google.api.services.prediction.PredictionScopes;
import com.google.api.services.prediction.model.Input;
import com.google.api.services.prediction.model.Input.InputInput;
import com.google.api.services.prediction.model.Output;
import com.google.api.services.prediction.model.Training;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;

/**
 * @author Yaniv Inbar
 */
public class PredictionSample {

  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "senti-model/1.0";

  static final String MODEL_ID = "senti-model";
  //static final String STORAGE_DATA_LOCATION = "enter_bucket/language_id.txt";

  /** Directory to store user credentials. */
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".store/prediction_sample");

  /**
   * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
   * globally shared instance across your application.
   */
  private static FileDataStoreFactory dataStoreFactory;

  /** Global instance of the HTTP transport. */
  private static HttpTransport httpTransport;

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

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(PredictionSample.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=prediction "
          + "into prediction-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(PredictionScopes.PREDICTION)).setDataStoreFactory(
        dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  private static void run() throws Exception {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    // authorization
    Credential credential = authorize();
    Prediction prediction = new Prediction.Builder(
        httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    //train(prediction);
    predict(prediction, "Is this sentence in English?");
    predict(prediction, "¿Es esta frase en Español?");
    predict(prediction, "Est-ce cette phrase en Français?");
  }

   private static void error(String errorMessage) {
    System.err.println();
    System.err.println(errorMessage);
    System.exit(1);
  }

  private static void predict(Prediction prediction, String text) throws IOException {
    Input input = new Input();
    InputInput inputInput = new InputInput();
    inputInput.setCsvInstance(Collections.<Object>singletonList(text));
    input.setInput(inputInput);
    Output output = prediction.trainedmodels().predict(MODEL_ID, input).execute();
    System.out.println("Text: " + text);
    System.out.println("Predicted language: " + output.getOutputLabel());
  }

  public static void main(String[] args) {
    try {
      run();
      // success!
      return;
    } catch (IOException e) {
      System.err.println(e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(1);
  }
}

这是我在执行此代码时遇到的错误:

Jun 24, 2014 2:11:09 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\deepesh.shetty\.store\prediction_sample
Jun 24, 2014 2:11:09 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\deepesh.shetty\.store\prediction_sample
java.lang.NullPointerException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
    at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
    at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96)
    at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
    at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
    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.api.services.samples.prediction.cmdline.PredictionSample.predict(PredictionSample.java:157)
    at com.google.api.services.samples.prediction.cmdline.PredictionSample.run(PredictionSample.java:100)
    at com.google.api.services.samples.prediction.cmdline.PredictionSample.main(PredictionSample.java:164)

帮助我解决问题。 谢谢。

最佳答案

.../jre/lib/security/java.policy

您可以尝试向以下所有人授予权限吗?

grant{
permission java.security.AllPermission;
};

关于java - 执行 Google Prediction API 命令行示例时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24382069/

相关文章:

java - 加速java中的像素识别

android - Phonegap Dreamweaver CS5.5 安卓应用

java - Eclipse Java : “The import com.jidesoft cannot be resolved”

java - 什么是 NullPointerException,我该如何解决?

java - 获取图像的RGB-YCbCr分量

java - JTextPane 中的复制粘贴图标

java - 如何将 emma 用于 jar 文件

eclipse - 如何使用固定 IP 地址或系统变量设置 DOCKER_HOST?

android - NullPointerException(可能是由getStringExtra或getTimeInstance引起的)

JavaFX jar 未随 JAR 文件一起加载,但在将代码编译为应用程序时加载正常