Java Code Examples for org.apache.commons.lang.StringUtils.trimToNull()

The following are Jave code examples for showing how to use trimToNull() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: airsonic   File: HttpRange.java   View Source Code Vote up 6 votes
/**
 * Parses the given string as a HTTP header byte range.  See chapter 14.36.1 in RFC 2068
 * for details.
 * <p/>
 * Only a subset of the allowed syntaxes are supported. Only ranges which specify first-byte-pos
 * are supported. The last-byte-pos is optional.
 *
 * @param range The range from the HTTP header, for instance "bytes=0-499" or "bytes=500-"
 * @return A range object (using inclusive values). If the last-byte-pos is not given, the end of
 *         the returned range is {@code null}. The method returns <code>null</code> if the syntax
 *         of the given range is not supported.
 */
public static HttpRange valueOf(String range) {
    if (range == null) {
        return null;
    }

    Matcher matcher = PATTERN.matcher(range);
    if (matcher.matches()) {
        String firstString = matcher.group(1);
        String lastString = StringUtils.trimToNull(matcher.group(2));

        Long first = Long.parseLong(firstString);
        Long last = lastString == null ? null : Long.parseLong(lastString);

        if (last != null && first > last) {
            return null;
        }
        return new HttpRange(first, last);
    }
    return null;
}
 
Example 2
Project: airsonic   File: PodcastService.java   View Source Code Vote up 6 votes
private String getITunesAttribute(Element element, String childName, String attributeName) {
    for (Namespace ns : ITUNES_NAMESPACES) {
        Element elem = element.getChild(childName, ns);
        if (elem != null) {
            return StringUtils.trimToNull(elem.getAttributeValue(attributeName));
        }
    }
    return null;
}
 
Example 3
Project: Spring-Boot-Server   File: DES.java   View Source Code Vote up 6 votes
/**
* 加密
* @param datasource byte[]
* @param password String
* @return byte[]
*/
public static String encrypt(String datasource, String password) {
	try {
		if(StringUtils.trimToNull(datasource) == null){
			return null;
		}
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		// 创建一个密匙工厂,然后用它把DESKeySpec转换成
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(desKey);
		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
		// 现在,获取数据并加密
		// 正式执行加密操作
		 return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes()));
		
	} catch (Throwable e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 4
Project: airsonic   File: LyricsService.java   View Source Code Vote up 6 votes
private LyricsInfo parseSearchResult(String xml) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new StringReader(xml));

    Element root = document.getRootElement();
    Namespace ns = root.getNamespace();

    String lyric = StringUtils.trimToNull(root.getChildText("Lyric", ns));
    String song =  root.getChildText("LyricSong", ns);
    String artist =  root.getChildText("LyricArtist", ns);

    return new LyricsInfo(lyric, artist, song);
}
 
Example 5
Project: airsonic   File: LastFmService.java   View Source Code Vote up 6 votes
private String processWikiText(String text) {
    /*
     System of a Down is an Armenian American <a href="http://www.last.fm/tag/alternative%20metal" class="bbcode_tag" rel="tag">alternative metal</a> band,
     formed in 1994 in Los Angeles, California, USA. All four members are of Armenian descent, and are widely known for their outspoken views expressed in
     many of their songs confronting the Armenian Genocide of 1915 by the Ottoman Empire and the ongoing War on Terror by the US government. The band
     consists of <a href="http://www.last.fm/music/Serj+Tankian" class="bbcode_artist">Serj Tankian</a> (vocals), Daron Malakian (vocals, guitar),
     Shavo Odadjian (bass, vocals) and John Dolmayan (drums).
     <a href="http://www.last.fm/music/System+of+a+Down">Read more about System of a Down on Last.fm</a>.
     User-contributed text is available under the Creative Commons By-SA License and may also be available under the GNU FDL.
     */

    text = text.replaceAll("User-contributed text.*", "");
    text = text.replaceAll("<a ", "<a target='_blank' ");
    text = text.replace("\n", " ");
    text = StringUtils.trimToNull(text);

    if (text != null && text.startsWith("This is an incorrect tag")) {
        return null;
    }

    return text;
}
 
Example 6
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   View Source Code Vote up 5 votes
/**
 * creates a playlist name that is <= 150 characters and is unique
 * 
 * @param playlistName the name of the playlist
 * @return the safe playlist name
 * @throws IllegalArgumentException if playlist name is invalid
 */
@NoProfile
protected String makeSafePlaylistName(String playlistName) {
    playlistName = StringUtils.trimToNull(playlistName);
    if (playlistName == null) {
        throw new IllegalArgumentException("playlistName cannot be null");
    }
    if (playlistName.length() > PLAYLIST_MAX_LENGTH) {
        playlistName = StringUtils.abbreviate(playlistName, CATEGORY_MAX_LENGTH);
        playlistName = playlistName.substring(0, CATEGORY_MAX_LENGTH-3) + RandomStringUtils.randomAlphanumeric(3);
    }
    return playlistName;
}
 
Example 7
Project: dubbocloud   File: Loadbalances.java   View Source Code Vote up 5 votes
public void index(Map<String, Object> context) {
    final String service = StringUtils.trimToNull((String) context.get("service"));
    
    List<LoadBalance> loadbalances;
    if (service != null && service.length() > 0) {
        loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findByService(service));
        
        loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findByService(service));
    } else {
        loadbalances = OverrideUtils.overridesToLoadBalances(overrideService.findAll());
    }
    context.put("loadbalances", loadbalances);
}
 
Example 8
Project: dubbox-hystrix   File: Weights.java   View Source Code Vote up 5 votes
public void index(Map<String, Object> context) {
    final String service = StringUtils.trimToNull((String) context.get("service"));
    String address = (String) context.get("address");
    address = Tool.getIP(address);
    List<Weight> weights;
    if (service != null && service.length() > 0) {
        weights = OverrideUtils.overridesToWeights(overrideService.findByService(service));
    } else if (address != null && address.length() > 0) {
        weights = OverrideUtils.overridesToWeights(overrideService.findByAddress(address));
    } else {
        weights = OverrideUtils.overridesToWeights(overrideService.findAll());
    }
    context.put("weights", weights);
}
 
Example 9
Project: ymate-payment-v2   File: WxPayJsApiController.java   View Source Code Vote up 5 votes
/**
 * @param appId  微信公众号应用ID
 * @param openId 微信用户身份唯一标识
 * @param state  商品或订单ID
 * @param attach 附加信息
 * @return 微信支付 -- JS_API模式
 * @throws Exception 可能产生的任何异常
 */
@RequestMapping(value = "/jsapi/{app_id}", method = {Type.HttpMethod.GET, Type.HttpMethod.POST})
public IView __doJsApi(@PathVariable("app_id") String appId,
                       @VRequried @RequestParam("open_id") String openId,
                       @VRequried @RequestParam String state,
                       @RequestParam String attach,
                       @RequestParam boolean debug) throws Exception {
    IWxPayEventHandler _eventHandler = WxPay.get().getModuleCfg().getEventHandler();
    if (_eventHandler != null) {
        WxPayAccountMeta _meta = WxPay.get().getModuleCfg().getAccountProvider().getAccount(appId);
        if (_meta != null) {
            WxPayUnifiedOrder _request = _eventHandler.buildUnifiedOrderRequest(_meta, IWxPay.TradeType.JSAPI, state, attach).openId(openId);
            WxPayUnifiedOrder.Response _response = _request.execute();
            //
            if (_response.checkReturnCode() && _response.checkResultCode() && (WxPay.get().getModuleCfg().isSignCheckDisabled() || _response.checkSignature(_meta.getMchKey()))) {
                // 封装JSAPI初始化相关参数
                String _queryStr = StringUtils.trimToNull(WebContext.getRequest().getQueryString());
                String _currentURL = WebUtils.buildURL(WebContext.getRequest(), "payment/wxpay/jsapi/" + appId + (_queryStr == null ? "" : "?" + _queryStr), true);
                //
                String _timestamp = DateTimeUtils.currentTimeUTC() + "";
                String _nonceStr = WxPayBaseData.__doCreateNonceStr();
                String _config = __buildJsApiConfigStr(_meta.getAppId(), _eventHandler.getJsApiTicket(_meta.getAppId()), StringUtils.substringBefore(_currentURL, "#"), _timestamp, _nonceStr, debug);
                // 封装基于JSAPI的支付调用相关参数
                Map<String, Object> _paramMap = new HashMap<String, Object>();
                _paramMap.put("appId", _meta.getAppId());
                _paramMap.put("timeStamp", _timestamp);
                _paramMap.put("nonceStr", _nonceStr);
                _paramMap.put("package", "prepay_id=" + _response.prepayId());
                _paramMap.put("signType", IWxPay.Const.SIGN_TYPE_MD5);
                _paramMap.put("paySign", WxPayBaseData.__doCreateSignature(_paramMap, _meta.getMchKey()));
                //
                return View.jspView(WxPay.get().getModuleCfg().getJsApiView())
                        .addAttribute("_config", _config)
                        .addAttribute("_data", _paramMap)
                        .addAttribute("_trade_no", state);
            }
        }
    }
    return HttpStatusView.bind(HttpServletResponse.SC_BAD_REQUEST);
}
 
Example 10
Project: dubbo2   File: Weights.java   View Source Code Vote up 5 votes
public void index(Map<String, Object> context) {
    final String service = StringUtils.trimToNull((String) context.get("service"));
    String address = (String) context.get("address");
    address = Tool.getIP(address);
    List<Weight> weights;
    if (service != null && service.length() > 0) {
        weights = OverrideUtils.overridesToWeights(overrideService.findByService(service));
    } else if (address != null && address.length() > 0) {
        weights = OverrideUtils.overridesToWeights(overrideService.findByAddress(address));
    } else {
        weights = OverrideUtils.overridesToWeights(overrideService.findAll());
    }
    context.put("weights", weights);
}
 
Example 11
Project: airsonic   File: PlayerService.java   View Source Code Vote up 5 votes
/**
 * Reads the player ID from the cookie in the HTTP request.
 *
 * @param request  The HTTP request.
 * @param username The name of the current user.
 * @return The player ID embedded in the cookie, or <code>null</code> if cookie is not present.
 */
private String getPlayerIdFromCookie(HttpServletRequest request, String username) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }
    String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username);
    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return StringUtils.trimToNull(cookie.getValue());
        }
    }
    return null;
}
 
Example 12
Project: lams   File: WebUtil.java   View Source Code Vote up 5 votes
/**
    * @return long value of paramValue
    * @exception IllegalArgumentException
    *                - if (a) not set and is not optional or (b) not long
    */
   public static Long checkLong(String paramName, String paramValue, boolean isOptional)
    throws IllegalArgumentException {
try {
    if (!isOptional) {
	WebUtil.checkObject(paramName, paramValue);
    }
    String value = paramValue != null ? StringUtils.trimToNull(paramValue) : null;
    return value != null ? new Long(value) : null;

} catch (NumberFormatException e) {
    throw new IllegalArgumentException(paramName + " should be a long '" + paramValue + "'");
}
   }
 
Example 13
Project: airsonic   File: DLNASettingsController.java   View Source Code Vote up 5 votes
private void handleParameters(HttpServletRequest request) {
    boolean dlnaEnabled = ServletRequestUtils.getBooleanParameter(request, "dlnaEnabled", false);
    String dlnaServerName = StringUtils.trimToNull(request.getParameter("dlnaServerName"));
    String dlnaBaseLANURL = StringUtils.trimToNull(request.getParameter("dlnaBaseLANURL"));
    if (dlnaServerName == null) {
        dlnaServerName = "Airsonic";
    }

    upnpService.setMediaServerEnabled(false);
    settingsService.setDlnaEnabled(dlnaEnabled);
    settingsService.setDlnaServerName(dlnaServerName);
    settingsService.setDlnaBaseLANURL(dlnaBaseLANURL);
    settingsService.save();
    upnpService.setMediaServerEnabled(dlnaEnabled);
}
 
Example 14
Project: airsonic   File: SearchController.java   View Source Code Vote up 5 votes
@RequestMapping(method = RequestMethod.POST)
protected String onSubmit(HttpServletRequest request, HttpServletResponse response,@ModelAttribute("command") SearchCommand command, Model model)
        throws Exception {

    User user = securityService.getCurrentUser(request);
    UserSettings userSettings = settingsService.getUserSettings(user.getUsername());
    command.setUser(user);
    command.setPartyModeEnabled(userSettings.isPartyModeEnabled());

    List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(user.getUsername());
    String query = StringUtils.trimToNull(command.getQuery());

    if (query != null) {

        SearchCriteria criteria = new SearchCriteria();
        criteria.setCount(MATCH_COUNT);
        criteria.setQuery(query);

        SearchResult artists = searchService.search(criteria, musicFolders, SearchService.IndexType.ARTIST);
        command.setArtists(artists.getMediaFiles());

        SearchResult albums = searchService.search(criteria, musicFolders, SearchService.IndexType.ALBUM);
        command.setAlbums(albums.getMediaFiles());

        SearchResult songs = searchService.search(criteria, musicFolders, SearchService.IndexType.SONG);
        command.setSongs(songs.getMediaFiles());

        command.setPlayer(playerService.getPlayer(request, response));
    }

    return "search";
}
 
Example 15
Project: airsonic   File: SonosSettingsController.java   View Source Code Vote up 5 votes
private void handleParameters(HttpServletRequest request) {
    boolean sonosEnabled = ServletRequestUtils.getBooleanParameter(request, "sonosEnabled", false);
    String sonosServiceName = StringUtils.trimToNull(request.getParameter("sonosServiceName"));
    if (sonosServiceName == null) {
        sonosServiceName = "Airsonic";
    }

    settingsService.setSonosEnabled(sonosEnabled);
    settingsService.setSonosServiceName(sonosServiceName);
    settingsService.save();

    sonosService.setMusicServiceEnabled(false, NetworkService.getBaseUrl(request));
    sonosService.setMusicServiceEnabled(sonosEnabled, NetworkService.getBaseUrl(request));
}
 
Example 16
Project: ymate-payment-v2   File: DefaultModuleCfg.java   View Source Code Vote up 5 votes
public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWxPay.MODULE_NAME);
    //
    __accountProvider = ClassUtils.impl(_moduleCfgs.get("account_provider_class"), IWxPayAccountProvider.class, getClass());
    if (__accountProvider == null) {
        __accountProvider = new DefaultWxPayAccountProvider();
        //
        WxPayAccountMeta _meta = new WxPayAccountMeta(_moduleCfgs.get("app_id"),
                _moduleCfgs.get(IWxPay.Const.MCH_ID),
                _moduleCfgs.get(IWxPay.Const.MCH_KEY),
                _moduleCfgs.get("cert_file_path"),
                _moduleCfgs.get(IWxPay.Const.NOTIFY_URL));
        _meta.setSandboxEnabled(BlurObject.bind(_moduleCfgs.get("sandbox_enabled")).toBooleanValue());
        _meta.setSandboxPrefix(StringUtils.defaultIfBlank(_moduleCfgs.get("sandbox_prefix"), "sandboxnew"));
        //
        __defaultAccountId = _meta.getAppId();
        __accountProvider.registerAccount(_meta);
    } else {
        __defaultAccountId = StringUtils.trimToNull(_moduleCfgs.get("default_account_id"));
    }
    //
    __eventHandler = ClassUtils.impl(_moduleCfgs.get("event_handler_class"), IWxPayEventHandler.class, getClass());
    if (__eventHandler == null) {
        throw new NullArgumentException("event_handler_class");
    }
    //
    __jsApiView = StringUtils.defaultIfBlank(_moduleCfgs.get("jsapi_view"), "wxpay_jsapi");
    __nativeView = StringUtils.defaultIfBlank(_moduleCfgs.get("native_view"), "wxpay_native");
    //
    __signCheckDisabled = BlurObject.bind(_moduleCfgs.get("sign_check_disabled")).toBooleanValue();
}
 
Example 17
Project: ymate-module-sso   File: DefaultModuleCfg.java   View Source Code Vote up 4 votes
public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(ISSO.MODULE_NAME);
    //
    __tokenCookieName = StringUtils.defaultIfBlank(_moduleCfgs.get("token_cookie_name"), ISSO.MODULE_NAME + "_token");
    //
    __tokenHeaderName = StringUtils.defaultIfBlank(_moduleCfgs.get("token_header_name"), "X-ModuleSSO-Token");
    //
    __tokenParamName = StringUtils.defaultIfBlank(_moduleCfgs.get("token_param_name"), "token");
    //
    __tokenMaxage = BlurObject.bind(_moduleCfgs.get("token_maxage")).toIntValue();
    //
    __tokenValidateTimeInterval = BlurObject.bind(_moduleCfgs.get("token_validate_time_interval")).toIntValue();
    //
    __cacheNamePrefix = StringUtils.trimToEmpty(_moduleCfgs.get("cache_name_prefix"));
    //
    __multiSessionEnabled = BlurObject.bind(_moduleCfgs.get("multi_session_enabled")).toBooleanValue();
    //
    __ipCheckEnabled = BlurObject.bind(_moduleCfgs.get("ip_check_enabled")).toBooleanValue();
    //
    __isClientMode = BlurObject.bind(_moduleCfgs.get("client_mode")).toBooleanValue();
    //
    __serviceAuthKey = StringUtils.trimToEmpty(_moduleCfgs.get("service_auth_key"));
    //
    if (__isClientMode) {
        __serviceBaseUrl = StringUtils.trimToNull(_moduleCfgs.get("service_base_url"));
        if (__serviceBaseUrl != null) {
            if (!StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "http://") &&
                    !StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "https://")) {
                throw new IllegalArgumentException("The parameter service_base_url is invalid");
            } else if (!StringUtils.endsWith(__serviceBaseUrl, "/")) {
                __serviceBaseUrl = __serviceBaseUrl + "/";
            }
        }
    }
    //
    __tokenApater = ClassUtils.impl(_moduleCfgs.get("token_adapter_class"), ISSOTokenAdapter.class, getClass());
    if (__tokenApater == null) {
        __tokenApater = new DefaultSSOTokenAdapter();
    }
    //
    __tokenStorageAdapter = ClassUtils.impl(_moduleCfgs.get("storage_adapter_class"), ISSOTokenStorageAdapter.class, getClass());
    if (!__isClientMode && __tokenStorageAdapter == null) {
        throw new IllegalArgumentException("The parameter storage_adapter_class is invalid");
    }
    //
    if (!__isClientMode) {
        __tokenAttributeAdapter = ClassUtils.impl(_moduleCfgs.get("attribute_adapter_class"), ISSOTokenAttributeAdapter.class, getClass());
    }
}
 
Example 18
Project: airsonic   File: SettingsService.java   View Source Code Vote up 4 votes
public String getLoginMessage() {
    return StringUtils.trimToNull(getProperty(KEY_LOGIN_MESSAGE, DEFAULT_LOGIN_MESSAGE));
}
 
Example 19
Project: airsonic   File: UserSettingsController.java   View Source Code Vote up 4 votes
public void createUser(UserSettingsCommand command) {
    User user = new User(command.getUsername(), command.getPassword(), StringUtils.trimToNull(command.getEmail()));
    user.setLdapAuthenticated(command.isLdapAuthenticated());
    securityService.createUser(user);
    updateUser(command);
}
 
Example 20
Project: airsonic   File: RecoverController.java   View Source Code Vote up 4 votes
@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView recover(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    String usernameOrEmail = StringUtils.trimToNull(request.getParameter("usernameOrEmail"));
    ReCaptcha captcha = ReCaptchaFactory.newSecureReCaptcha("6LcZ3OMSAAAAANkKMdFdaNopWu9iS03V-nLOuoiH",
            "6LcZ3OMSAAAAAPaFg89mEzs-Ft0fIu7wxfKtkwmQ", false);
    boolean showCaptcha = true;

    if (usernameOrEmail != null) {

        map.put("usernameOrEmail", usernameOrEmail);
        User user = getUserByUsernameOrEmail(usernameOrEmail);
        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse captchaResponse = captcha.checkAnswer(request.getRemoteAddr(), challenge, uresponse);

        if (!captchaResponse.isValid()) {
            map.put("error", "recover.error.invalidcaptcha");
        } else if (user == null) {
            map.put("error", "recover.error.usernotfound");
        } else if (user.getEmail() == null) {
            map.put("error", "recover.error.noemail");
        } else {
            String password = RandomStringUtils.randomAlphanumeric(8);
            if (emailPassword(password, user.getUsername(), user.getEmail())) {
                map.put("sentTo", user.getEmail());
                user.setLdapAuthenticated(false);
                user.setPassword(password);
                securityService.updateUser(user);
                showCaptcha = false;
            } else {
                map.put("error", "recover.error.sendfailed");
            }
        }
    }

    if (showCaptcha) {
        map.put("captcha", captcha.createRecaptchaHtml(null, null));
    }

    return new ModelAndView("recover", "model", map);
}