diff --git a/src/main/java/com/treasuredata/client/AbstractTDClientBuilder.java b/src/main/java/com/treasuredata/client/AbstractTDClientBuilder.java index 32bb6f1d..2f457b82 100644 --- a/src/main/java/com/treasuredata/client/AbstractTDClientBuilder.java +++ b/src/main/java/com/treasuredata/client/AbstractTDClientBuilder.java @@ -18,9 +18,12 @@ */ package com.treasuredata.client; -import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import java.util.Optional; import java.util.stream.Stream; @@ -66,7 +69,7 @@ public abstract class AbstractTDClientBuilder headers = ImmutableMultimap.of(); + protected Map> headers = Collections.emptyMap(); private static Optional getConfigProperty(Properties p, TDClientConfig.Type key) { @@ -328,9 +331,20 @@ public BuilderImpl setConnectionPoolSize(int connectionPoolSize) return self(); } + /** + * @deprecated Use {@link #setHeaders(Map)} instead. + * @param headers + * @return + */ + @Deprecated public BuilderImpl setHeaders(Multimap headers) { - this.headers = ImmutableMultimap.copyOf(headers); + return this.setHeaders(headers.asMap()); + } + + public BuilderImpl setHeaders(Map> headers) + { + this.headers = Collections.unmodifiableMap(new HashMap<>(headers)); return self(); } diff --git a/src/main/java/com/treasuredata/client/TDApiRequest.java b/src/main/java/com/treasuredata/client/TDApiRequest.java index a161e496..0b2311ec 100644 --- a/src/main/java/com/treasuredata/client/TDApiRequest.java +++ b/src/main/java/com/treasuredata/client/TDApiRequest.java @@ -18,19 +18,20 @@ */ package com.treasuredata.client; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.Collections; import static java.util.Objects.requireNonNull; @@ -45,7 +46,7 @@ public class TDApiRequest private final TDHttpMethod method; private final String path; private final Map queryParams; - private final Multimap headerParams; + private final Map> headerParams; private final Optional postJson; private final Optional putFile; private final Optional content; @@ -57,7 +58,7 @@ public class TDApiRequest TDHttpMethod method, String path, Map queryParams, - Multimap headerParams, + Map> headerParams, Optional postJson, Optional putFile, Optional content, @@ -80,7 +81,7 @@ public class TDApiRequest public TDApiRequest withUri(String uri) { - return new TDApiRequest(method, uri, ImmutableMap.copyOf(queryParams), ImmutableMultimap.copyOf(headerParams), postJson, putFile, content, contentOffset, contentLength, followRedirects); + return new TDApiRequest(method, uri, Collections.unmodifiableMap(new HashMap<>(queryParams)), Collections.unmodifiableMap(new HashMap<>(headerParams)), postJson, putFile, content, contentOffset, contentLength, followRedirects); } public String getPath() @@ -98,7 +99,21 @@ public Map getQueryParams() return queryParams; } + /** + * @deprecated Use {@link #getAllHeaders()} instead. + * @return + */ + @Deprecated public Multimap getHeaderParams() + { + ImmutableMultimap.Builder builder = new ImmutableMultimap.Builder<>(); + for (Map.Entry> e : headerParams.entrySet()) { + builder.putAll(e.getKey(), e.getValue()); + } + return builder.build(); + } + + public Map> getAllHeaders() { return headerParams; } @@ -135,12 +150,12 @@ public Optional getFollowRedirects() public static class Builder { - private static final Map EMPTY_MAP = ImmutableMap.of(); - private static final Multimap EMPTY_HEADERS = ImmutableMultimap.of(); + private static final Map EMPTY_MAP = Collections.emptyMap(); + private static final Map> EMPTY_HEADERS = Collections.emptyMap(); private TDHttpMethod method; private String path; private Map queryParams; - private ImmutableMultimap.Builder headerParams; + private HashMap> headerParams; private Optional postJson = Optional.empty(); private Optional file = Optional.empty(); private Optional content = Optional.empty(); @@ -175,23 +190,54 @@ public static Builder DELETE(String uri) } public Builder addHeader(String key, String value) + { + return addHeaders(key, Collections.singletonList(value)); + } + + /** + * @deprecated Use {@link #addHeaders(Map)} or {@link #addHeaders(String, Collection)} instead. + * @param headers + * @return + */ + @Deprecated + public Builder addHeaders(Multimap headers) + { + return this.addHeaders(headers.asMap()); + } + + public Builder addHeaders(String key, Collection values) { if (headerParams == null) { - headerParams = ImmutableMultimap.builder(); + headerParams = new HashMap<>(); } - headerParams.put(key, value); + addHeaderValues(key, values); return this; } - public Builder addHeaders(Multimap headers) + public Builder addHeaders(Map> headers) { if (headerParams == null) { - headerParams = ImmutableMultimap.builder(); + headerParams = new HashMap<>(); + } + for (Map.Entry> e : headers.entrySet()) { + addHeaderValues(e.getKey(), e.getValue()); } - headerParams.putAll(headers); return this; } + private void addHeaderValues(String key, Collection values) + { + headerParams.compute(key, (unused, list) -> { + if (list == null) { + return new ArrayList<>(values); + } + else { + list.addAll(values); + return list; + } + }); + } + public Builder addQueryParam(String key, String value) { if (queryParams == null) { @@ -233,7 +279,7 @@ public TDApiRequest build() method, path, queryParams != null ? queryParams : EMPTY_MAP, - headerParams != null ? headerParams.build() : EMPTY_HEADERS, + headerParams != null ? Collections.unmodifiableMap(new HashMap<>(headerParams)) : EMPTY_HEADERS, postJson, file, content, diff --git a/src/main/java/com/treasuredata/client/TDClient.java b/src/main/java/com/treasuredata/client/TDClient.java index d8625629..b340551f 100644 --- a/src/main/java/com/treasuredata/client/TDClient.java +++ b/src/main/java/com/treasuredata/client/TDClient.java @@ -23,9 +23,6 @@ import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; import com.treasuredata.client.model.ObjectMappers; import com.treasuredata.client.model.TDApiKey; @@ -69,12 +66,16 @@ import java.io.InputStream; import java.net.URL; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; +import java.util.function.Function; import java.util.regex.Pattern; import static java.util.Objects.requireNonNull; @@ -143,12 +144,24 @@ public TDClient withApiKey(String newApiKey) return new TDClient(config, httpClient, Optional.of(newApiKey)); } + /** + * @deprecated Use {@link #withHeaders(Map)} instead. + * @param headers + * @return + */ + @Deprecated @Override public TDClient withHeaders(Multimap headers) { return new TDClient(config, httpClient.withHeaders(headers), apiKeyCache); } + @Override + public TDClient withHeaders(Map> headers) + { + return new TDClient(config, httpClient.withHeaders(headers), apiKeyCache); + } + /** * Visible for testing. */ @@ -240,7 +253,7 @@ protected ResultType doPost(String path, Map queryP protected ResultType doPost(String path, Class resultTypeClass) throws TDClientException { - return this.doPost(path, ImmutableMap.of(), Optional.empty(), resultTypeClass); + return this.doPost(path, Collections.emptyMap(), Optional.empty(), resultTypeClass); } protected ResultType doPost(String path, Map queryParam, Class resultTypeClass) @@ -320,7 +333,10 @@ protected String doPut(String path, File filePath) @Override public TDClient authenticate(String email, String password) { - TDAuthenticationResult authResult = doPost("/v3/user/authenticate", ImmutableMap.of("user", email, "password", password), TDAuthenticationResult.class); + Map m = new HashMap<>(); + m.put("user", email); + m.put("password", password); + TDAuthenticationResult authResult = doPost("/v3/user/authenticate", Collections.unmodifiableMap(m), TDAuthenticationResult.class); return withApiKey(authResult.getApikey()); } @@ -496,7 +512,7 @@ public void createTable(String databaseName, String tableName, String idempotent { // Idempotent key support is EXPERIMENTAL. doPost(buildUrl("/v3/table/create", databaseName, validateTableName(tableName), TDTableType.LOG.getTypeName()), - ImmutableMap.of("idempotent_key", idempotentKey)); + Collections.singletonMap("idempotent_key", idempotentKey)); } @Override @@ -523,7 +539,7 @@ public void renameTable(String databaseName, String tableName, String newTableNa throws TDClientException { doPost(buildUrl("/v3/table/rename", databaseName, tableName, validateTableName(newTableName)), - ImmutableMap.of("overwrite", Boolean.toString(overwrite)), + Collections.singletonMap("overwrite", Boolean.toString(overwrite)), TDUpdateTableResult.class ); } @@ -562,15 +578,15 @@ public TDPartialDeleteJob partialDelete(String databaseName, String tableName, l throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, String.format("from/to value must be a multiple of 3600: [%s, %s)", from, to)); } - ImmutableMap.Builder queryParams = ImmutableMap.builder() - .put("from", Long.toString(from)) - .put("to", Long.toString(to)); + Map queryParams = new HashMap<>(); + queryParams.put("from", Long.toString(from)); + queryParams.put("to", Long.toString(to)); if (domainKey != null) { queryParams.put("domain_key", domainKey); } - TDPartialDeleteJob job = doPost(buildUrl("/v3/table/partialdelete", databaseName, tableName), queryParams.build(), TDPartialDeleteJob.class); + TDPartialDeleteJob job = doPost(buildUrl("/v3/table/partialdelete", databaseName, tableName), Collections.unmodifiableMap(queryParams), TDPartialDeleteJob.class); return job; } @@ -593,12 +609,15 @@ public void updateTableSchema(String databaseName, String tableName, List> builder = ImmutableList.builder(); + List> builder = new ArrayList<>(newSchema.size()); for (TDColumn newColumn : newSchema) { - builder.add(ImmutableList.of(newColumn.getKeyString(), newColumn.getType().toString(), newColumn.getName())); + builder.add(Arrays.asList(newColumn.getKeyString(), newColumn.getType().toString(), newColumn.getName())); } - String schemaJson = toJSONString(ImmutableMap.of("schema", builder.build(), "ignore_duplicate_schema", ignoreDuplicate)); - doPost(buildUrl("/v3/table/update-schema", databaseName, tableName), ImmutableMap.of(), Optional.of(schemaJson), String.class); + Map m = new HashMap<>(); + m.put("schema", Collections.unmodifiableList(builder)); + m.put("ignore_duplicate_schema", ignoreDuplicate); + String schemaJson = toJSONString(m); + doPost(buildUrl("/v3/table/update-schema", databaseName, tableName), Collections.emptyMap(), Optional.of(schemaJson), String.class); } private static final ObjectMapper objectMapper = new ObjectMapper(); @@ -620,14 +639,14 @@ public void appendTableSchema(String databaseName, String tableName, List> builder = ImmutableList.builder(); + List> builder = new ArrayList<>(appendedSchema.size()); for (TDColumn appendedColumn : appendedSchema) { // Unlike update-schema API, append-schema API can generate alias for column name. // So we should not pass `appendedColumn.getName()` here. - builder.add(ImmutableList.of(appendedColumn.getKeyString(), appendedColumn.getType().toString())); + builder.add(Arrays.asList(appendedColumn.getKeyString(), appendedColumn.getType().toString())); } - String schemaJson = toJSONString(ImmutableMap.of("schema", builder.build())); - doPost(buildUrl("/v3/table/append-schema", databaseName, tableName), ImmutableMap.of(), Optional.of(schemaJson), String.class); + String schemaJson = toJSONString(Collections.singletonMap("schema", Collections.unmodifiableList(builder))); + doPost(buildUrl("/v3/table/append-schema", databaseName, tableName), Collections.emptyMap(), Optional.of(schemaJson), String.class); } @Override @@ -806,9 +825,9 @@ public void performBulkImportSession(String sessionName, Optional poolNa { Optional jsonBody = Optional.empty(); if (poolName.isPresent()) { - jsonBody = Optional.of(toJSONString(ImmutableMap.of("pool_name", poolName.get()))); + jsonBody = Optional.of(toJSONString(Collections.singletonMap("pool_name", poolName.get()))); } - doPost(buildUrl("/v3/bulk_import/perform", sessionName), ImmutableMap.of("priority", Integer.toString(priority.toInt())), jsonBody, String.class); + doPost(buildUrl("/v3/bulk_import/perform", sessionName), Collections.singletonMap("priority", Integer.toString(priority.toInt())), jsonBody, String.class); } @Override @@ -870,7 +889,7 @@ private String startSavedQueryV4(TDSavedQueryStartRequest request) TDSavedQueryStartResultV4 result = doPost(buildUrl("/v4/queries", Long.toString(request.id().get()), "jobs"), - ImmutableMap.of(), + Collections.emptyMap(), Optional.of(toJson(TDSavedQueryStartRequestV4.from(request))), TDSavedQueryStartResultV4.class); @@ -945,7 +964,7 @@ public TDSavedQuery saveQuery(TDSaveQueryRequest request) TDSavedQuery result = doPost( buildUrl("/v3/schedule/create", request.getName()), - ImmutableMap.of(), + Collections.emptyMap(), Optional.of(json), TDSavedQuery.class); return result; @@ -959,7 +978,7 @@ public TDSavedQuery updateSavedQuery(String name, TDSavedQueryUpdateRequest requ TDSavedQuery result = doPost( buildUrl("/v3/schedule/update", name), - ImmutableMap.of(), + Collections.emptyMap(), Optional.of(json), TDSavedQuery.class); return result; @@ -1029,7 +1048,7 @@ public TDBulkLoadSessionStartResult startBulkLoadSession(String name, long sched @Override public TDBulkLoadSessionStartResult startBulkLoadSession(String name, TDBulkLoadSessionStartRequest request) { - Map queryParams = ImmutableMap.of(); + Map queryParams = Collections.emptyMap(); String payload = null; try { payload = ObjectMappers.compactMapper().writeValueAsString(request); @@ -1086,36 +1105,36 @@ public Optional tableDistribution(String databaseName, Stri @Override public TDImportResult importFile(String databaseName, String tableName, File file) { - return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), file, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), Collections.emptyMap(), file, TDImportResult.class); } @Override public TDImportResult importFile(String databaseName, String tableName, File file, String id) { - return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), ImmutableMap.of(), file, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), Collections.emptyMap(), file, TDImportResult.class); } @Override public TDImportResult importBytes(String databaseName, String tableName, byte[] content) { - return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, 0, content.length, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), Collections.emptyMap(), content, 0, content.length, TDImportResult.class); } @Override public TDImportResult importBytes(String databaseName, String tableName, byte[] content, int offset, int length) { - return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, offset, length, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), Collections.emptyMap(), content, offset, length, TDImportResult.class); } @Override public TDImportResult importBytes(String databaseName, String tableName, byte[] content, String id) { - return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), ImmutableMap.of(), content, 0, content.length, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), Collections.emptyMap(), content, 0, content.length, TDImportResult.class); } @Override public TDImportResult importBytes(String databaseName, String tableName, byte[] content, int offset, int length, String id) { - return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), ImmutableMap.of(), content, offset, length, TDImportResult.class); + return doPut(buildUrl(String.format("/v3/table/import_with_id/%s/%s/%s/%s", databaseName, tableName, id, "msgpack.gz")), Collections.emptyMap(), content, offset, length, TDImportResult.class); } } diff --git a/src/main/java/com/treasuredata/client/TDClientApi.java b/src/main/java/com/treasuredata/client/TDClientApi.java index c4325899..0b9ff274 100644 --- a/src/main/java/com/treasuredata/client/TDClientApi.java +++ b/src/main/java/com/treasuredata/client/TDClientApi.java @@ -18,9 +18,10 @@ */ package com.treasuredata.client; +import java.util.Collection; +import java.util.Map; import java.util.Optional; -import com.google.common.base.Function; import com.google.common.collect.Multimap; import com.treasuredata.client.model.TDApiKey; import com.treasuredata.client.model.TDBulkImportSession; @@ -51,6 +52,7 @@ import java.io.InputStream; import java.util.Date; import java.util.List; +import java.util.function.Function; /** * Treasure Data Client API @@ -72,9 +74,19 @@ public interface TDClientApi * This instance will share the same internal http client, so closing the returned client will invalidate the current instance. * * @param headers + * @deprecated Use {@link #withHeaders(Map)} instead * @return */ - ClientImpl withHeaders(Multimap headers); + @Deprecated ClientImpl withHeaders(Multimap headers); + + /** + * Return a TDClientApi implementation that uses the provided headers when making api requests. + * This instance will share the same internal http client, so closing the returned client will invalidate the current instance. + * + * @param headers + * @return + */ + ClientImpl withHeaders(Map> headers); /** * Perform user email and password based authentication and return a new client that will use apikey based authentication. @@ -238,6 +250,24 @@ public interface TDClientApi TDJob jobInfo(String jobId); + /** + * Open an input stream to retrieve the job result. + * The input stream will be closed after this method + * + * You will receive an empty stream if the query has not finished yet. + * + * @deprecated Use {@link #jobResult(String, TDResultFormat, Function)} instead. + * @param jobId + * @param format + * @param resultStreamHandler + * @return + */ + @Deprecated + default Result jobResult(String jobId, TDResultFormat format, com.google.common.base.Function resultStreamHandler) + { + return this.jobResult(jobId, format, (Function) resultStreamHandler::apply); + } + /** * Open an input stream to retrieve the job result. * The input stream will be closed after this method @@ -278,6 +308,15 @@ public interface TDClientApi void deleteBulkImportSession(String sessionName); + /** + * @deprecated Use {@link #getBulkImportErrorRecords(String, Function)} instead. + */ + @Deprecated + default Result getBulkImportErrorRecords(String sessionName, com.google.common.base.Function resultStreamHandler) + { + return this.getBulkImportErrorRecords(sessionName, (Function) resultStreamHandler::apply); + } + Result getBulkImportErrorRecords(String sessionName, Function resultStreamHandler); /** diff --git a/src/main/java/com/treasuredata/client/TDClientConfig.java b/src/main/java/com/treasuredata/client/TDClientConfig.java index d0ae0060..04752105 100644 --- a/src/main/java/com/treasuredata/client/TDClientConfig.java +++ b/src/main/java/com/treasuredata/client/TDClientConfig.java @@ -19,7 +19,7 @@ package com.treasuredata.client; import com.fasterxml.jackson.annotation.JsonCreator; -import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,10 @@ import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Properties; @@ -78,11 +81,7 @@ public static enum Type public static List knownProperties() { - ImmutableList.Builder builder = ImmutableList.builder(); - for (Type t : Type.values()) { - builder.add(t); - } - return builder.build(); + return Arrays.asList(Type.values()); } /** @@ -103,8 +102,12 @@ public static List knownProperties() public final int connectTimeoutMillis; public final int readTimeoutMillis; public final int connectionPoolSize; + + @Deprecated public final Multimap headers; + public final Map> headersV2; + @JsonCreator TDClientConfig( Optional endpoint, @@ -122,7 +125,7 @@ public static List knownProperties() int connectTimeoutMillis, int readTimeoutMillis, int connectionPoolSize, - Multimap headers) + Map> headers) { this.endpoint = endpoint.orElse("api.treasuredata.com"); this.port = port; @@ -139,7 +142,12 @@ public static List knownProperties() this.connectTimeoutMillis = connectTimeoutMillis; this.readTimeoutMillis = readTimeoutMillis; this.connectionPoolSize = connectionPoolSize; - this.headers = headers; + this.headersV2 = headers; + ImmutableMultimap.Builder headersBuilder = ImmutableMultimap.builder(); + for (Map.Entry> e : headers.entrySet()) { + headersBuilder.putAll(e.getKey(), e.getValue()); + } + this.headers = headersBuilder.build(); } public TDClientConfig withApiKey(String apikey) @@ -165,7 +173,7 @@ public TDClientConfig withApiKey(Optional apikey) connectTimeoutMillis, readTimeoutMillis, connectionPoolSize, - headers + headersV2 ); } diff --git a/src/main/java/com/treasuredata/client/TDHttpClient.java b/src/main/java/com/treasuredata/client/TDHttpClient.java index 709b554f..fb6e9f26 100644 --- a/src/main/java/com/treasuredata/client/TDHttpClient.java +++ b/src/main/java/com/treasuredata/client/TDHttpClient.java @@ -27,8 +27,6 @@ import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.treasuredata.client.impl.ProxyAuthenticator; import com.treasuredata.client.model.JsonCollectionRootName; @@ -49,13 +47,17 @@ import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.StringJoiner; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -97,7 +99,7 @@ public class TDHttpClient /** * Visible for testing. */ - final Multimap headers; + final Map> headers; public TDHttpClient(TDClientConfig config) { @@ -125,7 +127,7 @@ public TDHttpClient(TDClientConfig config) // Build OkHttpClient this.httpClient = builder.build(); - this.headers = ImmutableMultimap.copyOf(config.headers); + this.headers = config.headersV2; // Prepare jackson json-object mapper this.objectMapper = defaultObjectMapper; @@ -136,7 +138,7 @@ protected TDHttpClient(TDHttpClient reference) this(reference.config, reference.httpClient, reference.objectMapper, reference.headers); } - private TDHttpClient(TDClientConfig config, OkHttpClient httpClient, ObjectMapper objectMapper, Multimap headers) + private TDHttpClient(TDClientConfig config, OkHttpClient httpClient, ObjectMapper objectMapper, Map> headers) { this.config = config; this.httpClient = httpClient; @@ -148,16 +150,28 @@ private TDHttpClient(TDClientConfig config, OkHttpClient httpClient, ObjectMappe * Get a {@link TDHttpClient} that uses the specified headers for each request. Reuses the same * underlying http client so closing the returned instance will return this instance as well. * + * @deprecated Use {@link #withHeaders(Map)} instead. * @param headers * @return */ + @Deprecated public TDHttpClient withHeaders(Multimap headers) { - Multimap mergedHeaders = ImmutableMultimap.builder() - .putAll(this.headers) - .putAll(headers) - .build(); - return new TDHttpClient(config, httpClient, objectMapper, mergedHeaders); + return withHeaders(headers.asMap()); + } + + /** + * Get a {@link TDHttpClient} that uses the specified headers for each request. Reuses the same + * underlying http client so closing the returned instance will return this instance as well. + * + * @param headers + * @return + */ + public TDHttpClient withHeaders(Map> headers) + { + Map> mergedHeaders = new HashMap<>(this.headers); + mergedHeaders.putAll(headers); + return new TDHttpClient(config, httpClient, objectMapper, Collections.unmodifiableMap(mergedHeaders)); } ObjectMapper getObjectMapper() @@ -228,7 +242,7 @@ public Request prepareRequest(TDApiRequest apiRequest, Optional apiKeyCa String dateHeader = RFC2822_FORMAT.get().format(new Date()); StringJoiner joiner = new StringJoiner(","); joiner.add(getClientName()); - for (String s : headers.get(USER_AGENT)) { + for (String s : headers.getOrDefault(USER_AGENT, Collections.emptyList())) { joiner.add(s); } String userAgent = joiner.toString(); @@ -241,13 +255,18 @@ public Request prepareRequest(TDApiRequest apiRequest, Optional apiKeyCa request = setTDAuthHeaders(request, dateHeader); // Set other headers - for (Map.Entry entry : headers.entries()) { - if (!entry.getKey().equals(USER_AGENT)) { - request = request.addHeader(entry.getKey(), entry.getValue()); + for (Map.Entry> e : headers.entrySet()) { + if (!e.getKey().equals(USER_AGENT)) { + for (String v : e.getValue()) { + request = request.addHeader(e.getKey(), v); + } } } - for (Map.Entry entry : apiRequest.getHeaderParams().entries()) { - request = request.addHeader(entry.getKey(), entry.getValue()); + for (Map.Entry> entry : apiRequest.getAllHeaders().entrySet()) { + String k = entry.getKey(); + for (String v : entry.getValue()) { + request = request.addHeader(k, v); + } } // Set API Key after setting the other headers @@ -505,6 +524,20 @@ public String call(TDApiRequest apiRequest, Optional apiKeyCache) return content; } + /** + * @deprecated Use {@link #call(TDApiRequest, Optional, Function)} instead. + * @param apiRequest + * @param apiKeyCache + * @param contentStreamHandler + * @param + * @return + */ + @Deprecated + public Result call(TDApiRequest apiRequest, Optional apiKeyCache, final com.google.common.base.Function contentStreamHandler) + { + return submitRequest(apiRequest, apiKeyCache, newByteStreamHandler(contentStreamHandler)); + } + /** * Submit an API request, and returns the byte InputStream. This stream is valid until exiting this function. * diff --git a/src/main/java/com/treasuredata/client/TDHttpRequestHandlers.java b/src/main/java/com/treasuredata/client/TDHttpRequestHandlers.java index 5611b257..6d59a187 100644 --- a/src/main/java/com/treasuredata/client/TDHttpRequestHandlers.java +++ b/src/main/java/com/treasuredata/client/TDHttpRequestHandlers.java @@ -1,9 +1,9 @@ package com.treasuredata.client; -import com.google.common.base.Function; import okhttp3.ResponseBody; import java.io.InputStream; +import java.util.function.Function; /** * Request handler implementations @@ -18,6 +18,22 @@ private TDHttpRequestHandlers() public static final TDHttpRequestHandler byteArrayContentHandler = response -> response.body().bytes(); + /** + * @deprecated Use {@link #newByteStreamHandler(Function)} instead. + * @param handler + * @return + * @param + */ + @Deprecated + public static final TDHttpRequestHandler newByteStreamHandler(final com.google.common.base.Function handler) + { + return response -> { + try (ResponseBody body = response.body()) { + return handler.apply(body.byteStream()); + } + }; + } + public static final TDHttpRequestHandler newByteStreamHandler(final Function handler) { return response -> { diff --git a/src/main/java/com/treasuredata/client/model/TDApiErrorMessage.java b/src/main/java/com/treasuredata/client/model/TDApiErrorMessage.java index 76c4bb0b..3c166b4e 100644 --- a/src/main/java/com/treasuredata/client/model/TDApiErrorMessage.java +++ b/src/main/java/com/treasuredata/client/model/TDApiErrorMessage.java @@ -20,8 +20,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.collect.ImmutableMap; +import java.util.Collections; import java.util.Map; /** @@ -39,7 +39,7 @@ public TDApiErrorMessage( String text, String severity) { - this(error, text, severity, ImmutableMap.of()); + this(error, text, severity, Collections.emptyMap()); } @JsonCreator diff --git a/src/main/java/com/treasuredata/client/model/TDColumnType.java b/src/main/java/com/treasuredata/client/model/TDColumnType.java index c90bbfc6..5c85701c 100644 --- a/src/main/java/com/treasuredata/client/model/TDColumnType.java +++ b/src/main/java/com/treasuredata/client/model/TDColumnType.java @@ -20,10 +20,10 @@ import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.google.common.collect.ImmutableList; import com.treasuredata.client.model.impl.TDColumnTypeDeserializer; import java.io.Serializable; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -37,16 +37,16 @@ public class TDColumnType implements Serializable public static final TDColumnType DOUBLE = new TDColumnType(TDTypeName.DOUBLE, Collections.emptyList()); public static final TDColumnType STRING = new TDColumnType(TDTypeName.STRING, Collections.emptyList()); - public static final List primitiveTypes = ImmutableList.of(INT, LONG, FLOAT, DOUBLE, STRING); + public static final List primitiveTypes = Arrays.asList(INT, LONG, FLOAT, DOUBLE, STRING); public static TDColumnType newArrayType(TDColumnType elementType) { - return new TDColumnType(TDTypeName.ARRAY, ImmutableList.of(elementType)); + return new TDColumnType(TDTypeName.ARRAY, Collections.singletonList(elementType)); } public static TDColumnType newMapType(TDColumnType keyType, TDColumnType valueType) { - return new TDColumnType(TDTypeName.MAP, ImmutableList.of(keyType, valueType)); + return new TDColumnType(TDTypeName.MAP, Arrays.asList(keyType, valueType)); } private final TDTypeName typeName; diff --git a/src/main/java/com/treasuredata/client/model/impl/TDScheduleRunResult.java b/src/main/java/com/treasuredata/client/model/impl/TDScheduleRunResult.java index df5883a9..ffb06c99 100644 --- a/src/main/java/com/treasuredata/client/model/impl/TDScheduleRunResult.java +++ b/src/main/java/com/treasuredata/client/model/impl/TDScheduleRunResult.java @@ -20,9 +20,10 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.collect.ImmutableList; import com.treasuredata.client.model.TDJob; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** @@ -78,7 +79,7 @@ public String toString() @JsonCreator public TDScheduleRunResult(@JsonProperty("jobs") List jobs) { - this.jobs = ImmutableList.copyOf(jobs); + this.jobs = Collections.unmodifiableList(new ArrayList<>(jobs)); } @JsonProperty("jobs") diff --git a/src/test/java/com/treasuredata/client/Example.java b/src/test/java/com/treasuredata/client/Example.java index 945d1745..4aa60da0 100644 --- a/src/test/java/com/treasuredata/client/Example.java +++ b/src/test/java/com/treasuredata/client/Example.java @@ -18,7 +18,6 @@ */ package com.treasuredata.client; -import com.google.common.base.Function; import com.treasuredata.client.model.TDBulkImportSession; import com.treasuredata.client.model.TDColumn; import com.treasuredata.client.model.TDColumnType; @@ -50,6 +49,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -138,24 +138,20 @@ public static void submitJobExample() System.out.println("error log:\n" + jobInfo.getStdErr()); // Read the job results in msgpack.gz format - client.jobResult(jobId, TDResultFormat.MESSAGE_PACK_GZ, new Function() { - @Override - public Integer apply(InputStream input) - { - int count = 0; - try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input))) { - while (unpacker.hasNext()) { - // Each row of the query result is array type value (e.g., [1, "name", ...]) - ArrayValue array = unpacker.unpackValue().asArrayValue(); - System.out.println(array); - count++; - } + Integer result = client.jobResult(jobId, TDResultFormat.MESSAGE_PACK_GZ, (Function) input -> { + int count = 0; + try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input))) { + while (unpacker.hasNext()) { + // Each row of the query result is array type value (e.g., [1, "name", ...]) + ArrayValue array = unpacker.unpackValue().asArrayValue(); + System.out.println(array); + count++; } - catch (Exception e) { - throw new RuntimeException(e); - } - return count; } + catch (Exception e) { + throw new RuntimeException(e); + } + return count; }); } catch (Exception e) { diff --git a/src/test/java/com/treasuredata/client/TestTDClient.java b/src/test/java/com/treasuredata/client/TestTDClient.java index 38e20bbd..cbf627ea 100644 --- a/src/test/java/com/treasuredata/client/TestTDClient.java +++ b/src/test/java/com/treasuredata/client/TestTDClient.java @@ -23,13 +23,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; import com.treasuredata.client.model.ObjectMappers; import com.treasuredata.client.model.TDBulkImportSession; import com.treasuredata.client.model.TDBulkLoadSessionStartRequest; @@ -78,7 +71,6 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Method; @@ -89,10 +81,12 @@ import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -102,6 +96,7 @@ import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -225,15 +220,10 @@ public void listDatabases() logger.debug(dbListStr); List detailedDBList = client.listDatabases(); - Iterable dbStr = Iterables.transform(detailedDBList, new Function() - { - @Override - public String apply(TDDatabase input) - { - String summary = String.format("name:%s, count:%s, createdAt:%s, updatedAt:%s, organization:%s, permission:%s", input.getName(), input.getCount(), input.getCreatedAt(), input.getUpdatedAt(), input.getOrganization(), input.getPermission()); - return summary; - } - }); + Iterable dbStr = detailedDBList.stream().map(input -> { + String summary = String.format("name:%s, count:%s, createdAt:%s, updatedAt:%s, organization:%s, permission:%s", input.getName(), input.getCount(), input.getCreatedAt(), input.getUpdatedAt(), input.getOrganization(), input.getPermission()); + return summary; + }).collect(Collectors.toList()); String detailedDbListStr = String.join(", ", dbStr); logger.trace(detailedDbListStr); @@ -314,20 +304,9 @@ public void listJobs() assertEquals(101, jobsInAnIDRange.getJobs().size()); // Check getters - Iterable getters = FluentIterable.from(TDJob.class.getDeclaredMethods()).filter(new Predicate() - { - @Override - public boolean apply(Method input) - { - return test(input); - } - - @Override - public boolean test(Method input) - { - return input.getName().startsWith("get"); - } - }); + Iterable getters = Arrays.stream(TDJob.class.getDeclaredMethods()).filter(input -> { + return input.getName().startsWith("get"); + }).collect(Collectors.toList()); // Call getters for (TDJob job : jobs.getJobs()) { for (Method m : getters) { @@ -390,28 +369,23 @@ public void submitJob() assertTrue(Long.parseLong(array[0]) > 0); // test msgpack.gz format - client.jobResult(jobId, TDResultFormat.MESSAGE_PACK_GZ, new Function() - { - @Override - public Object apply(InputStream input) - { - try { - logger.debug("Reading job result in msgpack.gz"); - MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input)); - int rowCount = 0; - while (unpacker.hasNext()) { - ArrayValue array = unpacker.unpackValue().asArrayValue(); - assertEquals(1, array.size()); - int numRows = array.get(0).asIntegerValue().toInt(); - assertTrue(numRows > 0); - rowCount++; - } - assertEquals(rowCount, 1); - return null; - } - catch (IOException e) { - throw new RuntimeException(e); + client.jobResult(jobId, TDResultFormat.MESSAGE_PACK_GZ, input -> { + try { + logger.debug("Reading job result in msgpack.gz"); + MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input)); + int rowCount = 0; + while (unpacker.hasNext()) { + ArrayValue array1 = unpacker.unpackValue().asArrayValue(); + assertEquals(1, array1.size()); + int numRows = array1.get(0).asIntegerValue().toInt(); + assertTrue(numRows > 0); + rowCount++; } + assertEquals(rowCount, 1); + return null; + } + catch (IOException e) { + throw new RuntimeException(e); } }); } @@ -926,21 +900,18 @@ public void tableOperation() byte[] keyName = "int_col_key_name".getBytes(StandardCharsets.UTF_8); // schema test TDTable targetTable = findTable(SAMPLE_DB, t).get(); - List newSchema = ImmutableList.builder() - .addAll(targetTable.getSchema()) - .add(new TDColumn("int_col", TDColumnType.INT, keyName)) - .build(); + + List newSchema = new ArrayList<>(targetTable.getSchema()); + newSchema.add(new TDColumn("int_col", TDColumnType.INT, keyName)); client.updateTableSchema(SAMPLE_DB, t, newSchema); TDTable updatedTable = findTable(SAMPLE_DB, t).get(); logger.debug(updatedTable.toString()); assertTrue("should have updated column", updatedTable.getSchema().contains(new TDColumn("int_col", TDColumnType.INT, keyName))); // schema test with duplicated key - newSchema = ImmutableList.builder() - .addAll(targetTable.getSchema()) - .add(new TDColumn("str_col", TDColumnType.STRING, keyName)) - .add(new TDColumn("str_col", TDColumnType.STRING, keyName)) - .build(); + newSchema = new ArrayList<>(targetTable.getSchema()); + newSchema.add(new TDColumn("str_col", TDColumnType.STRING, keyName)); + newSchema.add(new TDColumn("str_col", TDColumnType.STRING, keyName)); client.updateTableSchema(SAMPLE_DB, t, newSchema, true); updatedTable = findTable(SAMPLE_DB, t).get(); logger.debug(updatedTable.toString()); @@ -997,19 +968,14 @@ private String queryResult(String database, String sql) { String jobId = client.submit(TDJobRequest.newPrestoQuery(database, sql)); waitJobCompletion(jobId); - return client.jobResult(jobId, TDResultFormat.CSV, new Function() - { - @Override - public String apply(InputStream input) - { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { - String result = reader.lines().collect(Collectors.joining()); - logger.info(result); - return result; - } - catch (IOException e) { - throw new RuntimeException(e); - } + return client.jobResult(jobId, TDResultFormat.CSV, input -> { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { + String result = reader.lines().collect(Collectors.joining()); + logger.info(result); + return result; + } + catch (IOException e) { + throw new RuntimeException(e); } }); } @@ -1146,20 +1112,9 @@ public void testBulkImport() client.createBulkImportSession(session, SAMPLE_DB, bulkImportTable); List sessionList = client.listBulkImportSessions(); - TDBulkImportSession foundInList = Iterables.find(sessionList, new Predicate() - { - @Override - public boolean apply(TDBulkImportSession input) - { - return test(input); - } - - @Override - public boolean test(TDBulkImportSession input) - { - return input.getName().equals(session); - } - }); + TDBulkImportSession foundInList = sessionList.stream().filter(input -> { + return input.getName().equals(session); + }).findAny().get(); TDBulkImportSession bs = client.getBulkImportSession(session); logger.info("bulk import session: {}, error message: {}", bs.getJobId(), bs.getErrorMessage()); @@ -1237,26 +1192,21 @@ public boolean test(TDBulkImportSession input) assertTrue(bs.hasErrorOnPerform()); logger.debug(bs.getErrorMessage()); + final AtomicInteger errorRecordCount = new AtomicInteger(0); + // Error record check - int errorCount = client.getBulkImportErrorRecords(session, new Function() - { - int errorRecordCount = 0; - - @Override - public Integer apply(InputStream input) - { - try { - MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input)); - while (unpacker.hasNext()) { - Value v = unpacker.unpackValue(); - logger.info("error record: " + v); - errorRecordCount += 1; - } - return errorRecordCount; - } - catch (IOException e) { - throw new RuntimeException(e); + int errorCount = client.getBulkImportErrorRecords(session, input -> { + try { + MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new GZIPInputStream(input)); + while (unpacker.hasNext()) { + Value v = unpacker.unpackValue(); + logger.info("error record: " + v); + errorRecordCount.incrementAndGet(); } + return errorRecordCount.get(); + } + catch (IOException e) { + throw new RuntimeException(e); } }); @@ -1283,20 +1233,9 @@ public Integer apply(InputStream input) } // Check the data - TDTable imported = Iterables.find(client.listTables(SAMPLE_DB), new Predicate() - { - @Override - public boolean apply(TDTable input) - { - return test(input); - } - - @Override - public boolean test(TDTable input) - { - return input.getName().equals(bulkImportTable); - } - }); + TDTable imported = client.listTables(SAMPLE_DB).stream().filter(input -> { + return input.getName().equals(bulkImportTable); + }).findFirst().get(); assertEquals(numRowsInPart * 2, imported.getRowCount()); List columns = imported.getColumns(); @@ -1401,9 +1340,9 @@ public void listSavedQuery() public void getSavedQueryHistory() { List allQueries = client.listSavedQueries(); - List queries = FluentIterable.from(allQueries) + List queries = allQueries.stream() .limit(10) - .toList(); + .collect(Collectors.toList()); for (TDSavedQuery query : queries) { TDSavedQueryHistory firstPage = client.getSavedQueryHistory(query.getName()); @@ -1819,15 +1758,14 @@ public void arbitraryAuthorizationHeader() public void customHeaders() throws InterruptedException { - Multimap headers0 = ImmutableMultimap.of( - "k0", "v0"); - Multimap headers1 = ImmutableMultimap.of( - "k1", "v1a", - "k1", "v1b", - "k2", "v2"); - Multimap headers2 = ImmutableMultimap.of( - "k3", "v3", - "k4", "v4"); + Map> headers0 = Collections.singletonMap( + "k0", Collections.singleton("v0")); + Map> headers1 = new HashMap<>(); + headers1.put("k1", Arrays.asList("v1a", "v1b")); + headers1.put("k2", Collections.singletonList("v2")); + Map> headers2 = new HashMap<>(); + headers1.put("k3", Collections.singletonList("v3")); + headers1.put("k4", Collections.singletonList("v4")); client = TDClient.newBuilder(false) .setUseSSL(false) diff --git a/src/test/java/com/treasuredata/client/TestTDClientConfig.java b/src/test/java/com/treasuredata/client/TestTDClientConfig.java index b6556b09..3b265dbe 100644 --- a/src/test/java/com/treasuredata/client/TestTDClientConfig.java +++ b/src/test/java/com/treasuredata/client/TestTDClientConfig.java @@ -18,22 +18,21 @@ */ package com.treasuredata.client; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Multimap; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; -import java.util.Set; import static com.treasuredata.client.TDClientConfig.Type.API_ENDPOINT; import static com.treasuredata.client.TDClientConfig.Type.API_PORT; @@ -65,10 +64,10 @@ @SuppressWarnings("unchecked") public class TestTDClientConfig { - static ImmutableMap m; + static Map m; static { - ImmutableMap.Builder p = ImmutableMap.builder(); + Map p = new HashMap<>(); p.put(API_ENDPOINT, "api2.treasuredata.com"); p.put(API_PORT, 8981); p.put(USESSL, true); @@ -81,7 +80,7 @@ public class TestTDClientConfig p.put(RETRY_MULTIPLIER, 1.5); p.put(USER, "xxxx"); p.put(PASSOWRD, "yyyy"); - m = p.build(); + m = Collections.unmodifiableMap(p); assertTrue(new HashSet<>(TDClientConfig.knownProperties()).containsAll(m.keySet())); } @@ -214,17 +213,25 @@ public void canConvertToProperties() public void customHeaders() throws Exception { - Multimap noHeaders = ImmutableMultimap.of(); - Multimap headers = ImmutableMultimap.of( - "k1", "v1a", - "k2", "v2"); - Multimap extraHeaders = ImmutableMultimap.of( - "k1", "v1b", - "k3", "v3"); - Multimap combinedHeaders = ImmutableMultimap.builder() - .putAll(headers) - .putAll(extraHeaders) - .build(); + Map> noHeaders = Collections.emptyMap(); + Map> headers = new HashMap<>(); + headers.put("k1", Collections.singletonList("v1a")); + headers.put("k2", Collections.singletonList("v2")); + Map> extraHeaders = new HashMap<>(); + headers.put("k1", Collections.singletonList("v1b")); + headers.put("k3", Collections.singletonList("v3")); + Map> combinedHeaders = new HashMap<>(headers); + for (Map.Entry> e : extraHeaders.entrySet()) { + combinedHeaders.compute(e.getKey(), (unused, col) -> { + if (col != null) { + col.addAll(e.getValue()); + return col; + } + else { + return new ArrayList<>(e.getValue()); + } + }); + } TDClient clientWithNoHeaders1 = TDClient.newBuilder(false).build(); TDClient clientWithNoHeaders2 = TDClient.newBuilder(false).setHeaders(noHeaders).build(); @@ -258,26 +265,24 @@ public void apikeyWither() assertThat(config.withApiKey(Optional.empty()).withApiKey("bar").apiKey, is(Optional.of("bar"))); } - private Matcher> equalTo(final Multimap multimap) + private Matcher>> equalTo(final Map> multimap) { - return new BaseMatcher>() + return new BaseMatcher>>() { @Override public boolean matches(Object item) { - if (!(item instanceof Multimap)) { + if (!(item instanceof Map)) { return false; } - Multimap other = (Multimap) item; - Set> entries = ImmutableSet.copyOf(multimap.entries()); - Set> otherEntries = ImmutableSet.copyOf(other.entries()); - return entries.equals(otherEntries); + Map> other = (Map>) item; + return multimap.entrySet().equals(other.entrySet()); } @Override public void describeTo(Description description) { - description.appendValue(multimap.entries()); + description.appendValue(multimap.entrySet()); } }; } diff --git a/src/test/java/com/treasuredata/client/TestTDHttpClient.java b/src/test/java/com/treasuredata/client/TestTDHttpClient.java index b5c3b3f5..506b5b18 100644 --- a/src/test/java/com/treasuredata/client/TestTDHttpClient.java +++ b/src/test/java/com/treasuredata/client/TestTDHttpClient.java @@ -18,7 +18,6 @@ */ package com.treasuredata.client; -import com.google.common.collect.ImmutableMultimap; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Protocol; @@ -40,6 +39,7 @@ import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; @@ -95,7 +95,7 @@ public void addUserAgentHeader() assertEquals("td-client-java unknown", request1.header(USER_AGENT)); // With specifying User-Agent header - TDHttpClient newClient = client.withHeaders(ImmutableMultimap.of(USER_AGENT, "td-sample-client 1.0")); + TDHttpClient newClient = client.withHeaders(Collections.singletonMap(USER_AGENT, Collections.singletonList("td-sample-client 1.0"))); Request request2 = newClient.prepareRequest(apiRequest, Optional.empty()); assertEquals("td-client-java unknown,td-sample-client 1.0", request2.header(USER_AGENT)); } diff --git a/src/test/java/com/treasuredata/client/model/TestTDColumn.java b/src/test/java/com/treasuredata/client/model/TestTDColumn.java index 96407566..e8e51a44 100644 --- a/src/test/java/com/treasuredata/client/model/TestTDColumn.java +++ b/src/test/java/com/treasuredata/client/model/TestTDColumn.java @@ -19,7 +19,6 @@ package com.treasuredata.client.model; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableSet; import org.junit.Test; import java.io.ByteArrayOutputStream; @@ -85,7 +84,7 @@ public void parseRenamedColumns() public void parsePrimitiveColumnTypes() { // primitive type set - Set primitives = ImmutableSet.copyOf(TDColumnType.primitiveTypes); + Set primitives = new HashSet<>(TDColumnType.primitiveTypes); // primitive types for (String name : new String[] {"int", "long", "float", "double", "string"}) {