Example usage for org.apache.commons.lang StringUtils defaultIfBlank

List of usage examples for org.apache.commons.lang StringUtils defaultIfBlank

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultIfBlank.

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is whitespace, empty ("") or null, the value of defaultStr.

Usage

From source file:net.ymate.platform.cache.impl.DefaultModuleCfg.java

public DefaultModuleCfg(YMP owner) throws Exception {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(ICaches.MODULE_NAME);
    ////  ww w. j a  v  a  2  s .c om
    String _providerClassStr = StringUtils.defaultIfBlank(_moduleCfgs.get("provider_class"), "default");
    __cacheProvider = ClassUtils.impl(
            StringUtils.defaultIfBlank(Caches.PROVIDERS.get(_providerClassStr), _providerClassStr),
            ICacheProvider.class, this.getClass());
    if (__cacheProvider == null) {
        __cacheProvider = new DefaultCacheProvider();
    }
    //
    __cacheEventListener = ClassUtils.impl(_moduleCfgs.get("event_listener_class"), ICacheEventListener.class,
            this.getClass());
    //
    __cacheScopeProcessor = ClassUtils.impl(_moduleCfgs.get("scope_processor_class"),
            ICacheScopeProcessor.class, this.getClass());
    //
    __serializer = ClassUtils.impl(_moduleCfgs.get("serializer_class"), ISerializer.class, this.getClass());
    if (__serializer == null) {
        __serializer = new DefaultSerializer();
    }
    //
    __keyGenerator = ClassUtils.impl(_moduleCfgs.get("key_generator_class"), IKeyGenerator.class,
            this.getClass());
    if (__keyGenerator == null) {
        __keyGenerator = new DefaultKeyGenerator();
    }
    __keyGenerator.init(__serializer);
    //
    __defaultCacheName = StringUtils.defaultIfBlank(_moduleCfgs.get("default_cache_name"), "default");

    __defaultCacheTimeout = BlurObject
            .bind(StringUtils.defaultIfBlank(_moduleCfgs.get("default_cache_timeout"), "0")).toIntValue();
    if (__defaultCacheTimeout <= 0) {
        __defaultCacheTimeout = 300;
    }
}

From source file:net.ymate.platform.configuration.Cfgs.java

public void init(YMP owner) throws Exception {
    if (!__inited) {
        //// w  w  w . j  a v  a  2  s  .c o  m
        _LOG.info("Initializing ymate-platform-configuration-" + VERSION);
        //
        __owner = owner;
        __moduleCfg = new DefaultModuleCfg(__owner);
        //
        __owner.registerHandler(Configuration.class, new ConfigHandler(this));
        //
        __configHome = __moduleCfg.getConfigHome();
        if (StringUtils.isBlank(__configHome)) {
            // ???????CONFIG_HOME?
            __configHome = StringUtils.defaultIfBlank(System.getenv(__CONFIG_HOME),
                    RuntimeUtils.getSystemEnv(__CONFIG_HOME));
        }
        //
        if (StringUtils.isNotBlank(__configHome)) {
            __configHome = StringUtils.replace(__configHome, "%20", " ");
            File _configHomeFile = new File(__configHome);
            if (_configHomeFile.exists() && _configHomeFile.isDirectory()) {
                System.setProperty(__USER_DIR, __configHome = _configHomeFile.getPath());
                // ?configHome?
                if (StringUtils.isNotBlank(__moduleCfg.getProjectName())) {
                    System.setProperty(__USER_DIR, __projectHome = new File(__configHome,
                            __PROJECTS_FOLDER_NAME.concat(File.separator).concat(__moduleCfg.getProjectName()))
                                    .getPath());
                    // projectHome??
                    if (StringUtils.isNotBlank(__moduleCfg.getModuleName())) {
                        System.setProperty(__USER_DIR,
                                __moduleHome = new File(__projectHome, __MODULES_FOLDER_NAME
                                        .concat(File.separator).concat(__moduleCfg.getModuleName())).getPath());
                    }
                }
                __userHome = System.getProperty(__USER_HOME, "");
                __userDir = System.getProperty(__USER_DIR, "");
                //
                __inited = true;
                //
                _LOG.info("-->  CONFIG_HOME: " + __configHome);
                _LOG.info("-->    USER_HOME: " + __userHome);
                _LOG.info("-->     USER_DIR: " + __userDir);
                if (StringUtils.isNotBlank(__moduleCfg.getProjectName())) {
                    _LOG.info("--> PROJECT_NAME: " + __moduleCfg.getProjectName());
                }
                if (StringUtils.isNotBlank(__moduleCfg.getModuleName())) {
                    _LOG.info("-->  MODULE_NAME: " + __moduleCfg.getModuleName());
                }
            }
        }
        if (!__inited) {
            throw new IllegalArgumentException(
                    "The parameter CONFIG_HOME is invalid or is not a directory path");
        }
    }
}

From source file:net.ymate.platform.core.beans.support.PropertyStateSupport.java

public PropertyStateSupport(T source) throws Exception {
    __source = source;//from   w ww  . j  a  v  a  2  s . com
    __targetClass = source.getClass();
    __stateMetas = new ArrayList<PropertyStateMeta>();
    __propertyStates = new HashMap<String, PropertyStateMeta>();
    //
    ClassUtils.BeanWrapper<T> _wrapper = ClassUtils.wrapper(source);
    for (String _fieldName : _wrapper.getFieldNames()) {
        PropertyState _state = _wrapper.getField(_fieldName).getAnnotation(PropertyState.class);
        if (_state != null) {
            PropertyStateMeta _stateMeta = new PropertyStateMeta(
                    StringUtils.defaultIfBlank(_state.propertyName(), _fieldName), _state.aliasName(),
                    _wrapper.getValue(_fieldName));
            __stateMetas.add(_stateMeta);
            __propertyStates.put("set" + StringUtils.capitalize(_fieldName), _stateMeta);
            if (StringUtils.isNotBlank(_state.setterName())) {
                __propertyStates.put(_state.setterName(), _stateMeta);
            }
        }
    }
}

From source file:net.ymate.platform.core.event.impl.DefaultEventConfig.java

public DefaultEventConfig(Map<String, String> params) {
    if (params != null) {
        __params = params;/*from   w  ww. ja  va2  s . c  o  m*/
    } else {
        __params = Collections.emptyMap();
    }
    //
    __eventProvider = ClassUtils.impl(params != null ? params.get("provider_class") : null,
            IEventProvider.class, this.getClass());
    if (__eventProvider == null) {
        __eventProvider = new DefaultEventProvider();
    }
    //
    __defaultMode = Events.MODE.valueOf(StringUtils
            .defaultIfBlank(params != null ? params.get("default_mode") : null, "ASYNC").toUpperCase());
    //
    __threadPoolSize = BlurObject.bind(params != null ? params.get("thread_pool_size") : null).toIntValue();
    if (__threadPoolSize <= 0) {
        __threadPoolSize = Runtime.getRuntime().availableProcessors();
    }
}

From source file:net.ymate.platform.log.impl.DefaultLogger.java

public synchronized ILogger init(ILog owner, String loggerName) throws Exception {
    if (!__inited) {
        __owner = owner;//  w  w w.  j  ava  2s .com
        __loggerName = loggerName;
        //
        if (!__logInited) {
            ConfigurationSource _source = new ConfigurationSource(
                    new FileInputStream(__owner.getModuleCfg().getConfigFile()));
            Configurator.initialize(null, _source);
            final Configuration _config = new DefaultConfiguration();
            ConfigurationFactory.setConfigurationFactory(new XmlConfigurationFactory() {
                public Configuration getConfiguration(ConfigurationSource source) {
                    return _config;
                }
            });
            ConfigurationFactory.getInstance().getConfiguration(_source);
            __logInited = true;
        }
        __logger = LogManager
                .getLogger(StringUtils.defaultIfBlank(loggerName, __owner.getModuleCfg().getLoggerName()));
        __inited = true;
    }
    return this;
}

From source file:net.ymate.platform.log.impl.DefaultModuleCfg.java

@SuppressWarnings("unchecked")
public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(ILog.MODULE_NAME);
    //// w  w w  .ja  va2  s. co m
    String _cfgsClassName = "net.ymate.platform.configuration.Cfgs";
    if (!owner.getConfig().getExcludedModules().contains("configuration")
            && !owner.getConfig().getExcludedModules().contains(_cfgsClassName)) {
        try {
            // ????
            owner.getModule((Class<? extends IModule>) ClassUtils.loadClass(_cfgsClassName, this.getClass()));
        } catch (Exception ignored) {
        }
    }
    //
    this.configFile = new File(RuntimeUtils.replaceEnvVariable(
            StringUtils.defaultIfBlank(_moduleCfgs.get("config_file"), "${root}/cfgs/log4j.xml")));
    if (!this.configFile.isAbsolute() || !this.configFile.exists() || this.configFile.isDirectory()
            || !this.configFile.canRead()) {
        throw new IllegalArgumentException("The parameter configFile is invalid or is not a file");
    }
    //
    this.outputDir = new File(RuntimeUtils
            .replaceEnvVariable(StringUtils.defaultIfBlank(_moduleCfgs.get("output_dir"), "${root}/logs/")));
    if (!this.outputDir.isAbsolute() || !this.outputDir.exists() || !this.outputDir.isDirectory()
            || !this.outputDir.canRead()) {
        throw new IllegalArgumentException("The parameter outputDir is invalid or is not a directory");
    }
    //
    this.loggerName = StringUtils.defaultIfBlank(_moduleCfgs.get("logger_name"), "default").trim();
    //
    try {
        if (StringUtils.isNotBlank(_moduleCfgs.get("logger_class"))) {
            this.loggerClass = (Class<? extends ILogger>) ClassUtils.loadClass(_moduleCfgs.get("logger_class"),
                    this.getClass());
        } else {
            this.loggerClass = DefaultLogger.class;
        }
    } catch (Exception e) {
        this.loggerClass = DefaultLogger.class;
    }
    //
    this.allowOutputConsole = new BlurObject(_moduleCfgs.get("allow_output_console")).toBooleanValue();
}

From source file:net.ymate.platform.mvc.web.view.impl.BinaryView.java

protected void renderView() throws Exception {
    HttpServletResponse response = WebContext.getResponse();
    HttpServletRequest request = WebContext.getRequest();
    ///*from w w w. j  ava 2  s .  c o m*/
    response.setContentType(StringUtils.defaultIfBlank(getContentType(), "application/octet-stream"));
    //
    if (StringUtils.isNotBlank(fileName)) {
        StringBuilder _dispositionSB = new StringBuilder("attachment;filename=");
        if (request.getHeader("User-Agent").toLowerCase().contains("firefox")) {
            _dispositionSB.append(new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        } else {
            _dispositionSB.append(URLEncoder.encode(fileName, "UTF-8"));
        }
        response.setHeader("Content-Disposition", _dispositionSB.toString());
    }
    //
    if (this.data == null) {
        return;
    }
    // 
    if (this.data instanceof File) {
        // ??
        maxLength = ((File) this.data).length();
        // ?Range??
        PairObject<Long, Long> _rangePO = __doParseRange(maxLength);
        // 
        if (_rangePO != null) {
            __doSetRangeHeader(request, response, _rangePO);
            // ?
            IOUtils.copyLarge(new FileInputStream((File) this.data), response.getOutputStream(),
                    _rangePO.getKey(), _rangePO.getValue());
        } else {
            // 
            response.setContentLength(
                    (int) IOUtils.copyLarge(new FileInputStream((File) this.data), response.getOutputStream()));
        }
    }
    // 
    else if (this.data instanceof byte[]) {
        byte[] _datas = (byte[]) this.data;
        IOUtils.write(_datas, response.getOutputStream());
        response.setContentLength(_datas.length);
    }
    // 
    else if (this.data instanceof char[]) {
        char[] _datas = (char[]) this.data;
        IOUtils.write(_datas, response.getOutputStream());
        response.setContentLength(_datas.length);
    }
    // ?
    else if (this.data instanceof Reader) {
        Reader r = (Reader) this.data;
        IOUtils.copy(r, response.getOutputStream());
    }
    // ?
    else if (this.data instanceof InputStream) {
        PairObject<Long, Long> _rangePO = __doParseRange(maxLength);
        if (_rangePO != null) {
            __doSetRangeHeader(request, response, _rangePO);
            IOUtils.copyLarge((InputStream) this.data, response.getOutputStream(), _rangePO.getKey(),
                    _rangePO.getValue());
        } else {
            response.setContentLength(
                    (int) IOUtils.copyLarge((InputStream) this.data, response.getOutputStream()));
        }
    }
    // 
    else {
        IOUtils.write(String.valueOf(data), response.getOutputStream());
    }
}

From source file:net.ymate.platform.persistence.base.EntityMeta.java

/**
 * @param targetClass /*from  w  w w  .  j  av  a 2s  .com*/
 * @return ???
 */
public static EntityMeta createAndGet(Class<? extends IEntity> targetClass) {
    EntityMeta _returnMeta = __entityMetas.get(targetClass);
    if (_returnMeta == null) {
        // clazz?@Entity
        if (ClassUtils.isAnnotationOf(targetClass, Entity.class)) {
            _returnMeta = new EntityMeta(
                    StringUtils.defaultIfBlank(targetClass.getAnnotation(Entity.class).value(),
                            fieldNameToPropertyName(targetClass.getSimpleName(), 0)),
                    targetClass.getAnnotation(ShardingRule.class));
            // clazz?@Comment
            if (ClassUtils.isAnnotationOf(targetClass, Comment.class)) {
                _returnMeta.__comment = targetClass.getAnnotation(Comment.class).value();
            }
            // ?
            __doParseProperties(targetClass, _returnMeta);
            // ?
            __doParsePrimaryKeys(targetClass, _returnMeta);
            // ?
            __doParseIndexes(targetClass, _returnMeta);
            // ?
            __entityMetas.put(targetClass, _returnMeta);
        }
    }
    return _returnMeta;
}

From source file:net.ymate.platform.persistence.base.EntityMeta.java

private static PropertyMeta __doGetPropertyMeta(Property property, Field field, EntityMeta targetMeta) {
    PropertyMeta _meta = null;/*from   www  . j a v  a2  s.  c o m*/
    // ??Field
    String _propName = StringUtils.defaultIfBlank(property.name(), fieldNameToPropertyName(field.getName(), 0));
    if (!targetMeta.containsProperty(_propName)) {
        field.setAccessible(true);
        _meta = new PropertyMeta(_propName, field, property.autoincrement(), property.sequenceName(),
                property.nullable(), property.unsigned(), property.length(), property.decimals(),
                property.type());
        if (ClassUtils.isAnnotationOf(field, Default.class)) {
            _meta.setDefaultValue(field.getAnnotation(Default.class).value());
        }
        if (ClassUtils.isAnnotationOf(field, Comment.class)) {
            _meta.setComment(field.getAnnotation(Comment.class).value());
        }
        if (ClassUtils.isAnnotationOf(field, Readonly.class)) {
            _meta.setReadonly(true);
            targetMeta.__readonlyProps.add(_meta.getName());
        }
        if (_meta.isAutoincrement()) {
            targetMeta.__autoincrementProps.add(_meta.getName());
        }
    }
    return _meta;
}

From source file:net.ymate.platform.persistence.jdbc.base.AbstractOperator.java

public void execute() throws Exception {
    if (!this.executed) {
        StopWatch _time = new StopWatch();
        _time.start();// w  w w .j a  v  a 2  s.  c o m
        int _effectCounts = 0;
        try {
            _effectCounts = __doExecute();
            // ?????
            this.executed = true;
        } finally {
            _time.stop();
            this.expenseTime = _time.getTime();
            //
            if (this.connectionHolder.getDataSourceCfgMeta().isShowSQL()) {
                _LOG.info(ExpressionUtils.bind("[${sql}]${param}[${count}][${time}]")
                        .set("sql", StringUtils.defaultIfBlank(this.sql, "@NULL"))
                        .set("param", __doSerializeParameters()).set("count", _effectCounts + "")
                        .set("time", this.expenseTime + "ms").getResult());
            }
        }
    }
}