Skip to content

Commit

Permalink
add java
Browse files Browse the repository at this point in the history
  • Loading branch information
shortcuts committed May 20, 2022
1 parent 5ad13a6 commit b20ebf4
Show file tree
Hide file tree
Showing 19 changed files with 81 additions and 76 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.algolia.utils;

public class UseReadTransporter {}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.algolia.utils.retry;

import com.algolia.exceptions.*;
import com.algolia.utils.UseReadTransporter;
import com.algolia.utils.Utils;
import java.io.IOException;
import java.net.SocketTimeoutException;
Expand Down Expand Up @@ -28,8 +29,11 @@ public Interceptor getRetryInterceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
UseReadTransporter useReadTransporter = (UseReadTransporter) request.tag();
Iterator<StatefulHost> hostsIter = getTryableHosts(
request.method().equals("GET") ? CallType.READ : CallType.WRITE
(useReadTransporter != null || request.method().equals("GET"))
? CallType.READ
: CallType.WRITE
)
.iterator();
while (hostsIter.hasNext()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function createTransporter({
requestOptions: RequestOptions
): Promise<TResponse> {
const stackTrace: StackFrame[] = [];
const isRead = request?.useReadMethod || request.method === 'GET';
const isRead = request?.useReadTransporter || request.method === 'GET';

/**
* First we prepare the payload that do not depend from hosts.
Expand All @@ -99,12 +99,13 @@ export function createTransporter({
const method = request.method;

// On `GET`, the data is proxied to query parameters.
const dataQueryParameters: Record<string, any> = isRead
? {
...request.data,
...requestOptions.data,
}
: {};
const dataQueryParameters: Record<string, any> =
request.method === 'GET'
? {
...request.data,
...requestOptions.data,
}
: {};

const queryParameters: QueryParameters = {
'x-algolia-agent': algoliaAgent.value,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export type Request = {
* Some POST methods in the Algolia REST API uses the `read` transporter.
* This information is defined at the spec level.
*/
useReadMethod?: boolean;
useReadTransporter?: boolean;
};

export type EndRequest = {
Expand Down
2 changes: 1 addition & 1 deletion playground/javascript/node/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const searchIndex = process.env.SEARCH_INDEX || 'test_index';
const searchQuery = process.env.SEARCH_QUERY || 'test_query';

// Init client with appId and apiKey
const client = searchClient(appId, apiKey, { requester: echoRequester() });
const client = searchClient(appId, apiKey);

client.addAlgoliaAgent('Node playground', '0.0.1');

Expand Down
2 changes: 1 addition & 1 deletion specs/recommend/paths/getRecommendations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- recommendations
operationId: getRecommendations
x-use-read-method: true
x-use-read-transporter: true
summary: Get results.
description: Returns recommendations or trending results, for a specific model and `objectID`.
requestBody:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Dictionaries
operationId: searchDictionaryEntries
x-use-read-method: true
x-use-read-transporter: true
description: Search the dictionary entries.
summary: Search a dictionary entries.
parameters:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/multiclusters/searchUserIds.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Clusters
operationId: searchUserIds
x-use-read-method: true
x-use-read-transporter: true
summary: Search userID.
description: >
Search for userIDs.
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/objects/multipleGetObjects.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Records
operationId: getObjects
x-use-read-method: true
x-use-read-transporter: true
summary: Retrieve one or more objects.
description: Retrieve one or more objects, potentially from different indices, in a single API call.
requestBody:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/rules/searchRules.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Rules
operationId: searchRules
x-use-read-method: true
x-use-read-transporter: true
summary: Search for rules.
description: Search for rules matching various criteria.
parameters:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/search/search.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Search
operationId: search
x-use-read-method: true
x-use-read-transporter: true
summary: Search multiple indices.
description: Perform a search operation targeting one or many indices.
requestBody:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/search/searchForFacetValues.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Search
operationId: searchForFacetValues
x-use-read-method: true
x-use-read-transporter: true
summary: Search for values of a given facet.
description: Search for values of a given facet, optionally restricting the returned values to those contained in objects matching other search criteria.
parameters:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/search/searchSingleIndex.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Search
operationId: searchSingleIndex
x-use-read-method: true
x-use-read-transporter: true
summary: Search in a single index.
description: Perform a search operation targeting one specific index.
parameters:
Expand Down
2 changes: 1 addition & 1 deletion specs/search/paths/synonyms/searchSynonyms.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ post:
tags:
- Synonyms
operationId: searchSynonyms
x-use-read-method: true
x-use-read-transporter: true
summary: Search synonyms.
description: Search or browse all synonyms, optionally filtering them by type.
parameters:
Expand Down
95 changes: 46 additions & 49 deletions templates/java/libraries/okhttp-gson/ApiClient.mustache
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package {{invokerPackage}};

import com.algolia.utils.Requester;
import com.algolia.exceptions.*;
import com.algolia.utils.AlgoliaAgent;
import com.algolia.utils.JSON;
import com.algolia.utils.RequestOptions;
import com.algolia.utils.*;

import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
Expand Down Expand Up @@ -270,13 +267,14 @@ public class ApiClient {
* @param body The request body object
* @param headerParams The header parameters
* @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
* @param useReadTransporter Some POST methods in the Algolia REST API uses the `read` transporter. This information is defined at the spec level.
* @return The HTTP call
* @throws AlgoliaRuntimeException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, Map<String, Object> queryParameters, Object body, Map<String, String> headerParams, RequestOptions requestOptions) throws AlgoliaRuntimeException {
Request request = buildRequest(path, method, queryParameters, body, headerParams, requestOptions);
public Call buildCall(String path, String method, Map<String, Object> queryParameters, Object body, Map<String, String> headerParams, RequestOptions requestOptions, Boolean useReadTransporter) throws AlgoliaRuntimeException {
Request request = buildRequest(path, method, queryParameters, body, headerParams, requestOptions, useReadTransporter);
return requester.newCall(request);
return requester.newCall(request, useReadTransporter);
}
/**
Expand All @@ -288,39 +286,52 @@ public class ApiClient {
* @param body The request body object
* @param headerParams The header parameters
* @param requestOptions The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
* @param useReadTransporter Some POST methods in the Algolia REST API uses the `read` transporter. This information is defined at the spec level.
* @return The HTTP request
* @throws AlgoliaRuntimeException If fail to serialize the request body object
*/
public Request buildRequest(String path, String method, Map<String, Object> queryParameters, Object body, Map<String, String> headerParams, RequestOptions requestOptions) throws AlgoliaRuntimeException {
boolean hasRequestOptions = requestOptions != null;
final String url = buildUrl(
path,
queryParameters,
hasRequestOptions ? requestOptions.getExtraQueryParameters() : null
);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(
headerParams,
hasRequestOptions ? requestOptions.getExtraHeaders() : null,
reqBuilder
);
public Request buildRequest(
String path,
String method,
Map<String, Object> queryParameters,
Object body,
Map<String, String> headerParams,
RequestOptions requestOptions,
Boolean useReadTransporter
) throws AlgoliaRuntimeException {
boolean hasRequestOptions = requestOptions != null;
final String url = buildUrl(
path,
queryParameters,
hasRequestOptions ? requestOptions.getExtraQueryParameters() : null
);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(
headerParams,
hasRequestOptions ? requestOptions.getExtraHeaders() : null,
reqBuilder
);
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create("", MediaType.parse(this.contentType));
}
} else {
reqBody = serialize(body);
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create("", MediaType.parse(this.contentType));
}
} else {
reqBody = serialize(body);
}
return reqBuilder.method(method, reqBody).build();
if (useReadTransporter) {
reqBuilder.tag(new UseReadTransporter());
}
return reqBuilder.method(method, reqBody).build();
}
/**
Expand Down Expand Up @@ -401,18 +412,4 @@ public class ApiClient {
}
}
}
/**
* Build a form-encoding request body with the given form parameters.
*
* @param formParams Form parameters in the form of Map
* @return RequestBody
*/
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder();
for (Entry<String, Object> param : formParams.entrySet()) {
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
}
return formBuilder.build();
}
}
2 changes: 1 addition & 1 deletion templates/java/libraries/okhttp-gson/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public class {{classname}} extends ApiClient {
}

{{/headerParams}}
Call call = this.buildCall(requestPath, "{{httpMethod}}", queryParameters, bodyObj, headers, requestOptions);
Call call = this.buildCall(requestPath, "{{httpMethod}}", queryParameters, bodyObj, headers, requestOptions, {{#vendorExtensions.x-use-read-transporter}}true{{/vendorExtensions.x-use-read-transporter}}{{^vendorExtensions.x-use-read-transporter}}false{{/vendorExtensions.x-use-read-transporter}});
Type returnType = new TypeToken<{{{returnType}}}>() {}.getType();
return this.executeAsync(call, returnType);
}
Expand Down
6 changes: 3 additions & 3 deletions templates/javascript/api-single.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,9 @@ export function create{{capitalizedApiName}}(options: CreateClientOptions{{#hasR
{{#bodyParam}}
data: {{paramName}},
{{/bodyParam}}
{{#vendorExtensions.x-use-read-method}}
useReadMethod: true,
{{/vendorExtensions.x-use-read-method}}
{{#vendorExtensions.x-use-read-transporter}}
useReadTransporter: true,
{{/vendorExtensions.x-use-read-transporter}}
};

return transporter.request(request, {
Expand Down
4 changes: 2 additions & 2 deletions tests/CTS/client/recommend/api.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"expected": {
"match": {
"objectContaining": {
"host": "test-app-id.algolia.net"
"host": "test-app-id-dsn.algolia.net"
}
}
}
Expand Down Expand Up @@ -58,7 +58,7 @@
"match": {
"objectContaining": {
"connectTimeout": 2,
"responseTimeout": 30
"responseTimeout": 5
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions tests/CTS/client/search/api.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"expected": {
"match": {
"objectContaining": {
"host": "test-app-id.algolia.net"
"host": "test-app-id-dsn.algolia.net"
}
}
}
Expand Down Expand Up @@ -70,7 +70,7 @@
"match": {
"objectContaining": {
"connectTimeout": 2,
"responseTimeout": 30
"responseTimeout": 5
}
}
}
Expand Down

0 comments on commit b20ebf4

Please sign in to comment.