GithubHelp home page GithubHelp logo

datadog / datadog-api-client-java Goto Github PK

View Code? Open in Web Editor NEW
61.0 492.0 30.0 57.98 MB

Java client for the Datadog API

License: Apache License 2.0

Shell 0.02% Java 94.79% Python 0.32% Gherkin 4.10% Jinja 0.76%
datadog datadog-api java-client openapi

datadog-api-client-java's Introduction

datadog-api-client-java

This repository contains a Java API client for the Datadog API.

Requirements

Building the API client library requires:

  1. Java 1.8+
  2. Maven/Gradle

Installation

To install the API client library to your local Maven repository, simply execute:

mvn clean install

To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:

mvn clean deploy

Refer to the OSSRH Guide for more information.

Maven users

Add this dependency to your project's POM:

<dependency>
  <groupId>com.datadoghq</groupId>
  <artifactId>datadog-api-client</artifactId>
  <version>2.10.0</version>
  <scope>compile</scope>
</dependency>

See the Releases page for the latest available version.

Gradle users

Add this dependency to your project's build file:

compile "com.datadoghq:datadog-api-client:2.0.0"

See the Releases page for the latest available version.

Others

At first generate the JAR by executing:

mvn clean package

Then manually install the following JARs:

  • target/datadog-api-client-<VERSION>.jar
  • target/lib/*.jar

Getting Started

Please follow the installation instruction and execute the following Java code:

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.MonitorsApi;
import com.datadog.api.client.v1.model.Monitor;
import com.datadog.api.client.v1.model.MonitorType;
import java.util.Arrays;

public class MonitorCreatedExample {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    Monitor body =
        new Monitor()
            .name("my-monitor")
            .type(MonitorType.LOG_ALERT)
            .query(
                """
logs("service:foo AND type:error").index("main").rollup("count").by("source").last("5m") > 2
""")
            .message("some message Notify: @hipchat-channel")
            .tags(Arrays.asList("test:example", "env:ci"))
            .priority(3L);

    try {
      Monitor result = apiInstance.createMonitor(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling MonitorsApi#createMonitor");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Asynchronous support

All API methods have asynchronous versions returning CompletableFuture when adding the Async suffix to their names:

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.v1.api.MonitorsApi;

public class ListMonitorsAsyncExample {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    apiInstance.listMonitorsAsync().thenApply(monitors -> {
      System.out.println(monitors);
      return null;
    }).exceptionally(error -> {
      System.out.println(error);
      return null;
    });
  }
}

Unstable Endpoints

This client includes access to Datadog API endpoints while they are in an unstable state and may undergo breaking changes. An extra configuration step is required to enable these endpoints:

defaultClient.setUnstableOperationEnabled("<Version>.<OperationName>", true);

where <OperationName> is the name of the method used to interact with that endpoint. For example: listSLOCorrection, or getSLOHistory

Changing Server

When talking to a different server, like the eu instance, change the serverVariables on your client:

HashMap<String, String> serverVariables = new HashMap<String, String>();
serverVariables.put("site", "datadoghq.eu");
defaultApiClient.setServerVariables(serverVariables);

Disable compressed payloads

If you want to disable GZIP compressed responses, set the compress flag on your client:

defaultClient.setCompress(false)

Enable requests logging

If you want to enable requests logging, set the debugging flag on your client:

defaultClient.setDebugging(true)

Enable Retry

To enable the client to retry when rate limited (status 429) or status 500 and above:

defaultClient.enableRetry(true)

The interval between 2 retry attempts will be the value of the x-ratelimit-reset response header when available. If not, it will be : Math.pow (multiplier_for_retry_backoff, current_retry_count)*base_for_retry_backoff.

Configure proxy

You can provide custom connectorProvider implementation to clientConfig to use proxy. See example below using ApacheConnectorProvider:

import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.DashboardsApi;
import com.datadog.api.client.v1.model.DashboardSummary;

public class ProxyExample {
  public static void main( String[] args ) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    ClientConfig clientConfig = defaultClient.getClientConfig().connectorProvider(new ApacheConnectorProvider());
    clientConfig.property(ClientProperties.PROXY_URI, "http://127.0.0.1:80");
    defaultClient.setClientConfig(clientConfig);

    DashboardsApi apiInstance = new DashboardsApi(defaultClient);
    try {
      DashboardSummary result =
          apiInstance.listDashboards();
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DashboardsApi#listDashboards");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Using alternative artifacts

Outside of the regular JAR file we also release 2 artifacts that can be useful for development, namely:

  • jar-with-dependencies, which contains all the dependencies of the client in a single JAR
  • shaded-jar, which includes and renames the core dependencies of the client, allowing you to use different versions of those libraries in your project.

To use them in Maven, just add the classifier keyword in the dependency definition. For example:

<dependency>
  <groupId>com.datadoghq</groupId>
  <artifactId>datadog-api-client</artifactId>
  <version>2.10.0</version>
  <classifier>shaded-jar</classifier>
  <scope>compile</scope>
</dependency>

Documentation for API Endpoints and Models

Javadoc is available on javadoc.io.

Documentation for Authorization

To programmatically defined authorization headers, calls the configureApiKeys method with a map containing the required secrets for the operations:

HashMap<String, String> secrets = new HashMap<>();
secrets.put("apiKeyAuth", "<YOUR API KEY>");
secrets.put("appKeyAuth", "<YOUR APPLICATION KEY>");
generalApiClient.configureApiKeys(secrets);

Recommendation

It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issues.

Author

[email protected]

datadog-api-client-java's People

Contributors

api-clients-generation-pipeline[bot] avatar bgong-mdsol avatar borsch avatar burberius avatar dependabot[bot] avatar hantingzhang2 avatar hugo-ma-alves avatar jack-edmonds-dd avatar jimschubert avatar jirikuncar avatar jmini avatar jorgerod avatar joschi avatar kiran-sivakumar avatar marcoreni avatar matiasdwek avatar mosheelisha avatar nkzou avatar nmuesch avatar nouemankhal avatar ravisankar-challa avatar reinhard-ptv avatar saigiridhar21 avatar sebastien-rosset avatar skarimo avatar spacether avatar therve avatar viclovsky avatar wing328 avatar zippolyte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datadog-api-client-java's Issues

Confusing documentation for setting app key, is it needed at all?

Describe the bug

Looking at the documentation at
https://github.com/DataDog/datadog-api-client-java#documentation-for-authorization
to set the appKey and apiKey, we should do

HashMap<String, String> secrets = new HashMap<>();
secrets.put("apiKeyAuth", "<YOUR API KEY>");
secrets.put("appKeyAuth", "<YOUR APPLICATION KEY>");
generalApiClient.configureApiKeys(secrets);

But looking at the source for configureApiKeys, it looks like this

public ApiClient configureApiKeys(Map<String, String> secrets) {
    for (Map.Entry<String, Authentication> authEntry : authentications.entrySet()) {
      Authentication auth = authEntry.getValue();
      if (auth instanceof ApiKeyAuth) {
        String name = authEntry.getKey();
        if (secrets.containsKey(name)) {
          ((ApiKeyAuth) auth).setApiKey(secrets.get(name));
        }
      }
    }
    return this;
  }

This method doesn't bother looking at the appKey at all, only the api key.
I'm not sure if this is an issue with the documentation, or if it's an actual bug in the code.

Expected behavior
I expect the app key to be configured according to the example in the documentation,
or if the the app key is not required, remove it from the example in the docs.

Environment and Versions (please complete the following information):
2.12.0

Client api can not run with javax 1.x dependency at runtime

Describe the bug
As javax 1 do not provide any method to parse URI with a String, when an execution is bind to an old javax version and user can do nothing (like inside apache spark distribution), the client api can not send data to datadof.

at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:356) at org.apache.spark.sql.execution.streaming.StreamExecution$$anon$1.run(StreamExecution.scala:244) Caused by: java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder; at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:96) at org.glassfish.jersey.client.JerseyWebTarget.<init>(JerseyWebTarget.java:48) at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:274) at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:56) at com.datadog.api.v1.client.ApiClient.invokeAPI(ApiClient.java:1337)

Monitor Search and SLO History not updated to handle breaking changes

Describe the bug

  • The SLO History API "data.overall.precision" field is sometimes being returned as a single float value instead of a map as defined in the spec
     com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.String,java.lang.Double>` out of VALUE_NUMBER_FLOAT token
      at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 2869] (through reference chain: com.datadog.api.v1.client.model.SLOHistoryResponse["data"]->com.datadog.api.v1.client.model.SLOHistoryResponseData["monitors"]->java.util.ArrayList[0]->com.datadog.api.v1.client.model.SLOHistorySLIData["precision"])
    
  • The Monitor Search API "monitors.type" field is returning "metric-slo alert", which isn't defined in the spec.
     com.fasterxml.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of `com.datadog.api.v1.client.model.MonitorType`, problem: Unexpected value 'metric-slo alert'
      at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 5302] (through reference chain: com.datadog.api.v1.client.model.MonitorSearchResponse["monitors"]->java.util.ArrayList[3]->com.datadog.api.v1.client.model.MonitorSearchResult["type"])
    

Both of these result the SDK throwing a javax.ws.rs.ProcessingException.

To Reproduce
Have opened a ticket here https://help.datadoghq.com/hc/en-us/requests/574449. Not sure how to recreate, but I've added example IDs in the ticket.

Expected behavior
The SDK processes these correctly.

Environment and Versions (please complete the following information):
Version 1.2 of the SDK

Additional context
This issue has been going on for months and looks to be that the SDK hasn't been updated to reflect changes that are already in production.

Example in "Getting Started" section of README doesn't compile

Describe the bug
The example in the "Getting Started" section of the README doesn't compile for me because of a syntax error.

To Reproduce
Steps to reproduce the behavior:

  1. Try to compile the Java code in the "Getting Started" section of the README

Expected behavior
I expected the code to compile without errors.

Screenshots

image

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • Java: openjdk 17 2021-09-14
  • com.datadoghq:datadog-api-client: 2.0.0

Provide a shaded/standalone jar to avoid dependencies issues

Is your feature request related to a problem? Please describe.

Datadog api client depends on popular third-party libraries that are fast moving and which implementation may conflict with the one of the application it needs to be integrated with. Clashes are often exacerbated by excessive transitive dependencies issues.

Describe the solution you'd like

Provide a shaded/standalone jar that is self contained with no dependencies (except for the api interfaces needed)

Examples:

Describe alternatives you've considered

  • Add a lengthy list of exclusions to the datadog-api-client and hope for the best that the glassfish client and jackson code in use will be compatible with the one used in the application

  • Fork the datadog-api-client code and maintain it to be compatible

None of those solution are adequate for increased adoption of the datadog-api-client library across a wide range of applications and benefit from any improvement of the project in a safe way.

java.lang.ClassNotFoundException: jakarta.ws.rs.client.InvocationCallback

Spring boot version: 2.6.4
Java version: 11
datadog-api-client: 2.9.0

ApiClient defaultClient = ApiClient.getDefaultApiClient();
java.lang.ClassNotFoundException: jakarta.ws.rs.client.InvocationCallback at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na] at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na] at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ~[na:na]

Common interface/implementation of HttpClient for all APIs

Is your feature request related to a problem? Please describe.
Right now each API version namespace takes a different ApiClient (com.datadog.api.v1.client.ApiClient vs com.datadog.api.v2.client.ApiClient)
If you need to use APIs from both V1 and V2, you have to configure each ApiClient separately leading to duplicated code for things such as:

Describe the solution you'd like
I would like to see ApiClient exist outside of the versioned namespace and able to be used across multiple versions,

Describe alternatives you've considered
A common interface across all the API Clients would also work that defines the common setters though this may have higher memory footprint due to duplicate API Clients

Unhandled EventAlertType "user_update"

Describe the bug
If event contains "alert_type":"user_update" an exception is raised.

To Reproduce
Steps to reproduce the behavior:

  1. fetch events from datadog
  2. try to parse it
  3. an exception occured
  4. See error

Caused by: com.fasterxml.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of 'com.datadog.api.v1.client.model.EventAlertType', problem: Unexpected value 'user_update'

Expected behavior
All possible alert types should be covered in EventAlertType enum class

Environment and Versions (please complete the following information):
`

	<dependency>
		<groupId>com.datadoghq</groupId>
		<artifactId>datadog-api-client</artifactId>
		<version>1.0.0-beta.6</version>
	</dependency>`

Example of fetched events
{ "events": [ { "alert_type": "user_update", "comments": [], "date_happened": 1603179512, ...

Site variable not accepted

Environment variable:

DD_SITE=datadoghq.com

Produces error:
The variable site in the server URL has invalid value datadoghq.com.

Version: com.datadoghq:datadog-api-client:1.0.0
Java/Spring Application

Per the documentation: https://docs.datadoghq.com/api/latest/metrics/

Not specifying the site, and I assume leaving the library to default, results in:

com.datadog.api.v1.client.ApiException: {"status":"error","code":403,"errors":["Forbidden"],"statuspage":"http://status.datadoghq.com","twitter":"http://twitter.com/datadogops","email":"[email protected]"}

Don't require passing concrete HashMap type

Describe the bug

ApiClient#configureApiKeys should accept a Map instead of requiring HashMap.

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • Version: 1.0.0-beta.7

Response body of ApiException is null when receiving a 400 error while trying to create events

Describe the bug

While trying to debug an application I am working on that uses the DataDog API to create events, I received a 400 Bad Request error whose responseBody was null. This made it difficult to troubleshoot the HTTP error, because there was no easy way to access an explanation of why the request was invalid.

To Reproduce

  dataDogClient = Configuration.getDefaultApiClient();
  dataDogClient.setApiKey(API_KEY);
  eventsApi = new EventsApi(dataDogClient);
  EventCreateRequest request = new EventCreateRequest();
  request.setTitle("Request Title");
  // Date.getTime() returns a timestamp in milliseconds, but the API expects a timestamp in seconds.
  request.setDateHappened(Date.now().getTime());
  try {
    eventsApi.createEvent(request);
  } catch(ApiException e) {
    // This prints "null" instead of an explanation of why the request failed
    System.out.println(e.getResponseBody());
  }

Expected behavior

I expect e.getResponseBody() to return an object containing the string "Event too far in the future", which is the error message that the API returns. Instead, the response body is null.

Environment and Versions (please complete the following information):

On Windows 10, a Maven project with the following dependency:

        <dependency>
            <groupId>com.datadoghq</groupId>
            <artifactId>datadog-api-client</artifactId>
            <version>1.0.0</version>
            <scope>compile</scope>
        </dependency>

getSLOHistory fails with SLO type time-slice

Describe the bug

getSLOHistory fails to retrieve SLO History for time-slice SLOs, with the following error:

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot coerce String value ("NO_DATA") to `java.lang.Double` value (but might if coercion using `CoercionConfig` was enabled)
 at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 971] (through reference chain: com.datadog.api.client.v1.model.SLOHistoryResponse["data"]->com.datadog.api.client.v1.model.SLOHistoryResponseData["overall"]->com.datadog.api.client.v1.model.SLOHistorySLIData["history"]->java.util.ArrayList[0]->java.util.ArrayList[1])

Only SLOs of type time-slice are affected.

To Reproduce
Steps to reproduce the behavior:

We followed the most minimal example from the SLO API documentation:

ApiClient defaultClient = ApiClient.getDefaultApiClient();
ServiceLevelObjectivesApi apiInstance = new ServiceLevelObjectivesApi(defaultClient);

ServiceLevelObjectivesApi.GetSLOHistoryOptionalParameters parameters = new ServiceLevelObjectivesApi.GetSLOHistoryOptionalParameters().target(99.9).applyCorrection(false);

SLOHistoryResponse result = apiInstance.getSLOHistory(
    "asdf4567asdf7890, "// Some String SLO ID of type time-slice
    OffsetDateTime.now().plusDays(-7).toInstant().getEpochSecond(),
    OffsetDateTime.now().toInstant().getEpochSecond(),
    parameters
);

Expected behavior

apiInstance.getSLOHistory() should return an object of type SLOHistoryResponse.

This currently works for all SLOs in our environment except SLOs of type time-slice. This remains true even if we remove the .target() and .applyCorrection optional parameters from the query.

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • v2.21.0 of the Java datadog-api-client

Version 1.0.0 is not available in Mavne Central

Describe the bug
It is not possible to fetch the 1.0.0 version of the library from Maven Central.

To Reproduce
Steps to reproduce the behavior:

  1. Create an empty Gradle project
  2. Add the dependency to "com.datadoghq:datadog-api-client:1.0.0" like it is suggested in the documentation
  3. Try to build the project
  4. See that Gradle cannot get the dependency from Maven Central

Expected behavior
It should be possible to get the library from a central repository.

Additional context
Apparently the library is absent in maven central, only beta versions are available. It is either deployed in some other place (checked jcenter, not available either), or the documentation should suggest to use beta versions.

java.lang.NoSuchMethodException: org.glassfish.jersey.message.DeflateEncoder when init v1 API

Describe the bug
Got java.lang.NoSuchMethodException: org.glassfish.jersey.message.DeflateEncoder.() when initializing v1 API
BTW, the error is understandable because the DeflateEncoder class has no default constructor, but I'm probably missing something else a lot of people should have report for the same.

The initialization code is as follows:

// Configure authorization
Map<String, String> secrets = new HashMap<>();
secrets.put("apiKeyAuth", System.getenv("DD_API_KEY"));
secrets.put("appKeyAuth", System.getenv("DD_API_KEY"));
// initialize V1 API
v1Client = com.datadog.api.v1.client.Configuration.getDefaultApiClient().configureApiKeys(secrets);

To Reproduce
It occurs all the time in my application.

Expected behavior
API must be initialized correctly.

Screenshots

Caused by: java.lang.RuntimeException: java.lang.InstantiationException: org.glassfish.jersey.message.DeflateEncoder
	at org.apache.cxf.jaxrs.impl.ConfigurationImpl.createProvider(ConfigurationImpl.java:240)
	at org.apache.cxf.jaxrs.impl.ConfigurationImpl.<init>(ConfigurationImpl.java:66)
	at org.apache.cxf.jaxrs.client.spec.ClientConfigurableImpl.<init>(ClientConfigurableImpl.java:37)
	at org.apache.cxf.jaxrs.client.spec.ClientBuilderImpl.withConfig(ClientBuilderImpl.java:160)
	at com.datadog.api.v1.client.ApiClient.buildHttpClient(ApiClient.java:1521)
	at com.datadog.api.v1.client.ApiClient.<init>(ApiClient.java:321)
	at com.datadog.api.v1.client.ApiClient.<init>(ApiClient.java:311)
	at com.datadog.api.v1.client.Configuration.getDefaultApiClient(Configuration.java:29)
	at com.algosec.shared.issuescenter.client.IssuesCenterClient.<init>(IssuesCenterClient.java:35)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204)
	... 215 common frames omitted
Caused by: java.lang.InstantiationException: org.glassfish.jersey.message.DeflateEncoder
	at java.base/java.lang.Class.newInstance(Class.java:571)
	at org.apache.cxf.jaxrs.impl.ConfigurationImpl.createProvider(ConfigurationImpl.java:238)
	... 228 common frames omitted
Caused by: java.lang.NoSuchMethodException: org.glassfish.jersey.message.DeflateEncoder.<init>()
	at java.base/java.lang.Class.getConstructor0(Class.java:3349)
	at java.base/java.lang.Class.newInstance(Class.java:556)
	... 229 common frames omitted

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • java 11
  • datadog-api-client v1.5.0.

Additional context
Application is deployed in apache tomcat 9.0.54 on linux.

Inclusion of a third-party dependency results in a NPE when creating an Event

Describe the bug
The inclusion of other third-party dependencies can result in the datadog-api-client not functioning.

To Reproduce
Steps to reproduce the behaviour:

  1. Clone https://github.com/scottmuc-cp/datadog-api-client-bug-report
  2. Update line 22 of DataDogExample.java with a real API key (not necessary to replicate the issue but obviously would be necessary to see the expected result)
  3. Run ./gradlew run
 ./gradlew run

> Task :run FAILED
Exception in thread "main" javax.ws.rs.ProcessingException: java.lang.NullPointerException
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.filterRequest(ClientInvocation.java:603)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:440)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:62)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.post(ClientInvocationBuilder.java:219)
        at com.datadog.api.v1.client.ApiClient.sendRequest(ApiClient.java:1456)
        at com.datadog.api.v1.client.ApiClient.invokeAPI(ApiClient.java:1399)
        at com.datadog.api.v1.client.api.EventsApi.createEventWithHttpInfo(EventsApi.java:113)
        at com.datadog.api.v1.client.api.EventsApi.createEvent(EventsApi.java:65)
        at DataDogExample.main(DataDogExample.java:40)
Caused by: java.lang.NullPointerException
        at org.glassfish.jersey.client.filter.EncodingFilter.getSupportedEncodings(EncodingFilter.java:108)
        at org.glassfish.jersey.client.filter.EncodingFilter.filter(EncodingFilter.java:82)
        at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.filterRequest(ClientInvocation.java:590)
        ... 8 more

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> Process 'command '/Users/summer/homebrew/Cellar/openjdk@11/11.0.12/libexec/openjdk.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 6s
2 actionable tasks: 2 executed

Expected behaviour
The printed output of the EventCreateResponse:

class EventCreateResponse {
    alertType: null
    dateHappened: null
    deviceName: null
    host: null
    id: null
    payload: null
    priority: null
    relatedEventId: null
    sourceTypeName: null
    status: ok
    tags: null
    text: null
    title: null
    url: null
}

and the event is visible in the Event Stream.

To see expected behaviour:

  1. Comment out line 12 of build.gradle.
  2. Run ./gradlew run

Environment and Versions (please complete the following information):

  • version 1.4.0 of this project.
  • tested on macOS with openjdk@11

Additional context

The NullPointerException is occurring here.

I don't quite understand why the inclusion of a different library would result in the dependency injection not fulfilling its task.

Below are the different dependencies graphs based on the inclusion of the keycloak dependency:
with_keycloak.dependencies.txt
without_keycloak.dependencies.txt

This feels like it might be related to #1179

javax.ws transitive dependency resolution issue with sbt

Describe the bug
When you reference datadog-api-client as a dependency in a scala sbt project (at least with sbt 1.2.8), you get an issue when it comes to resolve javax.ws.rs:javax.ws.rs-api, pulled by library's explicit dependency org.glassfish.jersey.core:jersey-client.

The problem is caused by sbt and is largely discussed in sbt/sbt#3618.

Amongst all the workarounds mentioned in the thread above, the only one that solved the problem for me was to replace javax.ws.rs:javax.ws.rs-api by jakarta.ws.rs:jakarta.ws.rs-api:

libraryDependencies ++= Seq(
  ...
  "com.datadoghq" % "datadog-api-client" % "1.0.0-beta.6" exclude("javax.ws.rs", "javax.ws.rs-api"),
  "jakarta.ws.rs" % "jakarta.ws.rs-api" % "2.1.2", // see https://github.com/sbt/sbt/issues/3618

Maybe a good way to "workaround" the problem would be to use another high level http client library.

To Reproduce
Steps to reproduce the behavior:

  1. create a scala sbt project
  2. add "com.datadoghq" % "datadog-api-client" % "1.0.0-beta.6" as a dependency
  3. run sbt update
  4. see error:
[warn] 	Detected merged artifact: [FAILED     ] javax.ws.rs#javax.ws.rs-api;2.1!javax.ws.rs-api.${packaging.type}:  (0ms).
[warn] ==== local: tried
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/javax/ws/rs/javax.ws.rs-api/2.1/javax.ws.rs-api-2.1.${packaging.type}
[warn] 	::::::::::::::::::::::::::::::::::::::::::::::
[warn] 	::              FAILED DOWNLOADS            ::
[warn] 	:: ^ see resolution messages for details  ^ ::
[warn] 	::::::::::::::::::::::::::::::::::::::::::::::
[warn] 	:: javax.ws.rs#javax.ws.rs-api;2.1!javax.ws.rs-api.${packaging.type}
[warn] 	::::::::::::::::::::::::::::::::::::::::::::::
[error] sbt.librarymanagement.ResolveException: download failed: javax.ws.rs#javax.ws.rs-api;2.1!javax.ws.rs-api.${packaging.type}
[error] 	at ...
[error] (update) sbt.librarymanagement.ResolveException: download failed: javax.ws.rs#javax.ws.rs-api;2.1!javax.ws.rs-api.${packaging.type}

Expected behavior
No dependency download issue when installing the datadog-api-client library in your project.

Environment and Versions (please complete the following information):
Using com.datadoghq:datadog-api-client:1.0.0-beta.6 (1.0.0-beta.7 is not available in any public repo).

Java 21 and datadog

Describe the bug
I am not sure if this is the correct place to ask this.
But lets see,
I am facing an issue with java 21 and when adding a bean to jettyserver.
checking the stacktrace seems it could be related to datadog and the usage of unsafe,

java.lang.UnsupportedOperationException: Cannot get defined package using reflection: sun.misc.Unsafe
        at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Initializable$Unavailable.getDefinedPackage(ClassInjector.java:479)
        at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.injectRaw(ClassInjector.java:251)
        at datadog.trace.agent.tooling.HelperInjector.injectClassLoader(HelperInjector.java:138)
        at datadog.trace.agent.tooling.HelperInjector.transform(HelperInjector.java:105)
        at datadog.trace.agent.tooling.AdviceStack.transform(AdviceStack.java:31)
        at datadog.trace.agent.tooling.SplittingTransformer.transform(SplittingTransformer.java:28)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doTransform(AgentBuilder.java:12223)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:12160)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.access$1800(AgentBuilder.java:11869)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$Java9CapableVmDispatcher.run(AgentBuilder.java:12647)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$Java9CapableVmDispatcher.run(AgentBuilder.java:12579)
        at java.base/java.security.AccessController.doPrivileged(Unknown Source)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.doPrivileged(AgentBuilder.java)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer.transform(AgentBuilder.java:12103)
        at net.bytebuddy.agent.builder.AgentBuilder$Default$ExecutingTransformer$ByteBuddy$ModuleSupport.transform(Unknown Source)
        at datadog.trace.agent.tooling.bytebuddy.DDJava9ClassFileTransformer.transform(DDJava9ClassFileTransformer.java:60)
        at java.instrument/sun.instrument.TransformerManager.transform(Unknown Source)
        at java.instrument/sun.instrument.InstrumentationImpl.transform(Unknown Source)
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(Unknown Source)
        at java.base/java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(Unknown Source)
        at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(Unknown Source)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(Unknown Source)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        at org.eclipse.jetty.server.HttpChannelListeners$NotifyRequest.<clinit>(HttpChannelListeners.java:219)
        at org.eclipse.jetty.server.HttpChannelListeners.<init>(HttpChannelListeners.java:53)
        at org.eclipse.jetty.server.AbstractConnector$1.beanAdded(AbstractConnector.java:217)
        at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:350)
        at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:320)

To Reproduce
connector = new ServerConnector(_server, _factory);
connector.addBean(new ChannelListener());

class ChannelListener implements HttpChannel.Listener { ... }

I am using JettyServer 11.0.15 on a linux machine, I am initializing the datadog agent with "-javaagent:/usr/lib/jvm/datadog/dd-java-agent.jar"

Provide a shaded jar to avoid dependencies issues

@therve I'm opening this again as a follow up to #893 as this has been incorrectly resolved as a standalone jar without shading, so the problem remains as it does not solve compatibility issues between implementation specific libs used by datadog that could conflict with a project one.

Is your feature request related to a problem? Please describe.

Datadog api client depends on popular third-party libraries that are fast moving and which implementation may conflict with the one of the application it needs to be integrated with. Clashes are often exacerbated by excessive transitive dependencies issues.

Describe the solution you'd like

Provide a shaded/standalone jar that is self contained with no dependencies (except for the api interfaces needed)

Examples:

Describe alternatives you've considered

  • Add a lengthy list of exclusions to the datadog-api-client and hope for the best that the glassfish client and jackson code in use will be compatible with the one used in the application

  • Fork the datadog-api-client code and maintain it to be compatible

None of those solution are adequate for increased adoption of the datadog-api-client library across a wide range of applications and benefit from any improvement of the project in a safe way.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.