com.github.dactiv.fear.commons.Apis.java Source code

Java tutorial

Introduction

Here is the source code for com.github.dactiv.fear.commons.Apis.java

Source

/*
 * Copyright 2015 dactiv
 *
 * 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 com.github.dactiv.fear.commons;

import com.github.dactiv.fear.commons.exception.ApiInvokeException;
import com.github.dactiv.fear.commons.result.ApiResult;
import com.github.dactiv.fear.commons.result.support.ErrorApiResult;
import com.github.dactiv.fear.commons.result.support.SimpleApiResult;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.*;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * api 
 *
 * @author maurice
 */
public class Apis implements InitializingBean {

    private final static Logger LOGGER = LoggerFactory.getLogger(Apis.class);

    /**
     * ??
     */
    public static final String DEFAULT_VALUE_NAME = "value";
    /**
     * ??
     */
    public static final String DEFAULT_KEY_NAME = "key";

    // api 
    private static ApiCaller apiCaller;
    // spring 
    private static Environment environment;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     *  api 
     *
     * @param apiCaller api 
     */
    public void setApiCaller(ApiCaller apiCaller) {
        Apis.apiCaller = apiCaller;
    }

    /**
     *  api 
     *
     * @param serviceName ???
     * @param methodName  ??
     * @param params      ?
     * @param <T>         
     * @return 
     */
    @SuppressWarnings("unchecked")
    public static <T> T invoke(String serviceName, String methodName, Object... params) {

        ApiResult apiResult = invokeAndResult(serviceName, methodName, params);

        if (apiResult instanceof ErrorApiResult) {

            ErrorApiResult result = (ErrorApiResult) apiResult;

            if (result.getThrowable() != null) {
                throw new ApiInvokeException(result.getThrowable());
            }

            throw new ApiInvokeException(((ErrorApiResult) apiResult).getMessage());
        }

        try {
            return (T) apiResult.getData();
        } catch (Exception e) {
            throw new ApiInvokeException(e);
        }

    }

    /**
     * ? spring ?
     *
     * @return ?
     */
    public static Environment getEnvironment() {
        return environment;
    }

    /**
     * ????
     *
     * @param code ?
     *
     * @param <T> 
     *
     * @return 
     */
    @SuppressWarnings("unchecked")
    public static <T> T getConfigValue(String code) {
        Object value = null;
        Map<String, Object> data = invoke("configs", "get", code);

        if (MapUtils.isNotEmpty(data)) {
            value = data.get(DEFAULT_VALUE_NAME);
        }

        if (value == null) {
            value = environment.getProperty(code);
        }

        return (T) value;
    }

    /**
     * ???
     *
     * @param code   ?
     *
     * @return key value ? Map ?
     */
    public static List<Map<String, Object>> getConfigList(String code) {
        return invoke("configs", "find", code);
    }

    /**
     * ???
     *
     * @param code   ?
     * @param ignore ?
     *
     * @return key value ? Map ?
     */
    public static List<Map<String, Object>> getConfigList(String code, List<String> ignore) {
        return invoke("configs", "find", code, ignore);
    }

    /**
     * {@link ValueEnum} ?? class ???
     *
     * @param enumClass  class
     *
     * @return key value ? Map ?
     */
    public static List<Map<String, Object>> getConfigList(Class<? extends Enum<? extends ValueEnum<?>>> enumClass) {
        return getConfigList(enumClass, new ArrayList());
    }

    /**
     * {@link ValueEnum} ?? class ???
     *
     * @param enumClass  class
     * @param ignore    ?
     *
     * @return key value ? Map ?
     */
    public static List<Map<String, Object>> getConfigList(Class<? extends Enum<? extends ValueEnum<?>>> enumClass,
            List ignore) {

        List<Map<String, Object>> result = new ArrayList<>();
        Enum<? extends ValueEnum<?>>[] values = enumClass.getEnumConstants();

        for (Enum<? extends ValueEnum<?>> o : values) {
            ValueEnum<?> ve = (ValueEnum<?>) o;
            Object value = ve.getValue();

            if (ignore != null && !ignore.contains(value)) {
                Map<String, Object> dictionary = new LinkedHashMap<>();

                dictionary.put(DEFAULT_VALUE_NAME, value);
                dictionary.put(DEFAULT_KEY_NAME, ve.getName());

                result.add(dictionary);
            }

        }

        return result;
    }

    /**
     *  api  api 
     *
     * @param serviceName ???
     * @param methodName  ??
     * @param params      ?
     * @return api 
     */
    public static ApiResult invokeAndResult(String serviceName, String methodName, Object... params) {
        return apiCaller.invoke(serviceName, methodName, params);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        PropertySourcesPlaceholderConfigurer configurer = null;
        PropertySources propertySources = null;
        try {
            configurer = applicationContext.getBean(PropertySourcesPlaceholderConfigurer.class);
            propertySources = configurer.getAppliedPropertySources();
        } catch (Exception e) {
            LOGGER.warn("install " + PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME
                    + " error", e);
        }

        if (propertySources == null) {
            return;
        }

        Field field = ReflectionUtils.findField(configurer.getClass(), "environment");
        field.setAccessible(Boolean.TRUE);
        environment = (Environment) field.get(configurer);
        if (environment instanceof ConfigurableEnvironment) {
            ConfigurableEnvironment ce = (ConfigurableEnvironment) environment;
            MutablePropertySources sources = ce.getPropertySources();
            PropertySource<?> ps = propertySources
                    .get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME);
            sources.addFirst(ps);
        }
    }
}