Skip to content
This repository has been archived by the owner on Feb 12, 2023. It is now read-only.

Commit

Permalink
imlement issue influxdata#449 : support for Basic Authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
lxhoan committed Aug 21, 2018
1 parent becbfb5 commit 090864f
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 49 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## 2.13 [unreleased]

### Features

- Support for Basic Authentication [PR #492](https://github.com/influxdata/influxdb-java/pull/492)

## 2.12 [2018-07-31]

Expand Down
24 changes: 24 additions & 0 deletions src/main/java/org/influxdb/impl/BasicAuthInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.influxdb.impl;

import java.io.IOException;

import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BasicAuthInterceptor implements Interceptor {

private String credentials;

public BasicAuthInterceptor(final String user, final String password) {
credentials = Credentials.basic(user, password);
}

@Override
public Response intercept(final Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder().header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
49 changes: 16 additions & 33 deletions src/main/java/org/influxdb/impl/InfluxDBImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,6 @@ public class InfluxDBImpl implements InfluxDB {
private static final LogLevel LOG_LEVEL = LogLevel.parseLogLevel(System.getProperty(LOG_LEVEL_PROPERTY));

private final InetAddress hostAddress;
private final String username;
private final String password;
private String version;
private final Retrofit retrofit;
private final InfluxDBService influxDBService;
Expand Down Expand Up @@ -116,16 +114,14 @@ public InfluxDBImpl(final String url, final String username, final String passwo
final ResponseFormat responseFormat) {
this.messagePack = ResponseFormat.MSGPACK.equals(responseFormat);
this.hostAddress = parseHostAddress(url);
this.username = username;
this.password = password;

this.loggingInterceptor = new HttpLoggingInterceptor();
setLogLevel(LOG_LEVEL);

this.gzipRequestInterceptor = new GzipRequestInterceptor();
OkHttpClient.Builder clonedBuilder = client.build().newBuilder();
clonedBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor);

clonedBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor).
addInterceptor(new BasicAuthInterceptor(username, password));
Factory converterFactory = null;
switch (responseFormat) {
case MSGPACK:
Expand Down Expand Up @@ -164,16 +160,15 @@ public InfluxDBImpl(final String url, final String username, final String passwo
super();
this.messagePack = false;
this.hostAddress = parseHostAddress(url);
this.username = username;
this.password = password;

this.loggingInterceptor = new HttpLoggingInterceptor();
setLogLevel(LOG_LEVEL);

this.gzipRequestInterceptor = new GzipRequestInterceptor();
OkHttpClient.Builder clonedBuilder = client.build().newBuilder();
this.retrofit = new Retrofit.Builder().baseUrl(url)
.client(clonedBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor).build())
.client(clonedBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor).
addInterceptor(new BasicAuthInterceptor(username, password)).build())
.addConverterFactory(MoshiConverterFactory.create()).build();
this.influxDBService = influxDBService;

Expand Down Expand Up @@ -420,8 +415,6 @@ public void write(final BatchPoints batchPoints) {
this.batchedCount.add(batchPoints.getPoints().size());
RequestBody lineProtocol = RequestBody.create(MEDIA_TYPE_STRING, batchPoints.lineProtocol());
execute(this.influxDBService.writePoints(
this.username,
this.password,
batchPoints.getDatabase(),
batchPoints.getRetentionPolicy(),
TimeUtil.toTimePrecision(batchPoints.getPrecision()),
Expand All @@ -434,8 +427,6 @@ public void write(final BatchPoints batchPoints) {
public void write(final String database, final String retentionPolicy, final ConsistencyLevel consistency,
final TimeUnit precision, final String records) {
execute(this.influxDBService.writePoints(
this.username,
this.password,
database,
retentionPolicy,
TimeUtil.toTimePrecision(precision),
Expand Down Expand Up @@ -534,12 +525,10 @@ public void query(final Query query, final int chunkSize, final Consumer<QueryRe
Call<ResponseBody> call = null;
if (query instanceof BoundParameterQuery) {
BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query;
call = this.influxDBService.query(this.username, this.password,
query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize,
call = this.influxDBService.query(query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize,
boundParameterQuery.getParameterJsonWithUrlEncoded());
} else {
call = this.influxDBService.query(this.username, this.password,
query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize);
call = this.influxDBService.query(query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize);
}

call.enqueue(new Callback<ResponseBody>() {
Expand Down Expand Up @@ -578,11 +567,11 @@ public QueryResult query(final Query query, final TimeUnit timeUnit) {
Call<QueryResult> call = null;
if (query instanceof BoundParameterQuery) {
BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query;
call = this.influxDBService.query(this.username, this.password, query.getDatabase(),
call = this.influxDBService.query(query.getDatabase(),
TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded(),
boundParameterQuery.getParameterJsonWithUrlEncoded());
} else {
call = this.influxDBService.query(this.username, this.password, query.getDatabase(),
call = this.influxDBService.query(query.getDatabase(),
TimeUtil.toTimePrecision(timeUnit), query.getCommandWithUrlEncoded());
}
return executeQuery(call);
Expand All @@ -595,25 +584,23 @@ public QueryResult query(final Query query, final TimeUnit timeUnit) {
public void createDatabase(final String name) {
Preconditions.checkNonEmptyString(name, "name");
String createDatabaseQueryString = String.format("CREATE DATABASE \"%s\"", name);
executeQuery(this.influxDBService.postQuery(this.username, this.password, Query.encode(createDatabaseQueryString)));
executeQuery(this.influxDBService.postQuery(Query.encode(createDatabaseQueryString)));
}

/**
* {@inheritDoc}
*/
@Override
public void deleteDatabase(final String name) {
executeQuery(this.influxDBService.postQuery(this.username, this.password,
Query.encode("DROP DATABASE \"" + name + "\"")));
executeQuery(this.influxDBService.postQuery(Query.encode("DROP DATABASE \"" + name + "\"")));
}

/**
* {@inheritDoc}
*/
@Override
public List<String> describeDatabases() {
QueryResult result = executeQuery(this.influxDBService.query(this.username,
this.password, SHOW_DATABASE_COMMAND_ENCODED));
QueryResult result = executeQuery(this.influxDBService.query(SHOW_DATABASE_COMMAND_ENCODED));
// {"results":[{"series":[{"name":"databases","columns":["name"],"values":[["mydb"]]}]}]}
// Series [name=databases, columns=[name], values=[[mydb], [unittest_1433605300968]]]
List<List<Object>> databaseNames = result.getResults().get(0).getSeries().get(0).getValues();
Expand Down Expand Up @@ -647,16 +634,13 @@ private Call<QueryResult> callQuery(final Query query) {
Call<QueryResult> call;
if (query instanceof BoundParameterQuery) {
BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query;
call = this.influxDBService.postQuery(this.username,
this.password, query.getDatabase(), query.getCommandWithUrlEncoded(),
call = this.influxDBService.postQuery(query.getDatabase(), query.getCommandWithUrlEncoded(),
boundParameterQuery.getParameterJsonWithUrlEncoded());
} else {
if (query.requiresPost()) {
call = this.influxDBService.postQuery(this.username,
this.password, query.getDatabase(), query.getCommandWithUrlEncoded());
call = this.influxDBService.postQuery(query.getDatabase(), query.getCommandWithUrlEncoded());
} else {
call = this.influxDBService.query(this.username,
this.password, query.getDatabase(), query.getCommandWithUrlEncoded());
call = this.influxDBService.query(query.getDatabase(), query.getCommandWithUrlEncoded());
}
}
return call;
Expand Down Expand Up @@ -767,7 +751,7 @@ public void createRetentionPolicy(final String rpName, final String database, fi
if (isDefault) {
queryBuilder.append(" DEFAULT");
}
executeQuery(this.influxDBService.postQuery(this.username, this.password, Query.encode(queryBuilder.toString())));
executeQuery(this.influxDBService.postQuery(Query.encode(queryBuilder.toString())));
}

/**
Expand Down Expand Up @@ -802,8 +786,7 @@ public void dropRetentionPolicy(final String rpName, final String database) {
.append("\" ON \"")
.append(database)
.append("\"");
executeQuery(this.influxDBService.postQuery(this.username, this.password,
Query.encode(queryBuilder.toString())));
executeQuery(this.influxDBService.postQuery(Query.encode(queryBuilder.toString())));
}

private interface ChunkProccesor {
Expand Down
25 changes: 10 additions & 15 deletions src/main/java/org/influxdb/impl/InfluxDBService.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,49 +39,44 @@ interface InfluxDBService {
* Can be one of one, any, all, quorum. Defaults to all.
*/
@POST("write")
public Call<ResponseBody> writePoints(@Query(U) String username,
@Query(P) String password, @Query(DB) String database,
public Call<ResponseBody> writePoints(@Query(DB) String database,
@Query(RP) String retentionPolicy, @Query(PRECISION) String precision,
@Query(CONSISTENCY) String consistency, @Body RequestBody batchPoints);

@GET("query")
public Call<QueryResult> query(@Query(U) String username, @Query(P) String password, @Query(DB) String db,
public Call<QueryResult> query(@Query(DB) String db,
@Query(EPOCH) String epoch, @Query(value = Q, encoded = true) String query);

@POST("query")
public Call<QueryResult> query(@Query(U) String username, @Query(P) String password, @Query(DB) String db,
public Call<QueryResult> query(@Query(DB) String db,
@Query(EPOCH) String epoch, @Query(value = Q, encoded = true) String query,
@Query(value = PARAMS, encoded = true) String params);

@GET("query")
public Call<QueryResult> query(@Query(U) String username, @Query(P) String password, @Query(DB) String db,
public Call<QueryResult> query(@Query(DB) String db,
@Query(value = Q, encoded = true) String query);

@POST("query")
public Call<QueryResult> postQuery(@Query(U) String username, @Query(P) String password, @Query(DB) String db,
public Call<QueryResult> postQuery(@Query(DB) String db,
@Query(value = Q, encoded = true) String query);

@POST("query")
public Call<QueryResult> postQuery(@Query(U) String username, @Query(P) String password, @Query(DB) String db,
public Call<QueryResult> postQuery(@Query(DB) String db,
@Query(value = Q, encoded = true) String query, @Query(value = PARAMS, encoded = true) String params);

@GET("query")
public Call<QueryResult> query(@Query(U) String username, @Query(P) String password,
@Query(value = Q, encoded = true) String query);
public Call<QueryResult> query(@Query(value = Q, encoded = true) String query);

@POST("query")
public Call<QueryResult> postQuery(@Query(U) String username,
@Query(P) String password, @Query(value = Q, encoded = true) String query);
public Call<QueryResult> postQuery(@Query(value = Q, encoded = true) String query);

@Streaming
@GET("query?chunked=true")
public Call<ResponseBody> query(@Query(U) String username,
@Query(P) String password, @Query(DB) String db, @Query(value = Q, encoded = true) String query,
public Call<ResponseBody> query(@Query(DB) String db, @Query(value = Q, encoded = true) String query,
@Query(CHUNK_SIZE) int chunkSize);

@Streaming
@POST("query?chunked=true")
public Call<ResponseBody> query(@Query(U) String username,
@Query(P) String password, @Query(DB) String db, @Query(value = Q, encoded = true) String query,
public Call<ResponseBody> query(@Query(DB) String db, @Query(value = Q, encoded = true) String query,
@Query(CHUNK_SIZE) int chunkSize, @Query(value = PARAMS, encoded = true) String params);
}
2 changes: 1 addition & 1 deletion src/test/java/org/influxdb/impl/ChunkingExceptionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void testChunkingException(Exception ex, String message) throws IOExcepti
Call<ResponseBody> call = mock(Call.class);
ResponseBody responseBody = mock(ResponseBody.class);

when(influxDBService.query(any(String.class), any(String.class), any(String.class), any(String.class), anyInt())).thenReturn(call);
when(influxDBService.query(any(String.class), any(String.class), anyInt())).thenReturn(call);
when(responseBody.source()).thenReturn(new Buffer());
doThrow(ex).when(adapter).fromJson(any(JsonReader.class));

Expand Down

0 comments on commit 090864f

Please sign in to comment.