【发布时间】:2018-03-02 11:48:36
【问题描述】:
首先,下面的代码 sn-ps 是 Google Cloud Project 应用程序的一部分,并且在我的本地客户端(Raspberry Pi 1)上运行。为了能够从连接到 Pi 的传感器发送数据到云需要授权。所有需要的客户端机密都存储在 src/main/resources 中的“client_secrets.json”中。
项目层次结构
在尝试使用客户端机密来授权以下代码时,会引发 NullPointerException。它是“CmdLineAuthenticationProvider”类的一部分(参见项目层次结构)。
InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(this.clientSecretsFile));
这可能只是一个与路径相关的错误,但我解决它的尝试都没有奏效(我尝试调整路径并将 client_secrets.json 复制到不同的位置以希望它找到它)。在“RaspiApp”类中,“clientSecretsFile”被设置为“/client_secret.json”。
CmdLineAuthenticationProvider provider = new CmdLineAuthenticationProvider();
provider.setClientSecretsFile("client_secret.json");
provider.setScopes(SCOPES);
// get the oauth credentials using the client secrets
Credential credential = provider.authorize();
在我的 pom.xml 中,我指定了如下资源:
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.directory}/classes</targetPath>
<filtering>false</filtering>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
完整的错误代码:
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at de.econfood.pi.app.CmdLineAuthenticationProvider.getCredential(CmdLineAuthenticationProvider.java:102)
at de.econfood.pi.app.CmdLineAuthenticationProvider.authorize(CmdLineAuthenticationProvider.java:64)
at de.econfood.pi.app.RaspiApp.getSensorEndpoint(RaspiApp.java:171)
at de.econfood.pi.app.RaspiApp.sendSensorData(RaspiApp.java:144)
at de.econfood.pi.app.RaspiApp.onGetRecsets(RaspiApp.java:126)
at de.econfood.pi.app.BrmReadThread.readBuffer(BrmReadThread.java:112)
at de.econfood.pi.app.BrmReadThread.run(BrmReadThread.java:20)
at java.lang.Thread.run(Thread.java:745)
【问题讨论】:
-
ClassLoader.getResourceAsStream() 不需要文件路径。它不会通过文件返回流。它通过资源返回一个流,该资源必须在类路径中可用。并且路径不能以
/开头。 -
检查编译后文件的位置。它应该在 target/classes/secret.json
-
@JBNizet 你完全正确!领先的 / 更像是解决这个问题的绝望尝试,但没有它我会收到完全相同的错误。我将编辑问题以避免出现类似的建议。
-
为什么要将资源目标配置为非默认值?
-
我使用这个项目作为指导:link to github。除了使用的传感器和他定义的资源之外,这几乎是相同的用例。我也尝试注释掉
没有成功。
标签: java maven nullpointerexception google-cloud-platform inputstreamreader