当前位置: 首页>>代码示例>>Java>>正文


Java StringUtils.trimToEmpty方法代码示例

本文整理汇总了Java中org.apache.commons.lang3.StringUtils.trimToEmpty方法的典型用法代码示例。如果您正苦于以下问题:Java StringUtils.trimToEmpty方法的具体用法?Java StringUtils.trimToEmpty怎么用?Java StringUtils.trimToEmpty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.lang3.StringUtils的用法示例。


在下文中一共展示了StringUtils.trimToEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: readTagNames

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
private static void readTagNames() {
    try {
        File jarLocation = new File(Config.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
        File[] configFiles = jarLocation.listFiles(f -> f.isFile() && f.getName().equals("ruuvi-names.properties"));
        if (configFiles == null || configFiles.length == 0) {
            // look for config files in the parent directory if none found in the current directory, this is useful during development when
            // RuuviCollector can be run from maven target directory directly while the config file sits in the project root
            configFiles = jarLocation.getParentFile().listFiles(f -> f.isFile() && f.getName().equals("ruuvi-names.properties"));
        }
        if (configFiles != null && configFiles.length > 0) {
            LOG.debug("Tag names: " + configFiles[0]);
            Properties props = new Properties();
            props.load(new FileInputStream(configFiles[0]));
            Enumeration<?> e = props.propertyNames();
            while (e.hasMoreElements()) {
                String key = StringUtils.trimToEmpty((String) e.nextElement()).toUpperCase();
                String value = StringUtils.trimToEmpty(props.getProperty(key));
                if (key.length() == 12 && value.length() > 0) {
                    TAG_NAMES.put(key, value);
                }
            }
        }
    } catch (URISyntaxException | IOException ex) {
        LOG.warn("Failed to read tag names", ex);
    }
}
 
开发者ID:Scrin,项目名称:RuuviCollector,代码行数:27,代码来源:Config.java

示例2: validatePasswords

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Validate passwords input
 * <ul>
 *  <li>password is not empty</li>
 *  <li>password has appropriate length</li>
 *  <li>password and repeated password match</li>
 * </ul>
 * @param password to validate
 * @param repeatedPassword to validate
 * @param errors resulting to validation
 */
public void validatePasswords(String password, String repeatedPassword, Errors errors) {
	String cleanPassword = StringUtils.trimToEmpty(password);
	if (StringUtils.isBlank(cleanPassword)) {
		errors.rejectValue("password", "validation.error.password.blank");
	} else if (StringUtils.length(cleanPassword) < config.getPasswordLength()) {
		errors.rejectValue("password", "validation.error.password.tooShort", new Object[]{config.getPasswordLength()}, StringUtils.EMPTY);
	} else {
		String cleanRepeatedPassword = StringUtils.trimToEmpty(repeatedPassword);
		if (!StringUtils.equals(cleanPassword, cleanRepeatedPassword)) {
			errors.rejectValue("repeatedPassword", "validation.error.password.noMatch");
		}
	}
	
}
 
开发者ID:xabgesagtx,项目名称:fat-lining,代码行数:26,代码来源:ValidationUtils.java

示例3: authenticateAdmin

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Prepare an authenticated connection to JIRA
 */
protected boolean authenticateAdmin(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_ADMIN_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_ADMIN_PASSWORD));
	final String baseUrl = parameters.get(PARAMETER_URL);
	final String url = StringUtils.appendIfMissing(baseUrl, "/") + "login.jsp";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			JiraCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));

	// Sudoing is only required for JIRA 4+
	if ("4".compareTo(getVersion(parameters)) <= 0) {
		requests.add(
				new CurlRequest(HttpMethod.POST, StringUtils.appendIfMissing(baseUrl, "/") + "secure/admin/WebSudoAuthenticate.jspa",
						"webSudoIsPost=false&os_cookie=true&authenticate=Confirm&webSudoPassword=" + password,
						JiraCurlProcessor.SUDO_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	}
	return processor.process(requests);
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:24,代码来源:JiraBaseResource.java

示例4: doFilterInternal

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Forwards the request to the next filter in the chain and delegates down to the subclasses to perform the actual
 * request logging both before and after the request is processed.
 *
 * @see #beforeRequest
 * @see #afterRequest
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	if (resourceUrlStart==null) {
		resourceUrlStart = request.getContextPath() + YadaWebConfig.getResourceFolder() + "-"; // /site/res-
	}
	boolean isFirstRequest = !isAsyncDispatch(request);
	long startTime = -1;
	String sessionId = "";
	String username = "";
	// Questo codice per il calcolo dell'IP è stato messo in YadaWebUtil ma accedere quello da qui non viene facile, per cui duplico qui
	String remoteAddr = request.getRemoteAddr();
	String forwardedFor = request.getHeader("X-Forwarded-For");
	String remoteIp = "?";
	if (!StringUtils.isBlank(remoteAddr)) {
		remoteIp = remoteAddr;
	}
	if (!StringUtils.isBlank(forwardedFor)) {
		remoteIp = "[for " + forwardedFor + "]";
	}
	//
	String requestUri = request.getRequestURI();
	HttpSession session = request.getSession(false);
	SecurityContext securityContext = null;
	if (session!=null) {
		sessionId = StringUtils.trimToEmpty(session.getId());
		securityContext = ((SecurityContext)session.getAttribute("SPRING_SECURITY_CONTEXT"));
	}
	if (sessionId.length()==0) {
		sessionId = "req-"+Integer.toString(request.hashCode());
	}
	if (securityContext!=null) {
		try {
			username = securityContext.getAuthentication().getName();
		} catch (Exception e) {
			log.debug("No username in securityContext");
		}
	}
	MDC.put(MDC_SESSION, sessionId); // Session viene messo sull'MDC. Usarlo con %X{session} nel pattern
	MDC.put(MDC_USERNAME, username); // username viene messo sull'MDC. Usarlo con %X{username} nel pattern		
	MDC.put(MDC_REMOTEIP, remoteIp); // remoteIp viene messo sull'MDC. Usarlo con %X{remoteIp} nel pattern		

	if (isFirstRequest) {
		beforeRequest(request);
		startTime = System.currentTimeMillis();
	}
	try {
		filterChain.doFilter(request, response);
		int status = response.getStatus();
		if (!skipDuration(requestUri) && !isAsyncStarted(request)) {
			if (startTime>-1) {
				long timetaken = System.currentTimeMillis()-startTime;
				log.info("{}: {} ms (HTTP {})", requestUri, timetaken, status);
			}
		} else if (status>399) {
			log.error("{} HTTP {}", requestUri, status);
		}
	} finally {
		MDC.remove(MDC_USERNAME);
		MDC.remove(MDC_SESSION);
		MDC.remove(MDC_REMOTEIP);
	}
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:70,代码来源:AuditFilter.java

示例5: authenticate

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Prepare an authenticated connection to Confluence
 */
protected void authenticate(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "dologin.action";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			ConfluenceCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	if (!processor.process(requests)) {
		throw new ValidationJsonException(PARAMETER_URL, "confluence-login", parameters.get(PARAMETER_USER));
	}
}
 
开发者ID:ligoj,项目名称:plugin-km-confluence,代码行数:17,代码来源:ConfluencePluginResource.java

示例6: authenticate

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Prepare an authenticated connection to vCloud. The given processor would
 * be updated with the security token.
 */
protected void authenticate(final Map<String, String> parameters, final VCloudCurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String organization = StringUtils.trimToEmpty(parameters.get(PARAMETER_ORGANIZATION));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "sessions";

	// Encode the authentication '[email protected]:password'
	final String authentication = Base64
			.encodeBase64String((user + "@" + organization + ":" + password).getBytes(StandardCharsets.UTF_8));

	// Authentication request using cache
	processor.setToken(authenticate(url, authentication, processor));
}
 
开发者ID:ligoj,项目名称:plugin-vm-vcloud,代码行数:18,代码来源:VCloudPluginResource.java

示例7: getText

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
private String getText(final String[] columns, final Cols col) {
    return StringUtils.trimToEmpty(columns[col.index()]);
}
 
开发者ID:react-dev26,项目名称:NGB-master,代码行数:4,代码来源:CytobandReader.java

示例8: parse

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
    // 轴解析
    if (!stateMachine.tokenQueue.hasAxis()) {
        stateMachine.state = TAG;
        return;
    }

    String axisFunctionStr = stateMachine.tokenQueue.consumeTo("::");
    stateMachine.tokenQueue.consume("::");
    TokenQueue functionTokenQueue = new TokenQueue(axisFunctionStr);
    String functionName = functionTokenQueue.consumeCssIdentifier().trim();
    functionTokenQueue.consumeWhitespace();

    AxisFunction axisFunction = FunctionEnv.getAxisFunction(functionName);
    if (axisFunction == null) {
        throw new NoSuchAxisException(stateMachine.tokenQueue.nowPosition(),
                "not such axis " + functionName);
    }
    stateMachine.xpathChain.getXpathNodeList().getLast().setAxis(axisFunction);

    if (functionTokenQueue.isEmpty()) {
        stateMachine.state = TAG;
        return;
    }

    // 带有参数的轴函数
    if (!functionTokenQueue.matches("(")) {// 必须以括号开头
        throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
                "expression is not a function:\"" + axisFunctionStr + "\"");
    }
    String paramList = StringUtils.trimToEmpty(functionTokenQueue.chompBalanced('(', ')'));
    functionTokenQueue.consumeWhitespace();
    if (!functionTokenQueue.isEmpty()) {
        throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
                "expression is not a function: \"" + axisFunctionStr + "\" can not recognize token:"
                        + functionTokenQueue.remainder());
    }

    // 解析参数列表
    TokenQueue paramTokenQueue = new TokenQueue(paramList);
    LinkedList<String> params = Lists.newLinkedList();
    while (!paramTokenQueue.isEmpty()) {
        paramTokenQueue.consumeWhitespace();
        if (!paramTokenQueue.isEmpty() && paramTokenQueue.peek() == ',') {
            paramTokenQueue.advance();
            paramTokenQueue.consumeWhitespace();
        }
        String param;
        if (paramTokenQueue.matches("\"")) {
            param = paramTokenQueue.chompBalanced('\"', '\"');
            if (paramTokenQueue.peek() == ',') {
                paramTokenQueue.consume();
            }
        } else if (paramTokenQueue.matches("\'")) {
            param = paramTokenQueue.chompBalanced('\'', '\'');
            if (paramTokenQueue.peek() == ',') {
                paramTokenQueue.consume();
            }
        } else {
            param = paramTokenQueue.consumeTo(",");
            if (StringUtils.isEmpty(param)) {
                continue;
            }
        }
        params.add(TokenQueue.unescape(StringUtils.trimToEmpty(param)));
    }
    stateMachine.xpathChain.getXpathNodeList().getLast().setAxisParams(params);
    stateMachine.state = TAG;
}
 
开发者ID:virjar,项目名称:sipsoup,代码行数:71,代码来源:XpathStateMachine.java

示例9: resolveInternal

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

    if (service == null || authentication == null) {
        LOGGER.debug("No service or authentication is available to determine event for principal");
        return null;
    }

    String acr = request.getParameter(OAuth20Constants.ACR_VALUES);
    if (StringUtils.isBlank(acr)) {
        final URIBuilder builderContext = new URIBuilder(StringUtils.trimToEmpty(context.getFlowExecutionUrl()));
        final Optional<URIBuilder.BasicNameValuePair> parameter = builderContext.getQueryParams()
                .stream().filter(p -> p.getName().equals(OAuth20Constants.ACR_VALUES))
                .findFirst();
        if (parameter.isPresent()) {
            acr = parameter.get().getValue();
        }
    }
    if (StringUtils.isBlank(acr)) {
        LOGGER.debug("No ACR provided in the authentication request");
        return null;
    }
    final Set<String> values = org.springframework.util.StringUtils.commaDelimitedListToSet(acr);
    if (values.isEmpty()) {
        LOGGER.debug("No ACR provided in the authentication request");
        return null;
    }

    final Map<String, MultifactorAuthenticationProvider> providerMap =
            WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
    if (providerMap == null || providerMap.isEmpty()) {
        LOGGER.error("No multifactor authentication providers are available in the application context to handle [{}]", values);
        throw new AuthenticationException();
    }

    final Collection<MultifactorAuthenticationProvider> flattenedProviders = flattenProviders(providerMap.values());
    final Optional<MultifactorAuthenticationProvider> provider = flattenedProviders
            .stream()
            .filter(v -> values.contains(v.getId())).findAny();

    if (provider.isPresent()) {
        return Collections.singleton(new Event(this, provider.get().getId()));
    }
    LOGGER.warn("The requested authentication class [{}] cannot be satisfied by any of the MFA providers available", values);
    throw new AuthenticationException();
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:50,代码来源:OidcAuthenticationContextWebflowEventEventResolver.java

示例10: CodeCacheKey

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
public CodeCacheKey(String context, String code, String codeSystem, String term) {
    this.context = StringUtils.trimToEmpty(context);
    this.code = StringUtils.trimToEmpty(code);
    this.codeSystem = StringUtils.trimToEmpty(codeSystem);
    this.term = StringUtils.trimToEmpty(term);
}
 
开发者ID:endeavourhealth,项目名称:HL7Receiver,代码行数:7,代码来源:CodeCacheKey.java

示例11: handleSingleStr

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
protected String handleSingleStr(String input) {
    return StringUtils.trimToEmpty(input);
}
 
开发者ID:virjar,项目名称:vscrawler,代码行数:5,代码来源:TrimToEmpty.java

示例12: getExpiry

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
public ZonedDateTime getExpiry(Key key) {

    String code = StringUtils.trimToEmpty(convertProductAlias(key));

    if (!EXPIRY_PATTERN.matcher(code).matches()) {
        return null;
    }

    ZonedDateTime expiry;

    try {

        String value = code.substring(6) + EXPIRY_TIME;

        Date date = EXPIRY_FORMAT.get().parse(value);

        ZoneId zone = ZoneId.of(EXPIRY_FORMAT.get().getTimeZone().getID());

        expiry = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), zone);

    } catch (ParseException e) {

        expiry = null;

    }

    return expiry;

}
 
开发者ID:after-the-sunrise,项目名称:cryptotrader,代码行数:31,代码来源:BitflyerContext.java

示例13: validateCurrentPassword

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
 * Validate current password
 * <ul>
 * 	<li>current password and entered password have to match</li>
 * </ul>
 * @param currentPassword
 * @param errors
 */
public void validateCurrentPassword(String currentPassword, Errors errors) {
	String cleanCurrentPassword = StringUtils.trimToEmpty(currentPassword);
	AppUser currentUser = manager.getCurrentUser();
	if (!encoder.matches(cleanCurrentPassword, currentUser.getHash())) {
		errors.rejectValue("currentPassword", "validation.error.password.wrongPassword");
	}
}
 
开发者ID:xabgesagtx,项目名称:fat-lining,代码行数:16,代码来源:ValidationUtils.java

示例14: computeHash

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@VisibleForTesting
String computeHash(String secret, String method, String path, String nonce, String data) throws IOException {

    try {

        Mac mac = Mac.getInstance("HmacSHA256");

        mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));

        String raw = method + path + nonce + StringUtils.trimToEmpty(data);

        byte[] hash = mac.doFinal(raw.getBytes());

        StringBuilder sb = new StringBuilder(hash.length);

        for (byte b : hash) {
            sb.append(String.format("%02x", b & 0xff));
        }

        return sb.toString();

    } catch (GeneralSecurityException e) {

        throw new IOException("Failed to compute hash.", e);

    }

}
 
开发者ID:after-the-sunrise,项目名称:cryptotrader,代码行数:29,代码来源:BitmexContext.java

示例15: onBoardsSnapshot

import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
public void onBoardsSnapshot(String product, Board value) {

    if (value == null) {
        return;
    }

    String key = StringUtils.trimToEmpty(product);

    Instant timestamp = getNow();

    realtimeBoards.put(key, Optional.of(new BitflyerBoard(timestamp, value)));

}
 
开发者ID:after-the-sunrise,项目名称:cryptotrader,代码行数:15,代码来源:BitflyerContext.java


注:本文中的org.apache.commons.lang3.StringUtils.trimToEmpty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。