<commit_before>package com.chinamobile.iot.onenet;

import android.app.Application;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.chinamobile.iot.onenet.http.HttpExecutor;
import com.chinamobile.iot.onenet.http.Urls;
import com.chinamobile.iot.onenet.module.ApiKey;
import com.chinamobile.iot.onenet.module.Binary;
import com.chinamobile.iot.onenet.module.Command;
import com.chinamobile.iot.onenet.module.DataPoint;
import com.chinamobile.iot.onenet.module.DataStream;
import com.chinamobile.iot.onenet.module.Device;
import com.chinamobile.iot.onenet.module.Mqtt;
import com.chinamobile.iot.onenet.module.Trigger;
import com.chinamobile.iot.onenet.util.Assertions;
import com.chinamobile.iot.onenet.util.Meta;
import com.chinamobile.iot.onenet.util.OneNetLogger;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class OneNetApi {

    public static final String LOG_TAG = "OneNetApi";

    private static String sAppKey;
    static boolean sDebug;
    private static HttpExecutor sHttpExecutor;

    public static void init(Application application, boolean debug) {
        try {
            sAppKey = Meta.readAppKey(application);
            Urls.sHost = Meta.readHost(application);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sDebug = debug;
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        if (sDebug) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new OneNetLogger());
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClientBuilder.addNetworkInterceptor(loggingInterceptor);
        }
        okHttpClientBuilder.addInterceptor(sApiKeyInterceptor);
        sHttpExecutor = new HttpExecutor(okHttpClientBuilder.build());
    }

    private static Interceptor sApiKeyInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("api-key", sAppKey);
            if (TextUtils.isEmpty(sAppKey)) {
                Log.e(LOG_TAG, "APP-KEY is messing, please config in the meta-data or call setAppKey()");
            }
            return chain.proceed(builder.build());
        }
    };

    public static void setAppKey(String apiKey) {
        sAppKey = apiKey;
    }

    public static String getAppKey() {
        return sAppKey;
    }

    private static boolean isInitialized() {
        return sHttpExecutor != null;
    }

    private static boolean isOnUIThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    private static boolean isUrlConfigured() {
        return !TextUtils.isEmpty(Urls.sHost) && !Urls.sHost.contains(" ");
    }

    private static void assertInitialized() {
        Assertions.assertCondition(isInitialized(), "You should call OneNetApi.init() in your Application!");
    }

    private static void assertUIThread() {
        Assertions.assertCondition(isOnUIThread(), "Expected to run on UI thread!");
    }

    private static void assertUrlConfigured() {
        Assertions.assertCondition(isUrlConfigured(), "HOST must be configured in AndroidManifest.xml!");
    }

    public static void get(String url, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        sHttpExecutor.get(url, new OneNetApiCallbackAdapter(callback));
    }

    public static void post(String url, String requestBodyString, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBodyString);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    public static void post(String url, File file, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    public static void post(String url, byte[] content, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), content);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    public static void put(String url, String requestBodyString, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBodyString);
        sHttpExecutor.put(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    public static void delete(String url, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        sHttpExecutor.delete(url, new OneNetApiCallbackAdapter(callback));
    }

    /******************** 设备相关api ********************/

    /**
     * 注册设备（该方法用于让设备终端自己在平台创建设备，不适用于APP）
     *
     * @param registerCode      设备注册码
     * @param requestBodyString HTTP内容 详见<a href="http://www.heclouds.com/doc/art262.html#68">
     *                          http://www.heclouds.com/doc/art262.html#68</a>
     * @param callback          回调接口对象
     */
    public static void registerDevice(String registerCode, String requestBodyString, OneNetApiCallback callback) {
        post(Device.urlForRegistering(registerCode), requestBodyString, callback);
    }

    /**
     * 新增设备
     *
     * @param requestBodyString HTTP内容 详见<a href="http://www.heclouds.com/doc/art262.html#68">
     *                          http://www.heclouds.com/doc/art262.html#68</a><commit_msg>add comments<commit_after>package com.chinamobile.iot.onenet;

import android.app.Application;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.chinamobile.iot.onenet.http.HttpExecutor;
import com.chinamobile.iot.onenet.http.Urls;
import com.chinamobile.iot.onenet.module.ApiKey;
import com.chinamobile.iot.onenet.module.Binary;
import com.chinamobile.iot.onenet.module.Command;
import com.chinamobile.iot.onenet.module.DataPoint;
import com.chinamobile.iot.onenet.module.DataStream;
import com.chinamobile.iot.onenet.module.Device;
import com.chinamobile.iot.onenet.module.Mqtt;
import com.chinamobile.iot.onenet.module.Trigger;
import com.chinamobile.iot.onenet.util.Assertions;
import com.chinamobile.iot.onenet.util.Meta;
import com.chinamobile.iot.onenet.util.OneNetLogger;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class OneNetApi {

    public static final String LOG_TAG = "OneNetApi";

    private static String sAppKey;

    static boolean sDebug;

    private static HttpExecutor sHttpExecutor;

    /**
     * 初始化SDK
     *
     * @param application
     * @param debug       是否开启调试模式（打印HTTP请求和响应日志）
     */
    public static void init(Application application, boolean debug) {
        try {
            sAppKey = Meta.readAppKey(application);
            Urls.sHost = Meta.readHost(application);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sDebug = debug;
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        if (sDebug) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new OneNetLogger());
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClientBuilder.addNetworkInterceptor(loggingInterceptor);
        }
        okHttpClientBuilder.addInterceptor(sApiKeyInterceptor);
        sHttpExecutor = new HttpExecutor(okHttpClientBuilder.build());
    }

    private static Interceptor sApiKeyInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("api-key", sAppKey);
            if (TextUtils.isEmpty(sAppKey)) {
                Log.e(LOG_TAG, "APP-KEY is messing, please config in the meta-data or call setAppKey()");
            }
            return chain.proceed(builder.build());
        }
    };

    /**
     * 设置产品ApiKey
     *
     * @param apiKey
     */
    public static void setAppKey(String apiKey) {
        sAppKey = apiKey;
    }

    /**
     * 获取产品ApiKey
     *
     * @return
     */
    public static String getAppKey() {
        return sAppKey;
    }

    private static boolean isInitialized() {
        return sHttpExecutor != null;
    }

    private static boolean isOnUIThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    private static boolean isUrlConfigured() {
        return !TextUtils.isEmpty(Urls.sHost) && !Urls.sHost.contains(" ");
    }

    private static void assertInitialized() {
        Assertions.assertCondition(isInitialized(), "You should call OneNetApi.init() in your Application!");
    }

    private static void assertUIThread() {
        Assertions.assertCondition(isOnUIThread(), "Expected to run on UI thread!");
    }

    private static void assertUrlConfigured() {
        Assertions.assertCondition(isUrlConfigured(), "HOST must be configured in AndroidManifest.xml!");
    }

    /**
     * HTTP GET method
     *
     * @param url
     * @param callback
     */
    public static void get(String url, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        sHttpExecutor.get(url, new OneNetApiCallbackAdapter(callback));
    }

    /**
     * HTTP POST method
     *
     * @param url
     * @param requestBodyString
     * @param callback
     */
    public static void post(String url, String requestBodyString, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBodyString);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    /**
     * HTTP POST method
     *
     * @param url
     * @param file
     * @param callback
     */
    public static void post(String url, File file, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    /**
     * HTTP POST method
     *
     * @param url
     * @param content
     * @param callback
     */
    public static void post(String url, byte[] content, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), content);
        sHttpExecutor.post(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    /**
     * HTTP PUT method
     *
     * @param url
     * @param requestBodyString
     * @param callback
     */
    public static void put(String url, String requestBodyString, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBodyString);
        sHttpExecutor.put(url, requestBody, new OneNetApiCallbackAdapter(callback));
    }

    /**
     * HTTP DELETE method
     *
     * @param url
     * @param callback
     */
    public static void delete(String url, OneNetApiCallback callback) {
        assertInitialized();
        assertUIThread();
        assertUrlConfigured();
        sHttpExecutor.delete(url, new OneNetApiCallbackAdapter(callback));
    }

    /******************** 设备相关api ********************/

    /**
     * 注册设备（该方法用于让设备终端自己在平台创建设备，不适用于APP）
     *
     * @param registerCode      设备注册码
     * @param requestBodyString HTTP内容 详见<a href="http://www.heclouds.com/doc/art262.html#68">
     *                          http://www.heclouds.com/doc/art262.html#68</a>
     * @param callback          回调接口对象
     */
    public static void registerDevice(String registerCode, String requestBodyString, OneNetApiCallback callback) {
        post(Device.urlForRegistering(registerCode), requestBodyString, callback);
    }

    /**
     * 新增设备
     *
     * @param requestBodyString HTTP内容 详见<a href="http://www.heclouds.com/doc/art262.html#68">
     *                          http://www.heclouds.com/doc/art262.html#68</a>
{'fraction_non_alphanumeric': 0.10677179279345664, 'fraction_numerical': 0.00427381917323705, 'mean_word_length': 3.0586124401913874, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 8, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3956425', 'n_tokens_mistral': 3968, 'n_tokens_neox': 3891, 'n_words': 769}