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

com.nerdvision.agent.HTTPClient Maven / Gradle / Ivy

package com.nerdvision.agent;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HTTPClient
{
    private static final Logger LOGGER = LoggerFactory.getLogger( HTTPClient.class );

    private final OkHttpClient client;
    private final String uuid;
    private String session;
    private final String apikey;


    public HTTPClient( final String uuid, final String apikey )
    {
        this.uuid = uuid;
        this.apikey = apikey;
        this.client = new OkHttpClient();
    }


    public void setSession( final String session )
    {
        this.session = session;
    }


    public  void postJsonAsync( final String url,
                                   final byte[] bytes,
                                   final IHTTPResponseHandler handler )
    {
        final long start = System.currentTimeMillis();
        final RequestBody body = RequestBody.create( MediaType.get( "application/json; charset=utf-8" ), bytes );
        final Request request = new Request.Builder()
                .header( "Authorization", Credentials.basic( uuidOrSession(), apikey ) )
                .url( url )
                .post( body )
                .build();

        client.newCall( request ).enqueue( new Callback()
        {
            @Override
            public void onFailure( final Call call, final IOException e )
            {
                handler.handleError( e );
                final long end = System.currentTimeMillis();
                LOGGER.debug( "HTTP POST to ({}) took: {}", url, (end - start) );
            }


            @Override
            public void onResponse( final Call call, final Response response )
            {
                try( Response re = response )
                {
                    handler.handleResponse( re );
                }
                finally
                {
                    final long end = System.currentTimeMillis();
                    LOGGER.debug( "HTTP POST to ({}) took: {}", url, (end - start) );
                }
            }
        } );
    }


    public  T postJson( final String url,
                           final byte[] bytes,
                           final IHTTPResponseHandler handler )
    {
        final long start = System.currentTimeMillis();
        final RequestBody body = RequestBody.create( MediaType.get( "application/json; charset=utf-8" ), bytes );
        final Request request = new Request.Builder()
                .header( "Authorization", Credentials.basic( uuidOrSession(), apikey ) )
                .url( url )
                .post( body )
                .build();

        try( final Response response = client.newCall( request ).execute() )
        {
            return handler.handleResponse( response );
        }
        catch( IOException e )
        {
            handler.handleError( e );
        }
        finally
        {
            final long end = System.currentTimeMillis();
            LOGGER.debug( "HTTP POST to ({}) took: {}", url, (end - start) );
        }
        return null;
    }


    String uuidOrSession()
    {
        if( this.session == null )
        {
            return this.uuid;
        }
        return this.session;
    }


    public static class JsonBodyHandler implements IHTTPResponseHandler
    {
        private static final Logger LOGGER = LoggerFactory.getLogger( JsonBodyHandler.class );

        @Override
        public JSONObject handleResponse( final Response response )
        {
            if( response.code() == 200 && response.body() != null )
            {
                final byte[] bytes;
                try
                {
                    bytes = response.body().bytes();
                    return JsonUtils.fromJson( bytes );
                }
                catch( IOException e )
                {
                    handleError( e );
                }
            }
            return null;
        }


        @Override
        public void handleError( final Exception e )
        {
            LOGGER.error( "Error handling request", e );
        }
    }


    public static class SinkBodyHandler implements IHTTPResponseHandler
    {

        @Override
        public Object handleResponse( final Response response )
        {
            return null;
        }


        @Override
        public void handleError( final Exception e )
        {
            LOGGER.error( "Error handling request", e );
        }
    }


    public interface IHTTPResponseHandler
    {
        T handleResponse( final Response response );


        void handleError( final Exception e );
    }
}