Skip to content

gleanwork/api-client-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

91 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

api-client-java

The Glean Java SDK provides convenient access to the Glean REST API for Java 8+. It includes POJOs for all API models, fluent builders for requests, and supports both synchronous and asynchronous execution using standard HTTP clients.

Unified SDK Architecture

This SDK combines both the Client and Indexing API namespaces into a single unified package:

  • Client API: Used for search, retrieval, and end-user interactions with Glean content
  • Indexing API: Used for indexing content, permissions, and other administrative operations

Each namespace has its own authentication requirements and access patterns. While they serve different purposes, having them in a single SDK provides a consistent developer experience across all Glean API interactions.

// Example of accessing Client namespace
Glean glean = Glean.builder()
        .apiToken("client-token")
        .instance("instance-name")
        .build();
glean.client().search().query()
        .searchRequest(SearchRequest.builder().query("search term").build())
        .call();

// Example of accessing Indexing namespace 
Glean glean = Glean.builder()
        .apiToken("indexing-token")
        .instance("instance-name")
        .build();
glean.indexing().documents().index()
        .request(DocumentBulkIndexRequest.builder() /* document data */ .build())
        .call();

Remember that each namespace requires its own authentication token type as described in the Authentication Methods section.

Table of Contents

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.glean.api-client:glean-api-client:0.10.0'

Maven:

<dependency>
    <groupId>com.glean.api-client</groupId>
    <artifactId>glean-api-client</artifactId>
    <version>0.10.0</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example 1

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ChatResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

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

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        ChatResponse res = sdk.client().chat().create()
                .chatRequest(ChatRequest.builder()
                    .messages(List.of(
                        ChatMessage.builder()
                            .fragments(List.of(
                                ChatMessageFragment.builder()
                                    .text("What are the company holidays this year?")
                                    .build()))
                            .build()))
                    .build())
                .call();

        if (res.chatResponse().isPresent()) {
            // handle response
        }
    }
}

Example 2

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ChatStreamResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

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

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        ChatStreamResponse res = sdk.client().chat().createStream()
                .chatRequest(ChatRequest.builder()
                    .messages(List.of(
                        ChatMessage.builder()
                            .fragments(List.of(
                                ChatMessageFragment.builder()
                                    .text("What are the company holidays this year?")
                                    .build()))
                            .build()))
                    .build())
                .call();

        if (res.chatRequestStream().isPresent()) {
            // handle response
        }
    }
}

Asynchronous Call

An asynchronous SDK client is also available that returns a CompletableFuture<T>. See Asynchronous Support for more details on async benefits and reactive library integration.

package hello.world;

import com.glean.api_client.glean_api_client.AsyncGlean;
import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.async.ActivityResponse;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Application {

    public static void main(String[] args) {

        AsyncGlean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build()
            .async();

        Activity req = Activity.builder()
                .events(List.of(
                    ActivityEvent.builder()
                        .action(ActivityEventAction.HISTORICAL_VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.SEARCH)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/search?q=query")
                        .params(ActivityEventParams.builder()
                            .query("query")
                            .build())
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .params(ActivityEventParams.builder()
                            .duration(20L)
                            .referrer("https://example.com/document")
                            .build())
                        .build()))
                .build();

        CompletableFuture<ActivityResponse> resFut = sdk.client().activity().report()
                .request(req)
                .call();

        // handle response
    }
}

Asynchronous Support

The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.

Why Use Async?

Asynchronous operations provide several key benefits:

  • Non-blocking I/O: Your threads stay free for other work while operations are in flight
  • Better resource utilization: Handle more concurrent operations with fewer threads
  • Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
  • Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration

The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.

Why Reactive Streams over JDK Flow?

  • Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
  • Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
  • Better interoperability: Seamless integration without additional adapters for most use cases

Integration with Popular Libraries:

  • Project Reactor: Use Flux.from(publisher) to convert to Reactor types
  • RxJava: Use Flowable.fromPublisher(publisher) for RxJava integration
  • Akka Streams: Use Source.fromPublisher(publisher) for Akka Streams integration
  • Vert.x: Use ReadStream.fromPublisher(vertx, publisher) for Vert.x reactive streams
  • Mutiny: Use Multi.createFrom().publisher(publisher) for Quarkus Mutiny integration

For JDK Flow API Integration: If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:

// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);

// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);

For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.

Supported Operations

Async support is available for:

  • Server-sent Events: Stream real-time events with Reactive Streams Publisher<T>
  • JSONL Streaming: Process streaming JSON lines asynchronously
  • Pagination: Iterate through paginated results using callAsPublisher() and callAsPublisherUnwrapped()
  • File Uploads: Upload files asynchronously with progress tracking
  • File Downloads: Download files asynchronously with streaming support
  • Standard Operations: All regular API calls return CompletableFuture<T> for async execution

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
apiToken http HTTP Bearer GLEAN_API_TOKEN

To authenticate with the API the apiToken parameter must be set when initializing the SDK client instance. For example:

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ActivityResponse;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.util.List;

public class Application {

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

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        Activity req = Activity.builder()
                .events(List.of(
                    ActivityEvent.builder()
                        .action(ActivityEventAction.HISTORICAL_VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.SEARCH)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/search?q=query")
                        .params(ActivityEventParams.builder()
                            .query("query")
                            .build())
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .params(ActivityEventParams.builder()
                            .duration(20L)
                            .referrer("https://example.com/document")
                            .build())
                        .build()))
                .build();

        ActivityResponse res = sdk.client().activity().report()
                .request(req)
                .call();

        // handle response
    }
}

Authentication Methods

Glean supports different authentication methods depending on which API namespace you're using:

Client Namespace

The Client namespace supports two authentication methods:

  1. Manually Provisioned API Tokens

    • Can be created by an Admin or a user with the API Token Creator role
    • Used for server-to-server integrations
  2. OAuth

    • Requires OAuth setup to be completed by an Admin
    • Used for user-based authentication flows

Indexing Namespace

The Indexing namespace supports only one authentication method:

  1. Manually Provisioned API Tokens
    • Can be created by an Admin or a user with the API Token Creator role
    • Used for secure document indexing operations

Important

Client tokens will not work for Indexing operations, and Indexing tokens will not work for Client operations. You must use the appropriate token type for the namespace you're accessing.

For more information on obtaining the appropriate token type, please contact your Glean administrator.

Available Resources and Operations

Available methods
  • retrieve - Retrieve an agent
  • retrieveSchemas - List an agent's schemas
  • list - Search agents
  • runStream - Create an agent run and stream the response
  • run - Create an agent run and wait for the response
  • retrieve - Gets specified policy
  • update - Updates an existing policy
  • list - Lists policies
  • create - Creates new policy
  • download - Downloads violations CSV for policy
  • create - Creates new one-time report
  • download - Downloads violations CSV for report
  • status - Fetches report run status
  • list - Fetches documents visibility
  • create - Hide or unhide docs
  • list - List available tools
  • run - Execute the specified tool
  • status - Beta: Get datasource status
  • addOrUpdate - Index document

  • index - Index documents

  • bulkIndex - Bulk index documents

  • processAll - Schedules the processing of uploaded documents

  • delete - Delete document

  • debug - Beta: Get document information

  • debugMany - Beta: Get information of a batch of documents

  • checkAccess - Check document access

  • status - Get document upload and indexing status ⚠️ Deprecated

  • count - Get document count ⚠️ Deprecated

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

By default, an API error will throw a models/errors/APIException exception. When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the create method throws the following exceptions:

Error Type Status Code Content Type
models/errors/CollectionError 422 application/json
models/errors/APIException 4XX, 5XX */*

Example

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.errors.CollectionError;
import com.glean.api_client.glean_api_client.models.operations.CreatecollectionResponse;
import java.lang.Exception;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;

public class Application {

    public static void main(String[] args) throws CollectionError, Exception {

        Glean sdk = Glean.builder()
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        CreateCollectionRequest req = CreateCollectionRequest.builder()
                .name("<value>")
                .addedRoles(List.of(
                    UserRoleSpecification.builder()
                        .role(UserRole.VERIFIER)
                        .person(Person.builder()
                            .name("George Clooney")
                            .obfuscatedId("abc123")
                            .relatedDocuments(List.of(
                                RelatedDocuments.builder()
                                    .querySuggestion(QuerySuggestion.builder()
                                        .query("app:github type:pull author:mortimer")
                                        .searchProviderInfo(SearchProviderInfo.builder()
                                            .name("Google")
                                            .searchLinkUrlTemplate("https://www.google.com/search?q={query}&hl=en")
                                            .build())
                                        .label("Mortimer's PRs")
                                        .datasource("github")
                                        .requestOptions(SearchRequestOptions.builder()
                                            .facetBucketSize(977077L)
                                            .datasourceFilter("JIRA")
                                            .datasourcesFilter(List.of(
                                                "JIRA"))
                                            .queryOverridesFacetFilters(true)
                                            .facetFilters(List.of(
                                                FacetFilter.builder()
                                                    .fieldName("type")
                                                    .values(List.of(
                                                        FacetFilterValue.builder()
                                                            .value("Spreadsheet")
                                                            .relationType(RelationType.EQUALS)
                                                            .build(),
                                                        FacetFilterValue.builder()
                                                            .value("Presentation")
                                                            .relationType(RelationType.EQUALS)
                                                            .build()))
                                                    .build()))
                                            .facetFilterSets(List.of(
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build(),
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build(),
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build()))
                                            .authTokens(List.of(
                                                AuthToken.builder()
                                                    .accessToken("123abc")
                                                    .datasource("gmail")
                                                    .scope("email profile https://www.googleapis.com/auth/gmail.readonly")
                                                    .tokenType("Bearer")
                                                    .authUser("1")
                                                    .build()))
                                            .build())
                                        .ranges(List.of(
                                            TextRange.builder()
                                                .startIndex(86650L)
                                                .document(Document.builder()
                                                    .metadata(DocumentMetadata.builder()
                                                        .datasource("datasource")
                                                        .objectType("Feature Request")
                                                        .container("container")
                                                        .parentId("JIRA_EN-1337")
                                                        .mimeType("mimeType")
                                                        .documentId("documentId")
                                                        .createTime(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                                                        .updateTime(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                                                        .components(List.of(
                                                            "Backend",
                                                            "Networking"))
                                                        .status("[\"Done\"]")
                                                        .pins(List.of(
                                                            PinDocument.builder()
                                                                .documentId("<id>")
                                                                .audienceFilters(List.of(
                                                                    FacetFilter.builder()
                                                                        .fieldName("type")
                                                                        .values(List.of(
                                                                            FacetFilterValue.builder()
                                                                                .value("Spreadsheet")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build(),
                                                                            FacetFilterValue.builder()
                                                                                .value("Presentation")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build()))
                                                                        .build()))
                                                                .build()))
                                                        .collections(List.of(
                                                            Collection.builder()
                                                                .name("<value>")
                                                                .description("meaty dial elegantly while react")
                                                                .id(854591L)
                                                                .audienceFilters(List.of(
                                                                    FacetFilter.builder()
                                                                        .fieldName("type")
                                                                        .values(List.of(
                                                                            FacetFilterValue.builder()
                                                                                .value("Spreadsheet")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build(),
                                                                            FacetFilterValue.builder()
                                                                                .value("Presentation")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build()))
                                                                        .build()))
                                                                .items(List.of(
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build(),
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build(),
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build()))
                                                                .build()))
                                                        .interactions(DocumentInteractions.builder()
                                                            .reacts(List.of(
                                                                Reaction.builder()
                                                                    .build(),
                                                                Reaction.builder()
                                                                    .build()))
                                                            .shares(List.of(
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build(),
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build(),
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build()))
                                                            .build())
                                                        .verification(Verification.builder()
                                                            .state(State.DEPRECATED)
                                                            .metadata(VerificationMetadata.builder()
                                                                .reminders(List.of(
                                                                    Reminder.builder()
                                                                        .assignee(Person.builder()
                                                                            .name("George Clooney")
                                                                            .obfuscatedId("abc123")
                                                                            .build())
                                                                        .remindAt(268615L)
                                                                        .build()))
                                                                .lastReminder(Reminder.builder()
                                                                    .assignee(Person.builder()
                                                                        .name("George Clooney")
                                                                        .obfuscatedId("abc123")
                                                                        .build())
                                                                    .remindAt(423482L)
                                                                    .build())
                                                                .build())
                                                            .build())
                                                        .shortcuts(List.of(
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build(),
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build(),
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build()))
                                                        .customData(Map.ofEntries(
                                                            Map.entry("someCustomField", CustomDataValue.builder()
                                                                .build())))
                                                        .build())
                                                    .build())
                                                .build()))
                                        .inputDetails(SearchRequestInputDetails.builder()
                                            .hasCopyPaste(true)
                                            .build())
                                        .build())
                                    .results(List.of(
                                        SearchResult.builder()
                                            .url("https://example.com/foo/bar")
                                            .title("title")
                                            .nativeAppUrl("slack://foo/bar")
                                            .snippets(List.of(
                                                SearchResultSnippet.builder()
                                                    .snippet("snippet")
                                                    .mimeType("mimeType")
                                                    .build()))
                                            .build()))
                                    .build(),
                                RelatedDocuments.builder()
                                    .querySuggestion(QuerySuggestion.builder()
                                        .query("app:github type:pull author:mortimer")
                                        .searchProviderInfo(SearchProviderInfo.builder()
                                            .name("Google")
                                            .searchLinkUrlTemplate("https://www.google.com/search?q={query}&hl=en")
                                            .build())
                                        .label("Mortimer's PRs")
                                        .datasource("github")
                                        .requestOptions(SearchRequestOptions.builder()
                                            .facetBucketSize(977077L)
                                            .datasourceFilter("JIRA")
                                            .datasourcesFilter(List.of(
                                                "JIRA"))
                                            .queryOverridesFacetFilters(true)
                                            .facetFilters(List.of(
                                                FacetFilter.builder()
                                                    .fieldName("type")
                                                    .values(List.of(
                                                        FacetFilterValue.builder()
                                                            .value("Spreadsheet")
                                                            .relationType(RelationType.EQUALS)
                                                            .build(),
                                                        FacetFilterValue.builder()
                                                            .value("Presentation")
                                                            .relationType(RelationType.EQUALS)
                                                            .build()))
                                                    .build()))
                                            .facetFilterSets(List.of(
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build(),
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build(),
                                                FacetFilterSet.builder()
                                                    .filters(List.of(
                                                        FacetFilter.builder()
                                                            .fieldName("type")
                                                            .values(List.of(
                                                                FacetFilterValue.builder()
                                                                    .value("Spreadsheet")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build(),
                                                                FacetFilterValue.builder()
                                                                    .value("Presentation")
                                                                    .relationType(RelationType.EQUALS)
                                                                    .build()))
                                                            .build()))
                                                    .build()))
                                            .authTokens(List.of(
                                                AuthToken.builder()
                                                    .accessToken("123abc")
                                                    .datasource("gmail")
                                                    .scope("email profile https://www.googleapis.com/auth/gmail.readonly")
                                                    .tokenType("Bearer")
                                                    .authUser("1")
                                                    .build()))
                                            .build())
                                        .ranges(List.of(
                                            TextRange.builder()
                                                .startIndex(86650L)
                                                .document(Document.builder()
                                                    .metadata(DocumentMetadata.builder()
                                                        .datasource("datasource")
                                                        .objectType("Feature Request")
                                                        .container("container")
                                                        .parentId("JIRA_EN-1337")
                                                        .mimeType("mimeType")
                                                        .documentId("documentId")
                                                        .createTime(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                                                        .updateTime(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                                                        .components(List.of(
                                                            "Backend",
                                                            "Networking"))
                                                        .status("[\"Done\"]")
                                                        .pins(List.of(
                                                            PinDocument.builder()
                                                                .documentId("<id>")
                                                                .audienceFilters(List.of(
                                                                    FacetFilter.builder()
                                                                        .fieldName("type")
                                                                        .values(List.of(
                                                                            FacetFilterValue.builder()
                                                                                .value("Spreadsheet")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build(),
                                                                            FacetFilterValue.builder()
                                                                                .value("Presentation")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build()))
                                                                        .build()))
                                                                .build()))
                                                        .collections(List.of(
                                                            Collection.builder()
                                                                .name("<value>")
                                                                .description("meaty dial elegantly while react")
                                                                .id(854591L)
                                                                .audienceFilters(List.of(
                                                                    FacetFilter.builder()
                                                                        .fieldName("type")
                                                                        .values(List.of(
                                                                            FacetFilterValue.builder()
                                                                                .value("Spreadsheet")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build(),
                                                                            FacetFilterValue.builder()
                                                                                .value("Presentation")
                                                                                .relationType(RelationType.EQUALS)
                                                                                .build()))
                                                                        .build()))
                                                                .items(List.of(
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build(),
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build(),
                                                                    CollectionItem.builder()
                                                                        .collectionId(697663L)
                                                                        .itemType(CollectionItemItemType.TEXT)
                                                                        .shortcut(Shortcut.builder()
                                                                            .inputAlias("<value>")
                                                                            .build())
                                                                        .build()))
                                                                .build()))
                                                        .interactions(DocumentInteractions.builder()
                                                            .reacts(List.of(
                                                                Reaction.builder()
                                                                    .build(),
                                                                Reaction.builder()
                                                                    .build()))
                                                            .shares(List.of(
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build(),
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build(),
                                                                Share.builder()
                                                                    .numDaysAgo(365776L)
                                                                    .build()))
                                                            .build())
                                                        .verification(Verification.builder()
                                                            .state(State.DEPRECATED)
                                                            .metadata(VerificationMetadata.builder()
                                                                .reminders(List.of(
                                                                    Reminder.builder()
                                                                        .assignee(Person.builder()
                                                                            .name("George Clooney")
                                                                            .obfuscatedId("abc123")
                                                                            .build())
                                                                        .remindAt(268615L)
                                                                        .build()))
                                                                .lastReminder(Reminder.builder()
                                                                    .assignee(Person.builder()
                                                                        .name("George Clooney")
                                                                        .obfuscatedId("abc123")
                                                                        .build())
                                                                    .remindAt(423482L)
                                                                    .build())
                                                                .build())
                                                            .build())
                                                        .shortcuts(List.of(
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build(),
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build(),
                                                            Shortcut.builder()
                                                                .inputAlias("<value>")
                                                                .build()))
                                                        .customData(Map.ofEntries(
                                                            Map.entry("someCustomField", CustomDataValue.builder()
                                                                .build())))
                                                        .build())
                                                    .build())
                                                .build()))
                                        .inputDetails(SearchRequestInputDetails.builder()
                                            .hasCopyPaste(true)
                                            .build())
                                        .build())
                                    .results(List.of(
                                        SearchResult.builder()
                                            .url("https://example.com/foo/bar")
                                            .title("title")
                                            .nativeAppUrl("slack://foo/bar")
                                            .snippets(List.of(
                                                SearchResultSnippet.builder()
                                                    .snippet("snippet")
                                                    .mimeType("mimeType")
                                                    .build()))
                                            .build()))
                                    .build()))
                            .metadata(PersonMetadata.builder()
                                .type(PersonMetadataType.FULL_TIME)
                                .title("Actor")
                                .department("Movies")
                                .email("[email protected]")
                                .location("Hollywood, CA")
                                .phone("6505551234")
                                .photoUrl("https://example.com/george.jpg")
                                .startDate(LocalDate.parse("2000-01-23"))
                                .datasourceProfile(List.of(
                                    DatasourceProfile.builder()
                                        .datasource("github")
                                        .handle("<value>")
                                        .build(),
                                    DatasourceProfile.builder()
                                        .datasource("github")
                                        .handle("<value>")
                                        .build()))
                                .querySuggestions(QuerySuggestionList.builder()
                                    .suggestions(List.of(
                                        QuerySuggestion.builder()
                                            .query("app:github type:pull author:mortimer")
                                            .label("Mortimer's PRs")
                                            .datasource("github")
                                            .build()))
                                    .build())
                                .inviteInfo(InviteInfo.builder()
                                    .invites(List.of(
                                        ChannelInviteInfo.builder()
                                            .build(),
                                        ChannelInviteInfo.builder()
                                            .build()))
                                    .build())
                                .customFields(List.of(
                                    CustomFieldData.builder()
                                        .label("<value>")
                                        .values(List.of(
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build()),
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build()),
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build())))
                                        .build(),
                                    CustomFieldData.builder()
                                        .label("<value>")
                                        .values(List.of(
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build()),
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build()),
                                            CustomFieldValue.of(CustomFieldValueStr.builder()
                                                .build())))
                                        .build()))
                                .badges(List.of(
                                    Badge.builder()
                                        .key("deployment_name_new_hire")
                                        .displayName("New hire")
                                        .iconConfig(IconConfig.builder()
                                            .color("#343CED")
                                            .key("person_icon")
                                            .iconType(IconType.GLYPH)
                                            .name("user")
                                            .build())
                                        .build()))
                                .build())
                            .build())
                        .build()))
                .removedRoles(List.of(
                    UserRoleSpecification.builder()
                        .role(UserRole.VIEWER)
                        .person(Person.builder()
                            .name("George Clooney")
                            .obfuscatedId("abc123")
                            .metadata(PersonMetadata.builder()
                                .type(PersonMetadataType.FULL_TIME)
                                .title("Actor")
                                .department("Movies")
                                .email("[email protected]")
                                .location("Hollywood, CA")
                                .phone("6505551234")
                                .photoUrl("https://example.com/george.jpg")
                                .startDate(LocalDate.parse("2000-01-23"))
                                .datasourceProfile(List.of(
                                    DatasourceProfile.builder()
                                        .datasource("github")
                                        .handle("<value>")
                                        .build(),
                                    DatasourceProfile.builder()
                                        .datasource("github")
                                        .handle("<value>")
                                        .build()))
                                .querySuggestions(QuerySuggestionList.builder()
                                    .suggestions(List.of(
                                        QuerySuggestion.builder()
                                            .query("app:github type:pull author:mortimer")
                                            .label("Mortimer's PRs")
                                            .datasource("github")
                                            .build()))
                                    .build())
                                .inviteInfo(InviteInfo.builder()
                                    .invites(List.of(
                                        ChannelInviteInfo.builder()
                                            .build(),
                                        ChannelInviteInfo.builder()
                                            .build()))
                                    .build())
                                .badges(List.of(
                                    Badge.builder()
                                        .key("deployment_name_new_hire")
                                        .displayName("New hire")
                                        .iconConfig(IconConfig.builder()
                                            .color("#343CED")
                                            .key("person_icon")
                                            .iconType(IconType.GLYPH)
                                            .name("user")
                                            .build())
                                        .build()))
                                .build())
                            .build())
                        .build()))
                .audienceFilters(List.of(
                    FacetFilter.builder()
                        .fieldName("type")
                        .values(List.of(
                            FacetFilterValue.builder()
                                .value("Spreadsheet")
                                .relationType(RelationType.EQUALS)
                                .build(),
                            FacetFilterValue.builder()
                                .value("Presentation")
                                .relationType(RelationType.EQUALS)
                                .build()))
                        .build()))
                .build();

        CreatecollectionResponse res = sdk.client().collections().create()
                .request(req)
                .call();

        if (res.oneOf().isPresent()) {
            // handle response
        }
    }
}

Server Selection

Server Variables

The default server https://{instance}-be.glean.com contains variables and is set to https://instance-name-be.glean.com by default. To override default values, the following builder methods are available when initializing the SDK client instance:

Variable BuilderMethod Default Description
instance instance(String instance) "instance-name" The instance name (typically the email domain without the TLD) that determines the deployment backend.

Example

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ActivityResponse;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.util.List;

public class Application {

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

        Glean sdk = Glean.builder()
                .instance("<value>")
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        Activity req = Activity.builder()
                .events(List.of(
                    ActivityEvent.builder()
                        .action(ActivityEventAction.HISTORICAL_VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.SEARCH)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/search?q=query")
                        .params(ActivityEventParams.builder()
                            .query("query")
                            .build())
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .params(ActivityEventParams.builder()
                            .duration(20L)
                            .referrer("https://example.com/document")
                            .build())
                        .build()))
                .build();

        ActivityResponse res = sdk.client().activity().report()
                .request(req)
                .call();

        // handle response
    }
}

Override Server URL Per-Client

The default server can be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.glean.api_client.glean_api_client.Glean;
import com.glean.api_client.glean_api_client.models.components.*;
import com.glean.api_client.glean_api_client.models.operations.ActivityResponse;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.util.List;

public class Application {

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

        Glean sdk = Glean.builder()
                .serverURL("https://instance-name-be.glean.com")
                .apiToken(System.getenv().getOrDefault("GLEAN_API_TOKEN", ""))
            .build();

        Activity req = Activity.builder()
                .events(List.of(
                    ActivityEvent.builder()
                        .action(ActivityEventAction.HISTORICAL_VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.SEARCH)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/search?q=query")
                        .params(ActivityEventParams.builder()
                            .query("query")
                            .build())
                        .build(),
                    ActivityEvent.builder()
                        .action(ActivityEventAction.VIEW)
                        .timestamp(OffsetDateTime.parse("2000-01-23T04:56:07.000Z"))
                        .url("https://example.com/")
                        .params(ActivityEventParams.builder()
                            .duration(20L)
                            .referrer("https://example.com/document")
                            .build())
                        .build()))
                .build();

        ActivityResponse res = sdk.client().activity().report()
                .request(req)
                .call();

        // handle response
    }
}

Debugging

Debug

You can setup your SDK to emit debug logs for SDK requests and responses.

For request and response logging (especially json bodies), call enableHTTPDebugLogging(boolean) on the SDK builder like so:

SDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This should only used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

NOTE: This is a convenience method that calls HTTPClient.enableDebugLogging(). The SpeakeasyHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

The official Java library for the Glean API

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 5

Languages