> ## Documentation Index
> Fetch the complete documentation index at: https://developers.telnyx.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Java SDK advanced usage

> Logging, ProGuard and R8, Jackson, undocumented API functionality, FAQ, and versioning for the Telnyx Java SDK.

## Logging

The SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor).

Enable logging by setting the `TELNYX_LOG` environment variable to `info`:

```sh theme={null}
$ export TELNYX_LOG=info
```

Or to `debug` for more verbose logging:

```sh theme={null}
$ export TELNYX_LOG=debug
```

## ProGuard and R8

Although the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `telnyx-java-core` is published with a [configuration file](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-core/src/main/resources/META-INF/proguard/telnyx-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).

ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.

## Jackson

The SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.

The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).

If the SDK threw an exception, but you're *certain* the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`TelnyxOkHttpClient`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-client-okhttp/src/main/kotlin/com/telnyx/sdk/client/okhttp/TelnyxOkHttpClient.kt) or [`TelnyxOkHttpClientAsync`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-client-okhttp/src/main/kotlin/com/telnyx/sdk/client/okhttp/TelnyxOkHttpClientAsync.kt).

> \[!CAUTION]
> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.

## Undocumented API functionality

The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.

### Parameters

To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:

```java theme={null}
import com.telnyx.sdk.core.JsonValue;
import com.telnyx.sdk.models.calls.CallDialParams;

CallDialParams params = CallDialParams.builder()
    .putAdditionalHeader("Secret-Header", "42")
    .putAdditionalQueryParam("secret_query_param", "42")
    .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
    .build();
```

These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.

To set undocumented parameters on *nested* headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class:

```java theme={null}
import com.telnyx.sdk.core.JsonValue;
import com.telnyx.sdk.models.calls.CallDialParams;

CallDialParams params = CallDialParams.builder()
    .answeringMachineDetectionConfig(CallDialParams.AnsweringMachineDetectionConfig.builder()
        .putAdditionalProperty("secretProperty", JsonValue.from("42"))
        .build())
    .build();
```

These properties can be accessed on the nested built object later using the `_additionalProperties()` method.

To set a documented parameter or property to an undocumented or not yet supported *value*, pass a [`JsonValue`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-core/src/main/kotlin/com/telnyx/sdk/core/Values.kt) object to its setter:

```java theme={null}
import com.telnyx.sdk.core.JsonValue;
import com.telnyx.sdk.models.calls.CallDialParams;

CallDialParams params = CallDialParams.builder()
    .connectionId(JsonValue.from(42))
    .from("+15557654321")
    .to("+15551234567")
    .webhookUrl("https://your-webhook.url/events")
    .build();
```

The most straightforward way to create a [`JsonValue`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-core/src/main/kotlin/com/telnyx/sdk/core/Values.kt) is using its `from(...)` method:

```java theme={null}
import com.telnyx.sdk.core.JsonValue;
import java.util.List;
import java.util.Map;

// Create primitive JSON values
JsonValue nullValue = JsonValue.from(null);
JsonValue booleanValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("Hello World!");

// Create a JSON array value equivalent to `["Hello", "World"]`
JsonValue arrayValue = JsonValue.from(List.of(
  "Hello", "World"
));

// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`
JsonValue objectValue = JsonValue.from(Map.of(
  "a", 1,
  "b", 2
));

// Create an arbitrarily nested JSON equivalent to:
// {
//   "a": [1, 2],
//   "b": [3, 4]
// }
JsonValue complexValue = JsonValue.from(Map.of(
  "a", List.of(
    1, 2
  ),
  "b", List.of(
    3, 4
  )
));
```

Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.

To forcibly omit a required parameter or property, pass [`JsonMissing`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-core/src/main/kotlin/com/telnyx/sdk/core/Values.kt):

```java theme={null}
import com.telnyx.sdk.core.JsonMissing;
import com.telnyx.sdk.models.calls.CallDialParams;

CallDialParams params = CallDialParams.builder()
    .from("+18005550101")
    .to("+18005550100 or sip:username@sip.telnyx.com")
    .connectionId(JsonMissing.of())
    .build();
```

### Response properties

To access undocumented response properties, call the `_additionalProperties()` method:

```java theme={null}
import com.telnyx.sdk.core.JsonValue;
import java.util.Map;

Map<String, JsonValue> additionalProperties = client.calls().dial(params)._additionalProperties();
JsonValue secretPropertyValue = additionalProperties.get("secretProperty");

String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {
    @Override
    public String visitNull() {
        return "It's null!";
    }

    @Override
    public String visitBoolean(boolean value) {
        return "It's a boolean!";
    }

    @Override
    public String visitNumber(Number value) {
        return "It's a number!";
    }

    // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`
    // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden
});
```

To access a property's raw JSON value, which may be undocumented, call its `_` prefixed method:

```java theme={null}
import com.telnyx.sdk.core.JsonField;
import java.util.Optional;

JsonField<String> connectionId = client.calls().dial(params)._connectionId();

if (connectionId.isMissing()) {
  // The property is absent from the JSON response
} else if (connectionId.isNull()) {
  // The property was set to literal null
} else {
  // Check if value was provided as a string
  // Other methods include `asNumber()`, `asBoolean()`, etc.
  Optional<String> jsonString = connectionId.asString();

  // Try to deserialize into a custom type
  MyClass myObject = connectionId.asUnknown().orElseThrow().convert(MyClass.class);
}
```

### Response validation

In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.

By default, the SDK will not throw an exception in this case. It will throw [`TelnyxInvalidDataException`](https://github.com/team-telnyx/telnyx-java/tree/master/telnyx-java-core/src/main/kotlin/com/telnyx/sdk/errors/TelnyxInvalidDataException.kt) only if you directly access the property.

If you would prefer to check that the response is completely well-typed upfront, then either call `validate()`:

```java theme={null}
import com.telnyx.sdk.models.calls.CallDialResponse;

CallDialResponse response = client.calls().dial(params).validate();
```

Or configure the method call to validate the response using the `responseValidation` method:

```java theme={null}
import com.telnyx.sdk.models.calls.CallDialResponse;

CallDialResponse response = client.calls().dial(
  params, RequestOptions.builder().responseValidation(true).build()
);
```

Or configure the default for all method calls at the client level:

```java theme={null}
import com.telnyx.sdk.client.TelnyxClient;
import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient;

TelnyxClient client = TelnyxOkHttpClient.builder()
    .fromEnv()
    .responseValidation(true)
    .build();
```

## FAQ

### Why don't you use plain `enum` classes?

Java `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.

### Why do you represent fields using `JsonField<T>` instead of just plain `T`?

Using `JsonField<T>` enables a few features:

* Allowing usage of [undocumented API functionality](#undocumented-api-functionality)
* Lazily [validating the API response against the expected shape](#response-validation)
* Representing absent vs explicitly null values

### Why don't you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?

It is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don't want to introduce a breaking change every time we add a field to a class.

### Why don't you use checked exceptions?

Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.

Checked exceptions:

* Are verbose to handle
* Encourage error handling at the wrong level of abstraction, where nothing can be done about the error
* Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)
* Don't play well with lambdas (also due to the function coloring problem)

## Semantic versioning

This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:

1. Changes to library internals which are technically public but not intended or documented for external use. *(Please open a GitHub issue to let us know if you are relying on such internals.)*
2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an [issue](https://www.github.com/team-telnyx/telnyx-java/issues) with questions, bugs, or suggestions.
