Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.dottydingo.hyperion.client;
  
 
 import java.net.URI;
 import java.util.List;
 import java.util.Map;

 
 public class HyperionClient
 {
     private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapperBuilder().getObjectMapper();
     protected String baseUrl;
     protected OkHttpClient client;
     protected ParameterFactory parameterFactory;
     protected HeaderFactory headerFactory;
     protected String userAgent = "hyperionClient";
 
     public HyperionClient(String baseUrl)
     {
         this. = baseUrl;
         if (!baseUrl.endsWith("/"))
             this.+="/";
 
          = new OkHttpClient();
         // do not pool connections
         .setConnectionPool(new ConnectionPool(0,1000));
     }
 
     public HyperionClient(String baseUrlAuthorizationFactory authorizationFactory)
     {
         this(baseUrl);
         this. = authorizationFactory;
     }
 
     public void setParameterFactory(ParameterFactory parameterFactory)
     {
         this. = parameterFactory;
     }
 
     public void setHeaderFactory(HeaderFactory headerFactory)
     {
         this. = headerFactory;
     }
 
     public void setObjectMapper(ObjectMapper objectMapper)
     {
         this. = objectMapper;
     }
 
     public void setProxy(Proxy proxy)
     {
         java.net.Proxy p = new java.net.Proxy(....,
                 new InetSocketAddress(proxy.getHost(),proxy.getPort()));
         .setProxy(p);
     }
 
     protected void setClient(OkHttpClient client)
     {
         this. = client;
     }
 
     public void setClientEventListener(ClientEventListener clientEventListener)
     {
         this. = clientEventListener;
     }
 
     public void setUserAgent(String userAgent)
     {
         this. = userAgent;
     }
 
     public <T extends ApiObjectEntityResponse<T> get(Request<T> request)
     {
         return executeRequest(request,.getTypeFactory()
                .constructParametricType(EntityResponse.classrequest.getEntityType()));
    }
    public <T extends ApiObjectEntityResponse<T> query(Request<T> request)
    {
        return executeRequest(request.getTypeFactory()
                .constructParametricType(EntityResponse.classrequest.getEntityType()));
    }
    public int delete(Request request)
    {
                DeleteResponse.class));
        return response.getCount();
    }
    public <T extends ApiObject> T create(Request<T> request)
    {
        return executeRequest(request,.getTypeFactory().constructType(request.getEntityType()));
    }
    public <T extends ApiObject> T update(Request<T> request)
    {
        return executeRequest(request.getTypeFactory().constructType(request.getEntityType()));
    }
    protected <R> R executeRequest(Request requestJavaType javaType)
    {
        long start = System.currentTimeMillis();
        boolean error = true;
        try
        {
            HttpURLConnection connection = executeRequest(request);
            R r = readResponse(connectionjavaType);
            error = false;
            return r;
        }
        finally
        {
            if( != null)
            {
                ClientEvent event = new ClientEvent(,request.getEntityName(),request.getRequestMethod(),
                        System.currentTimeMillis() - start,error);
                .handleEvent(event);
            }
        }
    }
    protected <T> T readResponse(HttpURLConnection connection,JavaType javaType)
    {
        try
        {
            return .readValue(connection.getInputStream(),javaType);
        }
        catch (IOException e)
        {
            throw new ClientMarshallingException("Error reading results.",e);
        }
        finally
        {
            connection.disconnect();
        }
    }
    protected HttpURLConnection executeRequest(Request request)
    {
        try
        {
            HttpURLConnection connection = .open(URI.create(buildUrl(request)).toURL());
            executeRequest(requestconnection);
            if(connection.getResponseCode() == . &&  != null
                    && .retryOnAuthenticationError())
            {
                if( instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory).reset();
                connection.disconnect();
                connection = .open(URI.create(buildUrl(request)).toURL());
                executeRequest(requestconnection);
            }
            if (connection.getResponseCode() >= .)
            {
                throw readException(connection);
            }
            return connection;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }
    }
    private void executeRequest(Request requestHttpURLConnection connectionthrows IOException
    {
        setHeaders(connectionrequest);
        connection.setRequestMethod(request.getRequestMethod().name());
        if(request.getRequestMethod().isBodyRequest())
        {
            connection.addRequestProperty("Content-type","application/json");
            .writeValue(connection.getOutputStream(),request.getRequestBody());
        }
    }
    protected HyperionException readException(HttpURLConnection connectionthrows IOException
    {
        try
        {
            ErrorResponse errorResponse = null;
            try
            {
                errorResponse = .readValue(connection.getErrorStream(), ErrorResponse.class);
            }
            catch (Exception ignore)
            {
            }
            HyperionException resolvedException = null;
            if (errorResponse != null)
            {
                try
                {
                    Class exceptionClass = Class.forName(errorResponse.getType());
                    resolvedException = (HyperionExceptionexceptionClass.getConstructor(String.class)
                            .newInstance(errorResponse.getMessage());
                }
                catch (Exception ignore)
                {
                }
                if (resolvedException == null)
                {
                    resolvedException =
                            new HyperionException(errorResponse.getStatusCode(), errorResponse.getMessage());
                }
                resolvedException.setErrorDetails(errorResponse.getErrorDetails());
            }
            if (resolvedException == null)
                resolvedException =
                        new HyperionException(connection.getResponseCode(), connection.getResponseMessage());
            return resolvedException;
        }
        finally
        {
            connection.disconnect();
        }
    }
    protected boolean hasEntries(MultiMap map)
    {
        return map != null && !map.isEmpty();
    }
    protected String buildUrl(Request request)
    {
        StringBuilder sb = new StringBuilder(512);
        sb.append().append(request.getEntityName()).append("/");
        if(request.getPath() != null)
            sb.append(request.getPath());
        String queryString = buildQueryString(request);
        if(queryString.length()>0)
        {
            sb.append("?").append(queryString);
        }
        return sb.toString();
    }
    protected String buildQueryString(Request request)
    {
        MultiMap resolvedParameters = null;
        if( != null)
        {
            resolvedParameters = .getParameters();
        }
        if(hasEntries(resolvedParameters))
            resolvedParameters = resolvedParameters.merge(request.getParameters());
        else
            resolvedParameters = request.getParameters();
        if( != null)
        {
            MultiMap authEntries = .getParameters();
            if(hasEntries(authEntries))
                resolvedParameters = resolvedParameters.merge(authEntries);
        }
        int ct = 0;
        StringBuilder sb = new StringBuilder(512);
        for (Map.Entry<StringList<String>> entry : resolvedParameters.entries())
        {
            for (String value : entry.getValue())
            {
                if(ct++ > 0)
                    sb.append("&");
                sb.append(encode(entry.getKey())).append("=").append(encode(value));
            }
        }
        return sb.toString();
    }
    protected void setHeaders(HttpURLConnection connection,Request request)
    {
        MultiMap resolvedHeaders = null;
        if( != null)
            resolvedHeaders = .getHeaders();
        if(hasEntries(resolvedHeaders))
            resolvedHeaders = resolvedHeaders.merge(request.getHeaders());
        else
            resolvedHeaders = request.getHeaders();
        if( != null)
        {
            MultiMap authEntries = .getHeaders();
            if(hasEntries(authEntries))
                resolvedHeaders = resolvedHeaders.merge(authEntries);
        }
        if(resolvedHeaders.getFirst("user-agent") == null)
            connection.addRequestProperty("user-agent",);
        for (Map.Entry<StringList<String>> entry : resolvedHeaders.entries())
        {
            for (String value : entry.getValue())
            {
                connection.addRequestProperty(entry.getKey(),value);
            }
        }
    }
    protected String encode(String value)
    {
        try
        {
            return URLEncoder.encode(value,"UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            throw new ClientException(500,"Error encoding parameter.",e);
        }
    }
    private static class ObjectMapperBuilder
    {
        private final ObjectMapper objectMapper;
        private ObjectMapperBuilder()
        {
             = new ObjectMapper();
        }
        private ObjectMapper getObjectMapper()
        {
            return ;
        }
    }
New to GrepCode? Check out our FAQ X