diff --git a/README.md b/README.md
index 1f6f27e..b25e288 100644
--- a/README.md
+++ b/README.md
@@ -28,18 +28,18 @@ dependency is Jackson for JSON. Thread-safe.
io.newsdatanewsdataapi
- 0.3.0
+ 0.4.0
```
### Gradle (Kotlin DSL)
```kotlin
-implementation("io.newsdata:newsdataapi:0.2.1")
+implementation("io.newsdata:newsdataapi:0.4.0")
```
### Gradle (Groovy DSL)
```groovy
-implementation 'io.newsdata:newsdataapi:0.2.1'
+implementation 'io.newsdata:newsdataapi:0.4.0'
```
## Quickstart
@@ -141,7 +141,8 @@ for (ArticleV2 a : resp.articlesV2(client.objectMapper())) {
| `imageUrl()`, `videoUrl()` | `media().imageUrl()`, `media().videoUrl()` |
| `sentiment()`, `sentimentStats()` | `ai().sentiment().label()`, `ai().sentiment().score()` |
| `aiTag()`, `aiRegion()`, `aiOrg()` | `ai().tag()`, `ai().region()`, `ai().organization()` |
-| — | `ai().summary()`, `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` |
+| `aiSummary()` | `ai().summary()` |
+| `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` | `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` |
A group the API did not send (`source`, `media`, `ai`) is `null`; a list field
it did not send is an empty list. `ai().region()` entries are comma-separated
@@ -168,6 +169,14 @@ field holds the single notice, and a withheld sentiment carries it in
The real-time service is v2 only — there are no v1 WebSocket methods.
+v1 articles decode with `resp.articles(client.objectMapper())`. On plans
+without the AI add-ons, `ai_tag`, `ai_region` and `ai_org` arrive as the API's
+notice string: the list then holds that single notice
+(`ArticleV2.isPlanNotice(value)` recognises it), and `sentimentStats()` is
+`null`. If the results cannot be decoded at all, `articles()` and
+`articlesV2()` throw a `NewsdataException` carrying the decoding error rather
+than returning an empty list.
+
`params` is a `Map`. Use the bundled [`Params`](src/main/java/io/newsdata/api/Params.java) helper for fluent construction — `null` values are dropped automatically so you can chain optional fields without `if`-guards. Values may be `String`, `Number`, `Boolean`, or `Collection` (sent comma-joined). Parameter names are case-insensitive — `qInTitle` and `qintitle` are equivalent.
## Pagination
@@ -194,19 +203,19 @@ client.paginate(Endpoint.LATEST, Params.of().with("q", "news"))
client.latest(Params.of().with("rawQuery", "q=bitcoin&country=us&language=en"));
```
-`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves.
+`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves; for the v1 count endpoints it must also carry `from_date` and `to_date`. It works with `scrollAll`, `paginate` and `websocketRegister` too: parameters are validated once, and the page cursor (or `news_type`) is added afterwards.
## Client-side validation
A `NewsdataValidationException` is thrown — before any HTTP request — when:
- a parameter is not accepted by that endpoint;
-- mutually-exclusive parameters are set together — `q`/`qInTitle`/`qInMeta`, `country`/`excludecountry`, `category`/`excludecategory`, `language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`;
+- mutually-exclusive parameters are set together — version 1: `q`/`qInTitle`/`qInMeta`, `country`/`excludecountry`, `category`/`excludecategory`, `language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`/`excludedomainurl`; version 2: `q`/`q_in_title`/`q_in_meta`, `country`/`exclude_country`, `category`/`exclude_category`, `language`/`exclude_language`, `source_url`/`exclude_source_url`;
- `size` is outside 1–50;
- `sentiment_score` is set without `sentiment`;
- a count endpoint is missing `from_date` or `to_date`.
-Booleans for `full_content`, `image`, `video`, and `removeduplicate` are coerced to `"1"`/`"0"`.
+Booleans for `full_content`, `image`, `video`, `removeduplicate`, and the version 2 `content` and `remove_duplicate` are coerced to `"1"`/`"0"`.
## Real-time news (WebSocket)
@@ -262,12 +271,22 @@ rejection — bad API key or unknown
`registration_id`, exhausted API credits, or too many simultaneous devices — throws
`NewsdataWebSocketAuthException` and is **not** retried.
-The server always accepts the handshake and then closes with code **1008** when
-the connection is refused, carrying one of three reasons: `invalid credentials
-or registration not found`, `api limit reached`, or `device limit reached` (more
-than 5 devices on one `registration_id`). Every other close code — including
-`1013` (`send timeout`, meaning the client read too slowly) — is transient and
-reconnects.
+When it refuses a connection, the server accepts the handshake, sends one error
+response — `{"status":"error","results":{"message":"…","code":"…"}}` — and
+closes. That response never reaches your handler: it becomes the exception,
+whose message is the server's explanation, `errorCode()` its code and
+`responseBody()` the raw response. Close code **1008** is permanent; its reason
+is the bare code: `Unauthorized` or `InvalidRequest` (bad key or unknown
+`registration_id`), `ApiLimitExceeded` or `ApiKeyLimitExceeded` (credits used
+up), `DeviceLimitExceeded` (more than 5 devices on one `registration_id`).
+Every other close code — `1011` (server error) and `1013` (the client read too
+slowly) included — is transient and reconnects; with `.reconnect(false)` it
+throws `NewsdataWebSocketException` carrying the server's message.
+
+A quiet stream is not a failure: news can be minutes apart. When nothing
+arrives for `pingInterval` (default 20 s) the client sends a ping, and only
+when nothing comes back within `pingTimeout` (default 20 s) is the connection
+treated as dead and reconnected.
**Each delivered article consumes 1 API credit per connected device.**
@@ -277,7 +296,7 @@ Catch it like any other client error:
try {
ws.stream(registrationId, response -> true);
} catch (NewsdataWebSocketAuthException e) {
- System.err.println("rejected: " + e.getMessage());
+ System.err.println("rejected (" + e.errorCode() + "): " + e.getMessage());
} catch (NewsdataWebSocketException e) {
System.err.println("stream error: " + e.getMessage());
}
@@ -292,6 +311,8 @@ NewsDataApiWebSocket ws = NewsDataApiWebSocket.builder(client)
.reconnectDelay(Duration.ofSeconds(1)) // first delay; doubles each retry
.reconnectDelayMax(Duration.ofSeconds(30)) // cap on the delay
.handshakeTimeout(Duration.ofSeconds(10)) // opening handshake bound
+ .pingInterval(Duration.ofSeconds(20)) // silence before a keepalive ping; ZERO = off
+ .pingTimeout(Duration.ofSeconds(20)) // wait for a reply before reconnecting
.headers(Map.of("X-Trace", "abc")) // extra handshake headers
.build();
```
@@ -357,7 +378,7 @@ NewsDataApiClient client = NewsDataApiClient.builder()
`baseUrl` is the API root **without** a version segment; the default is `https://newsdata.io/api/` and the client adds `1/…` or `2/…` itself. Before 0.3.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `1/` if you override it.
-Retries cover network errors, HTTP 429, and 5xx. 429 honours the `Retry-After` header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger.
+Retries cover network errors, HTTP 429, and 5xx. A 429 waits for its `Retry-After` (integer seconds or HTTP-date) plus one second; without the header, backoff is exponential. When `Retry-After` is longer than `retryBackoffMax`, the call throws `NewsdataRateLimitException` at once with `retryAfter()` set, leaving the wait to you. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger and from error messages; a `baseUrl` that is not a valid absolute URL is rejected by `build()`.
A 429 that waiting cannot fix is never retried: `NewsdataApiLimitExceededException` means the account's whole credit pool is exhausted, `NewsdataApiKeyLimitExceededException` means this one key hit its own cap while the account may still have credits, and both extend `NewsdataRateLimitException`, so an existing `catch` on that type keeps working. `RegistrationLimitExceeded` is also never retried, but keeps the plain `NewsdataRateLimitException` — it is about real-time registration slots, not credits, and is fixed by deleting a registration.
diff --git a/pom.xml b/pom.xml
index cedaec5..deec2f2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,7 +6,7 @@
io.newsdatanewsdataapi
- 0.3.0
+ 0.4.0jarnewsdataapi
diff --git a/src/main/java/io/newsdata/api/Article.java b/src/main/java/io/newsdata/api/Article.java
index e3e4936..beeca44 100644
--- a/src/main/java/io/newsdata/api/Article.java
+++ b/src/main/java/io/newsdata/api/Article.java
@@ -5,6 +5,7 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* One news article from API v1 of the Newsdata.io API.
@@ -16,6 +17,15 @@
* {@code article.getTitle()}.
*
*
JSON keys use the API's snake_case; component names are camelCase.
+ *
+ *
The crypto endpoint fills {@code coin}; the market endpoint fills
+ * {@code symbol} and {@code marketId}.
+ *
+ *
On plans without the AI add-ons the API sends a plain notice string in
+ * place of some fields: a list field then holds that one notice (see
+ * {@link ArticleV2#isPlanNotice(String)}) and {@code sentimentStats} is
+ * {@code null}. A field the API does not send (or sends as {@code null}) is
+ * {@code null}.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public record Article(
@@ -24,8 +34,8 @@ public record Article(
@JsonProperty("link") String link,
@JsonProperty("description") String description,
@JsonProperty("content") String content,
- @JsonProperty("keywords") List keywords,
- @JsonProperty("creator") List creator,
+ @JsonProperty("keywords") @JsonDeserialize(using = NullableStringListDeserializer.class) List keywords,
+ @JsonProperty("creator") @JsonDeserialize(using = NullableStringListDeserializer.class) List creator,
@JsonProperty("video_url") String videoUrl,
@JsonProperty("image_url") String imageUrl,
@JsonProperty("pubDate") String pubDate,
@@ -36,14 +46,37 @@ public record Article(
@JsonProperty("source_icon") String sourceIcon,
@JsonProperty("source_name") String sourceName,
@JsonProperty("language") String language,
- @JsonProperty("country") List country,
- @JsonProperty("category") List category,
- @JsonProperty("ai_tag") List aiTag,
- @JsonProperty("ai_region") List aiRegion,
- @JsonProperty("ai_org") List aiOrg,
+ @JsonProperty("country") @JsonDeserialize(using = NullableStringListDeserializer.class) List country,
+ @JsonProperty("category") @JsonDeserialize(using = NullableStringListDeserializer.class) List category,
+ @JsonProperty("ai_tag") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiTag,
+ @JsonProperty("ai_region") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiRegion,
+ @JsonProperty("ai_org") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiOrg,
@JsonProperty("sentiment") String sentiment,
- @JsonProperty("sentiment_stats") Map sentimentStats,
+ @JsonProperty("sentiment_stats") @JsonDeserialize(using = LenientMapDeserializer.class)
+ Map sentimentStats,
@JsonProperty("datatype") String dataType,
- @JsonProperty("symbol") List symbol,
- @JsonProperty("market_id") List marketId
-) {}
+ @JsonProperty("symbol") @JsonDeserialize(using = NullableStringListDeserializer.class) List symbol,
+ @JsonProperty("market_id") @JsonDeserialize(using = NullableStringListDeserializer.class) List marketId,
+ @JsonProperty("fetched_at") String fetchedAt,
+ @JsonProperty("ai_summary") String aiSummary,
+ @JsonProperty("duplicate") Boolean duplicate,
+ @JsonProperty("coin") @JsonDeserialize(using = NullableStringListDeserializer.class) List coin
+) {
+ /**
+ * The constructor from before {@code fetchedAt}, {@code aiSummary},
+ * {@code duplicate} and {@code coin} were added; those four are
+ * {@code null}. Kept so code that builds articles by hand still compiles.
+ */
+ public Article(String articleId, String title, String link, String description, String content,
+ List keywords, List creator, String videoUrl, String imageUrl,
+ String pubDate, String pubDateTZ, String sourceId, Integer sourcePriority, String sourceUrl,
+ String sourceIcon, String sourceName, String language, List country,
+ List category, List aiTag, List aiRegion, List aiOrg,
+ String sentiment, Map sentimentStats, String dataType, List symbol,
+ List marketId) {
+ this(articleId, title, link, description, content, keywords, creator, videoUrl, imageUrl,
+ pubDate, pubDateTZ, sourceId, sourcePriority, sourceUrl, sourceIcon, sourceName,
+ language, country, category, aiTag, aiRegion, aiOrg, sentiment, sentimentStats,
+ dataType, symbol, marketId, null, null, null, null);
+ }
+}
diff --git a/src/main/java/io/newsdata/api/Constants.java b/src/main/java/io/newsdata/api/Constants.java
index 9998f25..4abefb8 100644
--- a/src/main/java/io/newsdata/api/Constants.java
+++ b/src/main/java/io/newsdata/api/Constants.java
@@ -12,7 +12,7 @@
/**
* Static configuration: base URL, endpoint paths, HTTP defaults, and the
* per-endpoint accepted-parameter sets. Mirrors the server-side filter
- * mapping and the official Python/PHP/Node/Go/Dart clients.
+ * mapping.
*
*
Parameter names are stored lowercase here; user-supplied keys are
* lowercased before validation (the API is case-insensitive, so
@@ -102,6 +102,12 @@ private Constants() {}
/** Bound on the opening handshake. */
public static final Duration WS_HANDSHAKE_TIMEOUT = Duration.ofSeconds(10);
+ /** Keepalive: silence after which the client sends a ping. */
+ public static final Duration WS_PING_INTERVAL = Duration.ofSeconds(20);
+
+ /** Keepalive: how long to wait for anything after a ping before the connection counts as dead. */
+ public static final Duration WS_PING_TIMEOUT = Duration.ofSeconds(20);
+
/**
* Error codes on a 429 that waiting cannot fix, so they are never retried.
* {@code ApiLimitExceeded} and {@code ApiKeyLimitExceeded} mean the API
@@ -294,14 +300,15 @@ NewsdataRateLimitException create(String message, int statusCode, String respons
// Real-time query registration. The real-time service is v2 only,
// so these are the v2 filter names. No date or paging filters apply
// — a registered query matches news as it is published.
- // `news_type` is set by websocketRegister, not by the caller.
+ // `news_type` is not accepted from the caller: websocketRegister
+ // adds it after validation (so it also works with rawQuery).
Map.entry("websocket_register", Set.of(
"q", "q_in_title", "q_in_meta", "country", "exclude_country",
"category", "exclude_category", "language", "exclude_language",
"source_url", "exclude_source_url", "source_priority", "timezone",
"content", "image", "video", "remove_duplicate", "tag", "sentiment",
"sentiment_score", "region", "organization", "creator", "datatype",
- "exclude_field", "news_type"
+ "exclude_field"
)),
Map.entry("websocket_fetch", Set.of()),
Map.entry("websocket_delete", Set.of("registration_id"))
diff --git a/src/main/java/io/newsdata/api/LenientMapDeserializer.java b/src/main/java/io/newsdata/api/LenientMapDeserializer.java
new file mode 100644
index 0000000..78969f5
--- /dev/null
+++ b/src/main/java/io/newsdata/api/LenientMapDeserializer.java
@@ -0,0 +1,32 @@
+package io.newsdata.api;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * Reads a JSON object as a {@code Map}, and anything else as {@code null}.
+ *
+ *
On plans without the AI add-ons the API replaces object fields such as
+ * {@code sentiment_stats} with a plain "not in your plan" notice string. Plain
+ * map deserialization fails on that and loses the whole page; this reads the
+ * notice as "no data" instead.
+ *
+ *
Package-private: it is an implementation detail of {@link Article}.
+ */
+final class LenientMapDeserializer extends JsonDeserializer