如何在Java中执行简单的Google Cloud Trace请求 [英] How to do a simple Google Cloud Trace request in Java

查看:119
本文介绍了如何在Java中执行简单的Google Cloud Trace请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的Google Cloud Trace项目执行一个简单的推送跟踪操作,而我似乎根本无法发送数据.

I am trying to perform a simple push traces operation to my Google Cloud Trace project and I simply can't seem to send data across.

这是我的build.gradle文件:

Here is my build.gradle file:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.oauth-client:google-oauth-client-java6:1.20.0'
    compile 'com.google.apis:google-api-services-cloudtrace:v1-rev6-1.22.0'
}

jar {
    from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

以及下面的Java代码以及有关项目ID和我的机密文件的虚拟信息:

And the following Java code with dummy info for the project ID and my secrets file:

package test;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
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.services.cloudtrace.v1.CloudTrace;
import com.google.api.services.cloudtrace.v1.CloudTraceScopes;
import com.google.api.services.cloudtrace.v1.model.Trace;
import com.google.api.services.cloudtrace.v1.model.TraceSpan;
import com.google.api.services.cloudtrace.v1.model.Traces;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.Instant;
import java.util.Collections;

public class Test {

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        GoogleCredential cred = GoogleCredential
                .fromStream(
                        new FileInputStream("/path/to/secrets.json"),
                        httpTransport,
                        jsonFactory)
                .createScoped(Collections.singletonList(CloudTraceScopes.TRACE_APPEND));

        CloudTrace gceTrace = new CloudTrace.Builder(httpTransport, jsonFactory, cred)
                .setApplicationName("Google Cloud Trace test app")
                .build();

        TraceSpan span1 = new TraceSpan();
        span1.setName("test");
        span1.setStartTime(Long.toString(Instant.now().toEpochMilli()*1000000)+"Z");
        Trace trace = new Trace();
        trace.setSpans(Collections.singletonList(span1));
        Traces traces = new Traces();
        traces.setTraces(Collections.singletonList(trace));
        gceTrace.projects().patchTraces("myprojectid", traces).execute();
    }

}

我目前收到以下错误,其中没有任何有用的指示,但我的startTime值似乎有问题:

I currently get the following error that contains no helpful indication except something seems to be wrong with my startTime value:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value at 'traces.traces[0].spans[0].start_time' (type.googleapis.com/google.protobuf.Timestamp), Field 'startTime', Invalid time format: Failed to parse input",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid value at 'traces.traces[0].spans[0].start_time' (type.googleapis.com/google.protobuf.Timestamp), Field 'startTime', Invalid time format: Failed to parse input",
  "status" : "INVALID_ARGUMENT"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    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:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at test.Test.main(Test.java:44)

我尝试将startTime替换为以下值:

I have tried to replace the startTime with the following value:

span1.setStartTime("2016-08-04T01:00:00Z");

这给了我

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Request contains an invalid argument.",
    "reason" : "badRequest"
  } ],
  "message" : "Request contains an invalid argument.",
  "status" : "INVALID_ARGUMENT"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    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:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at test.Test.main(Test.java:44)

我还尝试添加endTime与:

I also tried adding a endTime with:

span1.setEndTime("2016-08-04T01:00:01Z");

这也给我同样的错误.

由于无法为此找到一个可行的Java示例,因此我对所要做的事情一无所知. 预先感谢您提供可行解决方案的任何提示.

I'm pretty much at a lost at what needs to be done as I cannot find a single working Java example for this. Thank you in advance for any pointers for a working solution.

推荐答案

最后弄清楚了.这是一个工作示例,其中指出了必填字段和可选字段.

Finally figured it out. Here's a working example with mandatory and optional fields pointed out.

build.gradle

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.oauth-client:google-oauth-client-java6:1.20.0'
    compile 'com.google.apis:google-api-services-cloudtrace:v1-rev6-1.22.0'
}

jar {
    from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

Test.java

package test;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
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.services.cloudtrace.v1.CloudTrace;
import com.google.api.services.cloudtrace.v1.CloudTraceScopes;
import com.google.api.services.cloudtrace.v1.model.Trace;
import com.google.api.services.cloudtrace.v1.model.TraceSpan;
import com.google.api.services.cloudtrace.v1.model.Traces;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        GoogleCredential cred = GoogleCredential
                .fromStream(
                        new FileInputStream("/path/to/secrets.json"),
                        httpTransport,
                        jsonFactory)
                .createScoped(Collections.singletonList(CloudTraceScopes.TRACE_APPEND));

        CloudTrace gceTrace = new CloudTrace.Builder(httpTransport, jsonFactory, cred)
                .setApplicationName("Google Cloud Trace test app")
                .build();

        // They are optional
        Map<String, String> labels = new HashMap<>();
        labels.put("key1", "val1");

        TraceSpan span = new TraceSpan();
        span.setSpanId(new BigInteger("1")); // Mandatory
        span.setName("test"); // Optional
        span.setKind("RPC_SERVER"); // Optional
        span.setStartTime("2016-08-04T01:00:00Z"); // Optional
        span.setEndTime("2016-08-04T01:00:01Z"); // Optional
        span.setLabels(labels); // Optional
        Trace trace = new Trace();
        trace.setProjectId("myprojectid"); // Mandatory
        trace.setTraceId("A096D4956A424EEB98AE7863505B1E1F"); // Mandatory
        trace.setSpans(Collections.singletonList(span)); // Mandatory
        Traces traces = new Traces();
        traces.setTraces(Collections.singletonList(trace)); // Mandatory
        gceTrace.projects().patchTraces("myprojectid", traces).execute();
    }

}

虽然一些值是可选的,例如startTime或endTime,但在其中放置一些内容是有意义的.

While some values are optional, like startTime or endTime, it makes sense to put something there.

由于此问题显示了期望值,查看描述每个字段的REST API文档,尤其是对于诸如Trace ID之类的神秘值:

I managed to put it together thanks to this question showing the expected values and looking at the REST API doc describing each field, especially for cryptic values like Trace ID:

  • patchTraces()
  • Trace and TraceSpan

这篇关于如何在Java中执行简单的Google Cloud Trace请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆