Google provides a Java client library for interacting with the Ad Manager API.
We recommend using the client library with Apache Maven or Gradle.

To get started, create a new project in the IDE of your choice or add the
dependency to an existing project. Google publishes client library artifacts to
the Maven central repository as
[`com.google.api-ads/ad-manager`](https://central.sonatype.com/artifact/com.google.api-ads/ad-manager).

### Maven

```xml
<!-- pom.xml -->
<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>ad-manager</artifactId>
  <version>0.61.0</version>
</dependency>
```

### Gradle

```groovy
implementation 'com.google.api-ads:ad-manager:0.61.0'
```

## Configure credentials

The Java client library uses OAuth2 and [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
(ADC) to authenticate.

ADC searches for credentials in order in the following locations:

1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
2. User credentials set up through the Google Cloud CLI (gcloud CLI).
3. When running on Google Cloud, the service account attached to the Google Cloud resource.

For creating and configuring your ADC credentials, see
[Authentication](https://developers.google.com/ad-manager/api/beta/authentication.md.txt).

## Make your first request

Each service has a `ServiceClient` object with both synchronous and asynchronous
methods for each REST method. The following example reads a [`Network`](https://developers.google.com/ad-manager/api/beta/reference/rest/v1/networks.md.txt)
synchronously.

```java
import com.google.ads.admanager.v1.GetNetworkRequest;
import com.google.ads.admanager.v1.Network;
import com.google.ads.admanager.v1.NetworkName;
import com.google.ads.admanager.v1.NetworkServiceClient;

public class SyncGetNetwork {

  public static void main(String[] args) throws Exception {
    syncGetNetwork();
  }

  public static void syncGetNetwork() throws Exception {
    try (NetworkServiceClient networkServiceClient = NetworkServiceClient.create()) {
      GetNetworkRequest request =
          GetNetworkRequest.newBuilder()
              .setName(NetworkName.of("[NETWORK_CODE]").toString())
              .build();
      Network response = networkServiceClient.getNetwork(request);
    }
  }
}
```

For examples of other methods and resources, see the GitHub repository
[`googleapis/google-cloud-java`](https://github.com/googleapis/google-cloud-java/tree/main/java-admanager/samples/snippets/generated/com/google/ads/admanager/v1).

## Log HTTP requests and responses

The `com.google.api.client.http.HttpTransport` class makes all HTTP requests.
This class uses
[`java.util.logging`](https://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html)
(JUL) for logging HTTP request and response details, including URL, headers, and
content.

To enable logging, set the logger for this class to a log level of
`CONFIG` or higher. The steps for this differ depending on which logging
implementation you use.

### JUL

To enable logging, set `com.google.api.client.http.level` to `CONFIG` or
higher in your `logging.properties` file.

    handlers=java.util.logging.ConsoleHandler
    com.google.api.client.http.level=CONFIG
    java.util.logging.ConsoleHandler.level=CONFIG

Alternatively, you can enable logging in your Java code.

```java

import com.google.api.client.http.HttpTransport;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public static void enableLogging() {
  Logger logger = Logger.getLogger(HttpTransport.class.getName());
  logger.setLevel(Level.CONFIG);
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.CONFIG);
  logger.addHandler(handler);
}
```

### Log4j

If you use Log4j for logging, you can use the
[Log4j JDK Logging Adapter](https://logging.apache.org/log4j/2.x/log4j-jul.html)
to log JUL messages. This can be configured through a `SystemProperty` or by
using the `Log4jBridgeHandler` and a JUL `logging.properties` file.

### System Property

    -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager

### Log4j Bridge Handler

    handlers = org.apache.logging.log4j.jul.Log4jBridgeHandler
    org.apache.logging.log4j.jul.Log4jBridgeHandler.propagateLevels = true

These settings write Ad Manager API logs to any Logger with a level of
`CONFIG` or higher. The following example `log4j2.xml` file configures a
Logger that writes to `System.out`.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="com.google.api.client.http.HttpTransport" level="debug">
      <AppenderRef ref="Console"/>
    </Logger>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>
```

## Handle errors

All Ad Manager API errors are subclasses of
[ApiException](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ApiException)
in the Java client library.

The `ApiException.getReason()` method returns a string that uniquely identifies
error types. Use this to determine how to handle the error.

All errors except `404 Not Found` and `401 Unauthorized` contain [`ErrorDetails`](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ErrorDetails)
with additional information. For `400 Bad Request` errors, `ErrorDetails`
contains a [`BadRequest`](https://cloud.google.com/java/docs/reference/proto-google-common-protos/latest/com.google.rpc.BadRequest)
object with a list of
[`FieldViolations`](https://cloud.google.com/java/docs/reference/proto-google-common-protos/latest/com.google.rpc.BadRequest.FieldViolation).

```java
try {
  // ...
} catch (ApiException apiException) {
  // HTTP status code enum
  com.google.api.gax.rpc.StatusCode statusCode = apiException.getStatusCode();

  // Unique identifier for the type of error
  String errorCode = apiException.getReason();

  // Human readable error message
  String errorMessage = apiException.getMessage();

  // Additional information is available in ErrorDetails.
  ErrorDetails errorDetails = apiException.getErrorDetails();
  if (errorDetails != null) {
    // Additional information for 400 Bad Request errors
    if (errorDetails.getBadRequest() != null) {
      // List of field violations
      List<BadRequest.FieldViolation> fieldViolations =
          errorDetails.getBadRequest().getFieldViolationsList();
    }
  }
}
```

Ad Manager API errors also include a unique `request_id` you can
provide to [support](https://developers.google.com/ad-manager/api/beta/support) for assistance with
troubleshooting. The following example extracts the
`request_id`.

```java
ErrorDetails errorDetails = apiException.getErrorDetails();
if (errorDetails != null && errorDetails.getRequestInfo() != null) {
  // Unique request identifier.
  String requestId = errorDetails.getRequestInfo().getRequestId();
}
```

## Construct resource names

The client library provides helper classes for building resource names from
IDs.

```java
import com.google.ads.admanager.v1.OrderName;

// ...

//  Constructs a String in the format:
//  "networks/{networkCode}/orders/{orderId}"
OrderName.of("123", "789");
```

## Configure proxy settings

The Java client library respects both `http.proxyHost` and `https.proxyHost`
System Property settings. For more details on these settings, see
[Java networking and Proxies](https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html).