luki.x.XConfig.java Source code

Java tutorial

Introduction

Here is the source code for luki.x.XConfig.java

Source

/**
 * Copyright (C) 2014 Luki(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package luki.x;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map;

import luki.x.base.IAttachDataListener;
import luki.x.base.IDataParser;
import luki.x.base.INetEngine;
import luki.x.base.IParser;
import luki.x.base.XLog;
import luki.x.util.CacheUtil;
import luki.x.util.NetStatusUtils;

import org.apache.http.Header;

import android.content.Context;
import android.view.WindowManager;

/**
 * Presents configuration for {@link XParser}
 * 
 * @author Luki
 * @see XParser
 * @see luki.x.base.IAttachDataListener
 * @see luki.x.base.IParser
 * @see luki.x.base.INetEngine
 * @since 1.1.1
 */
public class XConfig {
    public static int HOLDER_KEY = -1;
    public static int HOLDER_POSITION = -1;
    public static int HOLDER_PARSER_KEY = -1;
    private static String[] TAG_KEY_CLASS = new String[] { ".R$layout", ".R$id", ".R$color", ".R$style",
            ".R$drawable", ".R$string", ".R$raw", ".R$attr", ".R$array", ".R$styleable" };
    private static int tagKeyPos;

    public static int SCREEN_WIDTH;
    public static Context sContext;
    private boolean writeLogs;
    Map<String, String> requestExtras;
    Type errorType;
    Header[] requestHeaders;
    IParser userParser;
    IAttachDataListener attachListener;
    INetEngine netEngine;
    boolean cacheInDB;
    int timeout;
    int times;
    IDataParser dataParser;

    /**
     * Builder for {@link XConfig}
     * 
     * @author Luki
     */
    public static class Builder {
        private Context context;
        private boolean writeLogs;
        private Map<String, String> requestExtras;
        private Type errorType;
        private boolean cacheInDB = true;
        private Header[] requestHeaders;
        private IParser userParser;
        private IAttachDataListener attachListener;
        private INetEngine netEngine;
        private int timeout = 15 * 1000;
        private int times = 1;
        private IDataParser dataParser;

        public Builder(Context context) {
            this.context = context.getApplicationContext();
        }

        /**
         * Enables detail logging of {@link XParser} work. To prevent detail logs don't call this method.
         * Consider {@link luki.x.base.XLog#disableLogging()} to disable XParser logging completely (even error logs)
         */
        public Builder writeDebugLogs() {
            this.writeLogs = true;
            return this;
        }

        /** Additional parameters for each request */
        public Builder requestExtras(Map<String, String> extras) {
            this.requestExtras = extras;
            return this;
        }

        /** It' will be used this analysis when parsing failed */
        public Builder errorType(Type errorType) {
            this.errorType = errorType;
            return this;
        }

        /**
         * True, cache in the inside of the DB but efficiency low. False, cache in the inside of the File but efficiency
         * high
         */
        public Builder cacheInDB(boolean cacheInDB) {
            this.cacheInDB = cacheInDB;
            return this;
        }

        /**
         * request header
         */
        public Builder requestHeaders(Header[] headers) {
            this.requestHeaders = headers;
            return this;
        }

        /**
         * Set up your own parser
         */
        public Builder userParser(IParser parser) {
            this.userParser = parser;
            return this;
        }

        /**
         * Set up your own data attach listener.
         */
        public Builder attachListener(IAttachDataListener l) {
            this.attachListener = l;
            return this;
        }

        /**
         * Set up your own net engine.
         */
        public Builder netEngine(INetEngine engine) {
            this.netEngine = engine;
            return this;
        }

        /**
         * Set up task timeout. Default is 15 sec.
         */
        public Builder taskTimeout(int timeout) {
            this.timeout = timeout;
            return this;
        }

        /**
         * Set up task retry times. Default is 2.
         */
        public Builder taskRetryTimes(int times) {
            this.times = times;
            return this;
        }

        public Builder taskDataParser(IDataParser dataParser) {
            this.dataParser = dataParser;
            return this;
        }

        /** Builds configured {@link XConfig} object */
        public XConfig build() {
            check();
            return new XConfig(this);
        }

        /**
         * 
         */
        private void check() {
            if (dataParser == null) {
                throw new IllegalArgumentException("DataParser can't be null");
            }
        }

    }

    /**
     * create default config.
     * 
     * @param context
     * @return
     */
    public static XConfig createDefaultConfig(Context context) {
        return new Builder(context).build();
    }

    private XConfig(final Builder builder) {
        sContext = builder.context;
        this.writeLogs = builder.writeLogs;
        this.requestExtras = builder.requestExtras;
        this.errorType = builder.errorType;
        this.cacheInDB = builder.cacheInDB;
        this.requestHeaders = builder.requestHeaders;
        this.userParser = builder.userParser;
        this.attachListener = builder.attachListener;
        this.netEngine = builder.netEngine;
        this.timeout = builder.timeout;
        this.times = builder.times;
        this.dataParser = builder.dataParser;

        if (writeLogs) {
            XLog.enableLogging();
        } else
            XLog.disableLogging();
        init(sContext);
    }

    private void init(Context context) {
        CacheUtil.init(context);
        NetStatusUtils.init(context);
        if (HOLDER_POSITION == -1) {
            initTagKey(context, TAG_KEY_CLASS[tagKeyPos++]);
        }
    }

    @SuppressWarnings("deprecation")
    private void initTagKey(Context context, String name) {
        try {
            sContext = context.getApplicationContext();
            WindowManager wm = (WindowManager) sContext.getSystemService(Context.WINDOW_SERVICE);
            SCREEN_WIDTH = wm.getDefaultDisplay().getWidth();

            Class<?> clazz = Class.forName(sContext.getPackageName() + name);
            Object obj = clazz.newInstance();
            Field[] s = clazz.getDeclaredFields();
            HOLDER_KEY = s[0].getInt(obj);
            HOLDER_POSITION = s[1].getInt(obj);
        } catch (Exception e) {
            try {
                initTagKey(sContext, TAG_KEY_CLASS[tagKeyPos++]);
            } catch (Exception e1) {
                XLog.e("InjectAdapter", "you should have at least two same resource type in 'res'.");
            }
        }
    }
}