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.framework.webmvc.WebResult.java

public static IView formatView(String path, String paramFormat, String defaultFormat, String paramCallback,
        WebResult result) {/* w ww.j a  v  a2s. c o m*/
    IView _view = null;
    String _format = StringUtils.defaultIfBlank(WebContext.getRequest().getParameter(paramFormat),
            StringUtils.trimToNull(defaultFormat));
    if (_format != null && result != null) {
        if (BlurObject.bind(WebContext.getContext().getOwner().getOwner().getConfig()
                .getParam(Optional.SYSTEM_ERROR_WITH_CONTENT_TYPE)).toBooleanValue()) {
            result.withContentType();
        }
        if ("json".equalsIgnoreCase(_format)) {
            _view = result.toJSON(StringUtils.trimToNull(WebContext.getRequest().getParameter(paramCallback)));
        } else if ("xml".equalsIgnoreCase(_format)) {
            _view = result.toXML(true);
        }
    }
    if (_view == null) {
        if (StringUtils.isNotBlank(path)) {
            _view = new JspView(path);
            if (result != null) {
                _view.addAttribute("ret", result.code());
                //
                if (StringUtils.isNotBlank(result.msg())) {
                    _view.addAttribute("msg", result.msg());
                }
                if (result.data() != null) {
                    _view.addAttribute("data", result.data());
                }
                for (Map.Entry<String, Object> _entry : result.attrs().entrySet()) {
                    _view.addAttribute(_entry.getKey(), _entry.getValue());
                }
            }
        } else {
            if (result != null && StringUtils.isNotBlank(result.msg())) {
                _view = new HttpStatusView(HttpServletResponse.SC_BAD_REQUEST, result.msg());
            } else {
                _view = new HttpStatusView(HttpServletResponse.SC_BAD_REQUEST);
            }
        }
    }
    return _view;
}

From source file:net.ymate.module.mailsender.impl.DefaultModuleCfg.java

@SuppressWarnings("unchecked")
public DefaultModuleCfg(YMP owner) throws Exception {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IMailSender.MODULE_NAME);
    ////from w  w  w  .  java  2 s .c om
    if ((__mailSendProvider = ClassUtils.impl(_moduleCfgs.get("provider_class"), IMailSendProvider.class,
            this.getClass())) == null) {
        __mailSendProvider = new DefaultMailSendProvider();
    }
    //
    __threadPoolSize = BlurObject.bind(_moduleCfgs.get("thread_pool_size")).toIntValue();
    if (__threadPoolSize <= 0) {
        __threadPoolSize = Runtime.getRuntime().availableProcessors();
    }
    //
    __defaultServerName = StringUtils.defaultIfBlank(_moduleCfgs.get("default_server_name"), "default");
    //
    __templatePath = RuntimeUtils.replaceEnvVariable(
            StringUtils.defaultIfBlank(_moduleCfgs.get("template_path"), "${root}/mail_templates/"));
    //
    String _defaultDisplayName = StringUtils.trimToNull(_moduleCfgs.get("default_display_name"));
    String _defaultFromAddr = StringUtils.trimToNull(_moduleCfgs.get("default_from_addr"));
    boolean _debugEnabled = BlurObject.bind(_moduleCfgs.get("debug_enabled")).toBooleanValue();
    //
    __mailSendServerCfgs = new HashMap<String, MailSendServerCfgMeta>();
    String _serverNameStr = StringUtils.defaultIfBlank(_moduleCfgs.get("server_name_list"), "default");
    if (StringUtils.contains(_serverNameStr, __defaultServerName)) {
        String[] _serverNameList = StringUtils.split(_serverNameStr, "|");
        for (String _serverName : _serverNameList) {
            String _prefix = "server.".concat(_serverName);
            boolean _needAuth = BlurObject.bind(_moduleCfgs.get(_prefix.concat(".need_auth"))).toBooleanValue();
            boolean _tlsEnabled = BlurObject.bind(_moduleCfgs.get(_prefix.concat(".tls_enabled")))
                    .toBooleanValue();
            MailSendServerCfgMeta _meta;
            if (_needAuth) {
                String _smtpPassword = _moduleCfgs.get(_prefix.concat(".smtp_password"));
                if (BlurObject.bind(_moduleCfgs.get(_prefix.concat(".password_encrypted"))).toBooleanValue()) {
                    IPasswordProcessor _processor = ClassUtils.impl(
                            _moduleCfgs.get(_prefix.concat(".password_class")), IPasswordProcessor.class,
                            this.getClass());
                    if (_processor == null) {
                        _processor = owner.getConfig().getDefaultPasswordClass().newInstance();
                    }
                    _smtpPassword = _processor.decrypt(_smtpPassword);
                }
                _meta = new MailSendServerCfgMeta(_serverName, _moduleCfgs.get(_prefix.concat(".smtp_host")),
                        _tlsEnabled, _moduleCfgs.get(_prefix.concat(".smtp_username")), _smtpPassword);
            } else {
                _meta = new MailSendServerCfgMeta(_serverName, _moduleCfgs.get(_prefix.concat(".smtp_host")),
                        _tlsEnabled);
            }
            _meta.setDebugEnabled(_debugEnabled);
            _meta.setDisplayName(StringUtils.defaultIfBlank(_moduleCfgs.get(_prefix.concat(".display_name")),
                    _defaultDisplayName));
            _meta.setFromAddr(StringUtils.defaultIfBlank(_moduleCfgs.get(_prefix.concat(".from_addr")),
                    _defaultFromAddr));
            if (_tlsEnabled) {
                _meta.setSocketFactoryClassName(
                        StringUtils.defaultIfBlank(_moduleCfgs.get(_prefix.concat(".socket_factory_class")),
                                "javax.net.ssl.SSLSocketFactory"));
                _meta.setSocketFactoryFallback(BlurObject
                        .bind(_moduleCfgs.get(_prefix.concat(".socket_factory_fallback"))).toBooleanValue());
            }
            __mailSendServerCfgs.put(_serverName, _meta);
        }
    } else {
        throw new IllegalArgumentException("The default mail server name does not match");
    }
}

From source file:net.ymate.module.mailsender.MailSendServerCfgMeta.java

public Session createIfNeed() {
    if (__mailSession == null) {
        synchronized (this) {
            if (__mailSession == null) {
                Properties _props = new Properties();
                _props.put("mail.smtp.host", smtpHost);
                _props.put("mail.smtp.auth", needAuth);
                _props.put("mail.transport.protocol", "smtp");
                if (tlsEnabled) {
                    _props.put("mail.smtp.starttls.enable", true);
                    _props.put("mail.smtp.socketFactory.port", smtpPort);
                    _props.put("mail.smtp.socketFactory.class", StringUtils
                            .defaultIfBlank(socketFactoryClassName, "javax.net.ssl.SSLSocketFactory"));
                    _props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
                } else {
                    _props.put("mail.smtp.port", smtpPort);
                }//from w  w w . j a v a 2  s  .co m
                //
                __mailSession = Session.getInstance(_props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(smtpUsername, smtpPassword);
                    }
                });
                __mailSession.setDebug(debugEnabled);
            }
        }
    }
    return __mailSession;
}

From source file:net.ymate.module.oauth.connector.AbstractOAuthConnectProcessor.java

public AbstractOAuthConnectProcessor(String clientParamName, String secretParamName, String openIdParamName) {
    __clientParamName = StringUtils.defaultIfBlank(clientParamName, "client_id");
    __secretParamName = StringUtils.defaultIfBlank(secretParamName, "client_secret");
    __openIdParamName = openIdParamName;
}

From source file:net.ymate.module.oauth.connector.AbstractOAuthConnectProcessor.java

protected void __doSetErrorFlag(String errorFlag) {
    __errorFlag = StringUtils.defaultIfBlank(errorFlag, "error");
}

From source file:net.ymate.module.oauth.connector.controller.OAuthConnectController.java

/**
 * @param connectName ??//from www . j  a  v a2 s. c  o  m
 * @param state       ?(CSRF)
 * @return ???URL?
 * @throws Exception ?
 */
@RequestMapping("/{connectName}")
public IView __connect(@PathVariable String connectName, @RequestParam String state) throws Exception {
    IOAuthConnectProcessor _processor = OAuthConnector.get().getConnectProcessor(connectName);
    if (_processor != null) {
        state = StringUtils.defaultIfBlank(state, ParamUtils.createNonceStr());
        IView _view = OAuthConnector.get().getModuleCfg().getConnectCallbackHandler().connect(connectName,
                state);
        //
        if (_view == null) {
            return View.redirectView(_processor.getAuthorizeUrl(state));
        }
        return _view;
    }
    return View.httpStatusView(HttpServletResponse.SC_BAD_REQUEST);
}

From source file:net.ymate.module.sso.controller.SSOTokenController.java

/**
 * <p>/*from  w  ww.  ja  va2  s.c  o  m*/
 * ?SSO?SSO??webmvc.redirect_login_url=sso/authorize?redirect_url=${redirect_url}??????????
 * </p>
 *
 * @param redirectUrl ??URL?
 * @return ???SSO(??)
 * @throws Exception ?
 */
@RequestMapping("/authorize")
@Before(UserSessionStatusInterceptor.class)
public IView __toAuthorize(@RequestParam(Type.Const.REDIRECT_URL) String redirectUrl) throws Exception {
    if (StringUtils.isBlank(redirectUrl) || StringUtils.contains(redirectUrl, "/sso/authorize")) {
        return HttpStatusView.METHOD_NOT_ALLOWED;
    }
    if (UserSessionBean.current() != null) {
        return View.redirectView(redirectUrl);
    }
    //
    if (SSO.get().getModuleCfg().isClientMode()) {
        Map<String, String> _params = new HashMap<String, String>();
        _params.put(Type.Const.REDIRECT_URL, redirectUrl);
        // ???
        return View.redirectView(ParamUtils.appendQueryParamValue(
                SSO.get().getModuleCfg().getServiceBaseUrl().concat("sso/authorize"), _params, true,
                WebContext.getContext().getOwner().getModuleCfg().getDefaultCharsetEncoding()));
    }
    //
    ISSOToken _token = SSO.get().currentToken();
    if (_token != null) {
        Map<String, String> _params = new HashMap<String, String>();
        _params.put(SSO.get().getModuleCfg().getTokenParamName(),
                SSO.get().getModuleCfg().getTokenAdapter().encryptToken(_token));
        // ????redirectUrl??token?
        return View.redirectView(ParamUtils.appendQueryParamValue(redirectUrl, _params, true,
                WebContext.getContext().getOwner().getModuleCfg().getDefaultCharsetEncoding()));
    }
    // ????
    String _redirectUrl = WebUtils
            .buildRedirectURL(null, WebContext.getRequest(),
                    StringUtils.defaultIfBlank(WebContext.getContext().getOwner().getOwner().getConfig()
                            .getParam(Optional.REDIRECT_LOGIN_URL), "login?redirect_url=${redirect_url}"),
                    true);
    _redirectUrl = ExpressionUtils.bind(_redirectUrl)
            .set(Type.Const.REDIRECT_URL, WebUtils.encodeURL(redirectUrl)).getResult();
    return View.redirectView(_redirectUrl);
}

From source file:net.ymate.module.sso.impl.DefaultSSOToken.java

public DefaultSSOToken(String uid, String userAgent, String remoteAddr, long createTime) {
    this();/*from  w w  w .  j  av  a  2 s.c  om*/
    this.uid = uid;
    this.remoteAddr = StringUtils.defaultIfBlank(remoteAddr, WebUtils.getRemoteAddr(WebContext.getRequest()));
    this.userAgent = StringUtils.defaultIfBlank(userAgent, WebContext.getRequest().getHeader("User-Agent"));
    this.createTime = createTime > 0 ? createTime : System.currentTimeMillis();
}

From source file:net.ymate.module.webproxy.impl.DefaultModuleCfg.java

public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWebProxy.MODULE_NAME);
    ////from ww  w .  jav a  2  s  .  co m
    __serviceBaseUrl = _moduleCfgs.get("service_base_url");
    if (StringUtils.isBlank(__serviceBaseUrl)) {
        throw new NullArgumentException("service_base_url");
    }
    if (!StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "http://")
            && !StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "https://")) {
        throw new IllegalArgumentException("Argument service_base_url must be start with http or https");
    } else if (StringUtils.endsWith(__serviceBaseUrl, "/")) {
        __serviceBaseUrl = StringUtils.substringBeforeLast(__serviceBaseUrl, "/");
    }
    //
    __serviceRequestPrefix = StringUtils.trimToEmpty(_moduleCfgs.get("service_request_prefix"));
    if (StringUtils.isNotBlank(__serviceRequestPrefix)
            && !StringUtils.startsWith(__serviceRequestPrefix, "/")) {
        __serviceRequestPrefix = "/" + __serviceRequestPrefix;
    }
    //
    __useProxy = BlurObject.bind(_moduleCfgs.get("use_proxy")).toBooleanValue();
    if (__useProxy) {
        Proxy.Type _proxyType = Proxy.Type
                .valueOf(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_type"), "HTTP").toUpperCase());
        int _proxyPrort = BlurObject.bind(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_port"), "80"))
                .toIntValue();
        String _proxyHost = _moduleCfgs.get("proxy_host");
        if (StringUtils.isBlank(_proxyHost)) {
            throw new NullArgumentException("proxy_host");
        }
        __proxy = new Proxy(_proxyType, new InetSocketAddress(_proxyHost, _proxyPrort));
    }
    //
    __useCaches = BlurObject.bind(_moduleCfgs.get("use_caches")).toBooleanValue();
    __instanceFollowRedirects = BlurObject.bind(_moduleCfgs.get("instance_follow_redirects")).toBooleanValue();
    //
    __connectTimeout = BlurObject.bind(_moduleCfgs.get("connect_timeout")).toIntValue();
    __readTimeout = BlurObject.bind(_moduleCfgs.get("read_timeout")).toIntValue();
    //
    __transferBlackList = Arrays
            .asList(StringUtils.split(StringUtils.trimToEmpty(_moduleCfgs.get("transfer_blacklist")), "|"));
    //
    __transferHeaderEnabled = BlurObject.bind(_moduleCfgs.get("transfer_header_enabled")).toBooleanValue();
    //
    if (__transferHeaderEnabled) {
        String[] _filters = StringUtils
                .split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __transferHeaderWhiteList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_blacklist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderBlackList = Arrays.asList(_filters);
        } else {
            __transferHeaderBlackList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("response_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __responseHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __responseHeaderWhiteList = Collections.emptyList();
        }
    } else {
        __transferHeaderWhiteList = Collections.emptyList();
        __transferHeaderBlackList = Collections.emptyList();
        //
        __responseHeaderWhiteList = Collections.emptyList();
    }
}

From source file:net.ymate.module.webproxy.WebProxy.java

public void init(YMP owner) throws Exception {
    if (!__inited) {
        ///*from  w  w  w .ja va  2s .  c o  m*/
        _LOG.info("Initializing ymate-module-webproxy-" + VERSION);
        //
        __owner = owner;
        __moduleCfg = new DefaultModuleCfg(owner);
        __owner.getEvents().registerEvent(WebProxyEvent.class);
        //
        _LOG.info("-->          service_base_url: " + __moduleCfg.getServiceBaseUrl());
        _LOG.info("-->            request_prefix: "
                + StringUtils.defaultIfBlank(__moduleCfg.getServiceRequestPrefix(), "none"));
        _LOG.info("-->                     proxy: "
                + (__moduleCfg.getProxy() != null ? __moduleCfg.getProxy().toString() : "none"));
        _LOG.info("-->   transfer_header_enabled: " + __moduleCfg.isTransferHeaderEnabled());
        if (__moduleCfg.isTransferHeaderEnabled()) {
            _LOG.info("--> transfer_header_whitelist: " + __moduleCfg.getTransferHeaderWhiteList());
            _LOG.info("--> transfer_header_blacklist: " + __moduleCfg.getTransferHeaderBlackList());
            _LOG.info("--> response_header_whitelist: " + __moduleCfg.getResponseHeaderWhileList());
        }
        _LOG.info("-->                use_caches: " + __moduleCfg.isUseCaches());
        _LOG.info("--> instance_follow_redirects: " + __moduleCfg.isInstanceFollowRedirects());
        _LOG.info("-->        connection_timeout: " + __moduleCfg.getConnectTimeout());
        _LOG.info("-->              read_timeout: " + __moduleCfg.getReadTimeout());
        //
        __inited = true;
    }
}