All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.graylog2.rest.RemoteInterfaceProvider Maven / Gradle / Ivy

There is a newer version: 5.2.7
Show newest version
/**
 * This file is part of Graylog.
 *
 * Graylog is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Graylog is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Graylog.  If not, see .
 */
package org.graylog2.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.graylog2.cluster.Node;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import javax.inject.Inject;

public class RemoteInterfaceProvider {
    private final ObjectMapper objectMapper;
    private final OkHttpClient okHttpClient;

    @Inject
    public RemoteInterfaceProvider(ObjectMapper objectMapper,
                                   OkHttpClient okHttpClient) {
        this.objectMapper = objectMapper;
        this.okHttpClient = okHttpClient;
    }

    public  T get(Node node, final String authorizationToken, Class interfaceClass) {
        final OkHttpClient okHttpClient = this.okHttpClient.newBuilder()
                .addInterceptor(chain -> {
                    final Request original = chain.request();

                    Request.Builder builder = original.newBuilder()
                            .header(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString())
                            .method(original.method(), original.body());

                    if (authorizationToken != null) {
                        builder = builder.header(HttpHeaders.AUTHORIZATION, authorizationToken);
                    }

                    return chain.proceed(builder.build());
                })
                .build();
        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(node.getTransportAddress())
                .addConverterFactory(JacksonConverterFactory.create(objectMapper))
                .client(okHttpClient)
                .build();

        return retrofit.create(interfaceClass);
    }

    public  T get(Node node, Class interfaceClass) {
        return get(node, null, interfaceClass);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy