Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 27 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,25 @@

<!-- x-release-please-end -->

The Onebusaway SDK Java SDK provides convenient access to the Onebusaway SDK REST API from applications written in Java. It includes helper classes with helpful types and documentation for every request and response property.
The Onebusaway SDK Java SDK provides convenient access to the Onebusaway SDK REST API from applications written in Java.

The Onebusaway SDK Java SDK is similar to the Onebusaway SDK Kotlin SDK but with minor differences that make it more ergonomic for use in Java, such as `Optional` instead of nullable values, `Stream` instead of `Sequence`, and `CompletableFuture` instead of suspend functions.

It is generated with [Stainless](https://www.stainlessapi.com/).

## Documentation
The REST API documentation can be found on [developer.onebusaway.org](https://developer.onebusaway.org).

The REST API documentation can be found on [developer.onebusaway.org](https://developer.onebusaway.org).

---

## Getting started

### Install dependencies

#### Gradle
## Installation

<!-- x-release-please-start-version -->

### Gradle

```kotlin
implementation("org.onebusaway:onebusaway-sdk-java:0.1.0-alpha.23")
```

#### Maven
### Maven

```xml
<dependency>
Expand All @@ -42,6 +36,12 @@ implementation("org.onebusaway:onebusaway-sdk-java:0.1.0-alpha.23")

<!-- x-release-please-end -->

## Requirements

This library requires Java 8 or later.

## Usage

### Configure the client

Use `OnebusawaySdkOkHttpClient.builder()` to configure the client. At a minimum you need to set `.apiKey()`:
Expand Down Expand Up @@ -98,19 +98,7 @@ CurrentTimeRetrieveResponse currentTime = client.currentTime().retrieve(params);

To make a request to the Onebusaway SDK API, you generally build an instance of the appropriate `Params` class.

In [Example: creating a resource](#example-creating-a-resource) above, we used the `CurrentTimeRetrieveParams.builder()` to pass to the `retrieve` method of the `currentTime` service.

Sometimes, the API may support other properties that are not yet supported in the Java SDK types. In that case, you can attach them using the `putAdditionalProperty` method.

```java
import org.onebusaway.core.JsonValue;
import org.onebusaway.models.CurrentTimeRetrieveParams;

CurrentTimeRetrieveParams params = CurrentTimeRetrieveParams.builder()
// ... normal properties
.putAdditionalProperty("secret_param", JsonValue.from("4242"))
.build();
```
See [Undocumented request params](#undocumented-request-params) for how to send arbitrary parameters.

## Responses

Expand Down Expand Up @@ -238,18 +226,26 @@ This library is typed for convenient access to the documented API. If you need t

### Undocumented request params

To make requests using undocumented parameters, you can provide or override parameters on the params object while building it.
In [Example: creating a resource](#example-creating-a-resource) above, we used the `CurrentTimeRetrieveParams.builder()` to pass to the `retrieve` method of the `currentTime` service.

Sometimes, the API may support other properties that are not yet supported in the Java SDK types. In that case, you can attach them using raw setters:

```java
FooCreateParams address = FooCreateParams.builder()
.id("my_id")
.putAdditionalProperty("secret_prop", JsonValue.from("hello"))
import org.onebusaway.core.JsonValue;
import org.onebusaway.models.CurrentTimeRetrieveParams;

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

You can also use the `putAdditionalProperty` method on nested headers, query params, or body objects.

### Undocumented response properties

To access undocumented response properties, you can use `res._additionalProperties()` on a response object to get a map of untyped fields of type `Map<String, JsonValue>`. You can then access fields like `._additionalProperties().get("secret_prop").asString()` or use other helpers defined on the `JsonValue` class to extract it to a desired type.
To access undocumented response properties, you can use `res._additionalProperties()` on a response object to get a map of untyped fields of type `Map<String, JsonValue>`. You can then access fields like `res._additionalProperties().get("secret_prop").asString()` or use other helpers defined on the `JsonValue` class to extract it to a desired type.

## Logging

Expand All @@ -271,13 +267,9 @@ $ export ONEBUSAWAY_SDK_LOG=debug

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)_.
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/OneBusAway/java-sdk/issues) with questions, bugs, or suggestions.

## Requirements

This library requires Java 8 or later.
6 changes: 0 additions & 6 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
plugins {

}

allprojects {
group = "org.onebusaway"
version = "0.1.0-alpha.23" // x-release-please-version
}


2 changes: 1 addition & 1 deletion buildSrc/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
plugins {
`kotlin-dsl`
kotlin("jvm") version "1.9.22"
kotlin("jvm") version "2.1.0"
id("com.vanniktech.maven.publish") version "0.28.0"
}

Expand Down
4 changes: 0 additions & 4 deletions buildSrc/src/main/kotlin/onebusaway-sdk.java.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import com.diffplug.gradle.spotless.SpotlessExtension
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import com.vanniktech.maven.publish.JavaLibrary
import com.vanniktech.maven.publish.JavadocJar
import com.vanniktech.maven.publish.MavenPublishBaseExtension
import com.vanniktech.maven.publish.SonatypeHost

plugins {
`java-library`
Expand Down
9 changes: 6 additions & 3 deletions buildSrc/src/main/kotlin/onebusaway-sdk.kotlin.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import com.diffplug.gradle.spotless.SpotlessExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.vanniktech.maven.publish.*

plugins {
id("onebusaway-sdk.java")
Expand All @@ -22,8 +21,12 @@ configure<SpotlessExtension> {

tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
allWarningsAsErrors = true
freeCompilerArgs = listOf("-Xjvm-default=all", "-Xjdk-release=1.8")
freeCompilerArgs = listOf(
"-Xjvm-default=all",
"-Xjdk-release=1.8",
// Suppress deprecation warnings because we may still reference and test deprecated members.
"-Xsuppress-warning=DEPRECATION"
)
jvmTarget = "1.8"
}
}
9 changes: 1 addition & 8 deletions buildSrc/src/main/kotlin/onebusaway-sdk.publish.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.get
import com.vanniktech.maven.publish.JavaLibrary
import com.vanniktech.maven.publish.JavadocJar
import com.vanniktech.maven.publish.MavenPublishBaseExtension
import com.vanniktech.maven.publish.SonatypeHost

Expand All @@ -25,7 +18,7 @@ configure<MavenPublishBaseExtension> {
signAllPublications()
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)

this.coordinates(project.group.toString(), project.name, project.version.toString())
coordinates(project.group.toString(), project.name, project.version.toString())

pom {
name.set("OneBusAway")
Expand Down
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
6 changes: 4 additions & 2 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
Expand Down Expand Up @@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
Expand Down Expand Up @@ -84,7 +86,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down
2 changes: 2 additions & 0 deletions gradlew.bat
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import okio.BufferedSink
import org.onebusaway.core.RequestOptions
import org.onebusaway.core.checkRequired
import org.onebusaway.core.http.Headers
import org.onebusaway.core.http.HttpClient
import org.onebusaway.core.http.HttpMethod
Expand All @@ -30,36 +31,11 @@ class OkHttpClient
private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) :
HttpClient {

private fun getClient(requestOptions: RequestOptions): okhttp3.OkHttpClient {
val clientBuilder = okHttpClient.newBuilder()

val logLevel =
when (System.getenv("ONEBUSAWAY_SDK_LOG")?.lowercase()) {
"info" -> HttpLoggingInterceptor.Level.BASIC
"debug" -> HttpLoggingInterceptor.Level.BODY
else -> null
}
if (logLevel != null) {
clientBuilder.addNetworkInterceptor(HttpLoggingInterceptor().setLevel(logLevel))
}

val timeout = requestOptions.timeout
if (timeout != null) {
clientBuilder
.connectTimeout(timeout)
.readTimeout(timeout)
.writeTimeout(timeout)
.callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
}

return clientBuilder.build()
}

override fun execute(
request: HttpRequest,
requestOptions: RequestOptions,
): HttpResponse {
val call = getClient(requestOptions).newCall(request.toRequest())
val call = newCall(request, requestOptions)

return try {
call.execute().toResponse()
Expand All @@ -78,18 +54,18 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val

request.body?.run { future.whenComplete { _, _ -> close() } }

val call = getClient(requestOptions).newCall(request.toRequest())
call.enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
future.complete(response.toResponse())
}
newCall(request, requestOptions)
.enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
future.complete(response.toResponse())
}

override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(OnebusawaySdkIoException("Request failed", e))
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(OnebusawaySdkIoException("Request failed", e))
}
}
}
)
)

return future
}
Expand All @@ -100,10 +76,35 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val
okHttpClient.cache?.close()
}

private fun HttpRequest.toRequest(): Request {
private fun newCall(request: HttpRequest, requestOptions: RequestOptions): Call {
val clientBuilder = okHttpClient.newBuilder()

val logLevel =
when (System.getenv("ONEBUSAWAY_SDK_LOG")?.lowercase()) {
"info" -> HttpLoggingInterceptor.Level.BASIC
"debug" -> HttpLoggingInterceptor.Level.BODY
else -> null
}
if (logLevel != null) {
clientBuilder.addNetworkInterceptor(HttpLoggingInterceptor().setLevel(logLevel))
}

val timeout = requestOptions.timeout
if (timeout != null) {
clientBuilder
.connectTimeout(timeout)
.readTimeout(timeout)
.writeTimeout(timeout)
.callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
}

val client = clientBuilder.build()
return client.newCall(request.toRequest(client))
}

private fun HttpRequest.toRequest(client: okhttp3.OkHttpClient): Request {
var body: RequestBody? = body?.toRequestBody()
// OkHttpClient always requires a request body for PUT and POST methods.
if (body == null && (method == HttpMethod.PUT || method == HttpMethod.POST)) {
if (body == null && requiresBody(method)) {
body = "".toRequestBody()
}

Expand All @@ -112,9 +113,33 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val
headers.values(name).forEach { builder.header(name, it) }
}

if (
!headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0
) {
builder.header(
"X-Stainless-Read-Timeout",
Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString()
)
}
if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) {
builder.header(
"X-Stainless-Timeout",
Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString()
)
}

return builder.build()
}

/** `OkHttpClient` always requires a request body for some methods. */
private fun requiresBody(method: HttpMethod): Boolean =
when (method) {
HttpMethod.POST,
HttpMethod.PUT,
HttpMethod.PATCH -> true
else -> false
}

private fun HttpRequest.toUrl(): String {
url?.let {
return it
Expand Down Expand Up @@ -168,7 +193,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val
@JvmStatic fun builder() = Builder()
}

class Builder {
class Builder internal constructor() {

private var baseUrl: HttpUrl? = null
// The default timeout is 1 minute.
Expand All @@ -190,7 +215,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val
.callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
.proxy(proxy)
.build(),
checkNotNull(baseUrl) { "`baseUrl` is required but was not set" },
checkRequired("baseUrl", baseUrl),
)
}
}
Loading