ca.tokenize.sally.api.SallyService.java Source code

Java tutorial

Introduction

Here is the source code for ca.tokenize.sally.api.SallyService.java

Source

/*
 * Copyright (C) 2014  Mike Farr
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ca.tokenize.sally.api;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;

import java.util.Date;

public class SallyService {

    public static SallyApi getService(String baseUrl) {
        return SallyService.getService(baseUrl, null);
    }

    public static SallyApi getService(String baseUrl, String authToken) {
        return buildService(baseUrl, authToken, SallyApi.class);
    }

    private static <T> T buildService(String baseUrl, String authToken, Class<T> service) {
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .registerTypeAdapter(Date.class, new DateDeserializer()).create();

        AuthInterceptor interceptor = new AuthInterceptor(authToken);

        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(baseUrl)
                .setConverter(new GsonConverter(gson)).setRequestInterceptor(interceptor)
                .setErrorHandler(new SallyErrorHandler()).build();

        return restAdapter.create(service);
    }
}