Java 类org.apache.commons.lang3.BooleanUtils 实例源码
项目:sipsoup
文件:BooleanFunction.java
@Override
public Object call(Element element, List<SyntaxNode> params) {
if (params.size() == 0) {
return false;
}
Object calc = params.get(0).calc(element);
if (calc == null) {
return false;
}
if (calc instanceof Boolean) {
return calc;
}
if (calc instanceof String) {
return BooleanUtils.toBoolean(calc.toString());
}
if (calc instanceof Integer) {
return calc != 0;
}
if (calc instanceof Number) {
return ((Number) calc).doubleValue() > 0D;
}
return false;
}
项目:cas-5.1.0
文件:CasFiltersConfiguration.java
@RefreshScope
@Bean
public FilterRegistrationBean responseHeadersSecurityFilter() {
final HttpWebRequestProperties.Header header = casProperties.getHttpWebRequest().getHeader();
final Map<String, String> initParams = new HashMap<>();
initParams.put("enableCacheControl", BooleanUtils.toStringTrueFalse(header.isCache()));
initParams.put("enableXContentTypeOptions", BooleanUtils.toStringTrueFalse(header.isXcontent()));
initParams.put("enableStrictTransportSecurity", BooleanUtils.toStringTrueFalse(header.isHsts()));
initParams.put("enableXFrameOptions", BooleanUtils.toStringTrueFalse(header.isXframe()));
initParams.put("enableXSSProtection", BooleanUtils.toStringTrueFalse(header.isXss()));
final FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new ResponseHeadersEnforcementFilter());
bean.setUrlPatterns(Collections.singleton("/*"));
bean.setInitParameters(initParams);
bean.setName("responseHeadersSecurityFilter");
bean.setAsyncSupported(true);
return bean;
}
项目:cas-5.1.0
文件:CasFiltersConfiguration.java
@RefreshScope
@Bean
public FilterRegistrationBean requestParameterSecurityFilter() {
final Map<String, String> initParams = new HashMap<>();
initParams.put(RequestParameterPolicyEnforcementFilter.PARAMETERS_TO_CHECK,
casProperties.getHttpWebRequest().getParamsToCheck());
initParams.put(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID, "none");
initParams.put(RequestParameterPolicyEnforcementFilter.ALLOW_MULTI_VALUED_PARAMETERS,
BooleanUtils.toStringTrueFalse(casProperties.getHttpWebRequest().isAllowMultiValueParameters()));
initParams.put(RequestParameterPolicyEnforcementFilter.ONLY_POST_PARAMETERS,
casProperties.getHttpWebRequest().getOnlyPostParams());
final FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new RequestParameterPolicyEnforcementFilter());
bean.setUrlPatterns(Collections.singleton("/*"));
bean.setName("requestParameterSecurityFilter");
bean.setInitParameters(initParams);
bean.setAsyncSupported(true);
return bean;
}
项目:cas-5.1.0
文件:PatternMatchingEntityIdAttributeReleasePolicy.java
@Override
protected Map<String, Object> getAttributesForSamlRegisteredService(final Map<String, Object> attributes,
final SamlRegisteredService service,
final ApplicationContext applicationContext,
final SamlRegisteredServiceCachingMetadataResolver resolver,
final SamlRegisteredServiceServiceProviderMetadataFacade facade,
final EntityDescriptor entityDescriptor) {
final Pattern pattern = RegexUtils.createPattern(this.entityIds);
final Matcher matcher = pattern.matcher(entityDescriptor.getEntityID());
LOGGER.debug("Creating pattern [{}] to match against entity id [{}]", pattern.pattern(), entityDescriptor.getEntityID());
final boolean matched = fullMatch ? matcher.matches() : matcher.find();
LOGGER.debug("Pattern [{}] matched against [{}]? [{}]", pattern.pattern(), entityDescriptor.getEntityID(),
BooleanUtils.toStringYesNo(matched));
if (matched) {
return authorizeReleaseOfAllowedAttributes(attributes);
}
return new HashMap<>();
}
项目:cas-5.1.0
文件:TokenWebApplicationServiceResponseBuilder.java
@Override
protected WebApplicationService buildInternal(final WebApplicationService service,
final Map<String, String> parameters) {
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService);
final Map.Entry<String, RegisteredServiceProperty> property = registeredService.getProperties()
.entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(TokenConstants.PROPERTY_NAME_TOKEN_AS_RESPONSE)
&& BooleanUtils.toBoolean(entry.getValue().getValue()))
.distinct()
.findFirst()
.orElse(null);
if (property == null) {
return super.buildInternal(service, parameters);
}
final String jwt = generateToken(service, parameters);
final TokenWebApplicationService jwtService =
new TokenWebApplicationService(service.getId(), service.getOriginalUrl(), service.getArtifactId());
jwtService.setFormat(service.getFormat());
jwtService.setLoggedOutAlready(service.isLoggedOutAlready());
parameters.put(CasProtocolConstants.PARAMETER_TICKET, jwt);
return jwtService;
}
项目:cas-5.1.0
文件:AbstractCasProtocolValidationSpecification.java
@Override
public boolean isSatisfiedBy(final Assertion assertion, final HttpServletRequest request) {
LOGGER.debug("Is validation specification set to enforce [{}] protocol behavior? [{}]. Is assertion issued from a new login? [{}]",
CasProtocolConstants.PARAMETER_RENEW,
BooleanUtils.toStringYesNo(this.renew),
BooleanUtils.toStringYesNo(assertion.isFromNewLogin()));
boolean satisfied = isSatisfiedByInternal(assertion);
if (!satisfied) {
LOGGER.warn("[{}] is not internally satisfied by the produced assertion", getClass().getSimpleName());
return false;
}
satisfied = !this.renew || assertion.isFromNewLogin();
if (!satisfied) {
LOGGER.warn("[{}] is to enforce the [{}] CAS protocol behavior, yet the assertion is not issued from a new login",
getClass().getSimpleName(), CasProtocolConstants.PARAMETER_RENEW);
return false;
}
LOGGER.debug("Validation specification is satisfied by the produced assertion");
return true;
}
项目:hybris-integration-intellij-idea-plugin
文件:TSStructureTreeElement.java
private void resolveModifier(
final GenericAttributeValue<Boolean> attribute,
final String methodName,
final List<String> resultList
) {
if (attribute == null) {
return;
}
final Boolean value = BooleanUtils.toBooleanObject(attribute.getStringValue());
if (value == null) {
return;
}
if (value) {
resultList.add(methodName);
} else {
resultList.add(methodName + "(false)");
}
}
项目:vscrawler
文件:ExpressionParser.java
private SyntaxNode buildByTokenHolder(TokenHolder tokenHolder) {
if (tokenHolder.tokenType == TokenType.Expression) {
return new ExpressionParser(new StringFunctionTokenQueue(tokenHolder.data)).parse();
}
if (tokenHolder.tokenType == TokenType.Function) {
return parseFunction(new StringFunctionTokenQueue(tokenHolder.data));
}
if (tokenHolder.tokenType == TokenType.String) {
return new StringSyntaxNode(tokenHolder.data);
}
if (tokenHolder.tokenType == TokenType.Boolean) {
return new BooleanSyntaxNode(BooleanUtils.toBoolean(tokenHolder.data));
}
if (tokenHolder.tokenType == TokenType.Number) {
if (tokenHolder.data.contains(".")) {
return new NumberSyntaxNode(NumberUtils.toDouble(tokenHolder.data));
} else {
return new NumberSyntaxNode(NumberUtils.toInt(tokenHolder.data));
}
}
throw new IllegalStateException("unknown token type: " + tokenHolder.tokenType);
}
项目:mafia
文件:DsMasterConfig.java
@Bean(name = ConfigConstant.NAME_DS_MASTER)
@Primary
@ConfigurationProperties(prefix = ConfigConstant.PREFIX_DS_MASTER)
public DataSource mafMasterDataSource() {
logger.info("----- MAFIA master data source INIT -----");
DruidDataSource ds = new DruidDataSource();
try {
ds.setFilters(env.getProperty("ds.filters"));
} catch (SQLException e) {
logger.warn("Data source set filters ERROR:", e);
}
ds.setMaxActive(NumberUtils.toInt(env.getProperty("ds.maxActive"), 90));
ds.setInitialSize(NumberUtils.toInt(env.getProperty("ds.initialSize"), 10));
ds.setMaxWait(NumberUtils.toInt(env.getProperty("ds.maxWait"), 60000));
ds.setMinIdle(NumberUtils.toInt(env.getProperty("ds.minIdle"), 1));
ds.setTimeBetweenEvictionRunsMillis(NumberUtils.toInt(env.getProperty("ds.timeBetweenEvictionRunsMillis"), 60000));
ds.setMinEvictableIdleTimeMillis(NumberUtils.toInt(env.getProperty("ds.minEvictableIdleTimeMillis"), 300000));
ds.setValidationQuery(env.getProperty("ds.validationQuery"));
ds.setTestWhileIdle(BooleanUtils.toBoolean(env.getProperty("ds.testWhileIdle")));
ds.setTestOnBorrow(BooleanUtils.toBoolean(env.getProperty("ds.testOnBorrow")));
ds.setTestOnReturn(BooleanUtils.toBoolean(env.getProperty("ds.testOnReturn")));
ds.setPoolPreparedStatements(BooleanUtils.toBoolean(env.getProperty("ds.poolPreparedStatements")));
ds.setMaxOpenPreparedStatements(NumberUtils.toInt(env.getProperty("ds.maxOpenPreparedStatements"), 20));
return ds;
}
项目:mafia
文件:DsSlaveConfig.java
@Bean(name = ConfigConstant.NAME_DS_SLAVE)
@ConfigurationProperties(prefix = ConfigConstant.PREFIX_DS_SLAVE)
public DataSource mafSlaveDataSource() {
logger.info("----- MAFIA slave data source INIT -----");
DruidDataSource ds = new DruidDataSource();
try {
ds.setFilters(env.getProperty("ds.filters"));
} catch (SQLException e) {
logger.warn("Data source set filters ERROR:", e);
}
ds.setMaxActive(NumberUtils.toInt(env.getProperty("ds.maxActive"), 90));
ds.setInitialSize(NumberUtils.toInt(env.getProperty("ds.initialSize"), 10));
ds.setMaxWait(NumberUtils.toInt(env.getProperty("ds.maxWait"), 60000));
ds.setMinIdle(NumberUtils.toInt(env.getProperty("ds.minIdle"), 1));
ds.setTimeBetweenEvictionRunsMillis(NumberUtils.toInt(env.getProperty("ds.timeBetweenEvictionRunsMillis"), 60000));
ds.setMinEvictableIdleTimeMillis(NumberUtils.toInt(env.getProperty("ds.minEvictableIdleTimeMillis"), 300000));
ds.setValidationQuery(env.getProperty("ds.validationQuery"));
ds.setTestWhileIdle(BooleanUtils.toBoolean(env.getProperty("ds.testWhileIdle")));
ds.setTestOnBorrow(BooleanUtils.toBoolean(env.getProperty("ds.testOnBorrow")));
ds.setTestOnReturn(BooleanUtils.toBoolean(env.getProperty("ds.testOnReturn")));
ds.setPoolPreparedStatements(BooleanUtils.toBoolean(env.getProperty("ds.poolPreparedStatements")));
ds.setMaxOpenPreparedStatements(NumberUtils.toInt(env.getProperty("ds.maxOpenPreparedStatements"), 20));
return ds;
}
项目:geoportal-server-harvester
文件:AgpInputBrokerDefinitionAdaptor.java
/**
* Creates instance of the adaptor.
* @param def broker definition
* @throws IllegalArgumentException if invalid broker definition
*/
public AgpInputBrokerDefinitionAdaptor(EntityDefinition def) throws InvalidDefinitionException {
super(def);
this.credAdaptor =new CredentialsDefinitionAdaptor(def);
this.botsAdaptor = new BotsBrokerDefinitionAdaptor(def);
if (StringUtils.trimToEmpty(def.getType()).isEmpty()) {
def.setType(AgpInputConnector.TYPE);
} else if (!AgpInputConnector.TYPE.equals(def.getType())) {
throw new InvalidDefinitionException("Broker definition doesn't match");
} else {
try {
hostUrl = new URL(get(P_HOST_URL));
} catch (MalformedURLException ex) {
throw new InvalidDefinitionException(String.format("Invalid %s: %s", P_HOST_URL,get(P_HOST_URL)), ex);
}
folderId = get(P_FOLDER_ID);
emitXml = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_XML)), true);
emitJson = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_JSON)), false);
}
}
项目:geoportal-server-harvester
文件:GptBrokerDefinitionAdaptor.java
/**
* Creates instance of the adaptor.
* @param def broker definition
*/
public GptBrokerDefinitionAdaptor(EntityDefinition def) throws InvalidDefinitionException {
super(def);
this.credAdaptor = new CredentialsDefinitionAdaptor(def);
this.botsAdaptor = new BotsBrokerDefinitionAdaptor(def);
if (StringUtils.trimToEmpty(def.getType()).isEmpty()) {
def.setType(GptConnector.TYPE);
} else if (!GptConnector.TYPE.equals(def.getType())) {
throw new InvalidDefinitionException("Broker definition doesn't match");
} else {
try {
String sHostUrl = get(P_HOST_URL);
if (sHostUrl!=null) {
sHostUrl = sHostUrl.replaceAll("/*$", "/");
}
hostUrl = new URL(sHostUrl);
} catch (MalformedURLException ex) {
throw new InvalidDefinitionException(String.format("Invalid %s: %s", P_HOST_URL,get(P_HOST_URL)), ex);
}
index = get(P_INDEX);
emitXml = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_XML)), true);
emitJson = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_JSON)), false);
}
}
项目:geoportal-server-harvester
文件:AgsBrokerDefinitionAdaptor.java
/**
* Creates instance of the adaptor.
* @param def broker definition
* @throws InvalidDefinitionException if invalid broker definition
*/
public AgsBrokerDefinitionAdaptor(EntityDefinition def) throws InvalidDefinitionException {
super(def);
this.credAdaptor =new CredentialsDefinitionAdaptor(def);
this.botsAdaptor = new BotsBrokerDefinitionAdaptor(def);
if (StringUtils.trimToEmpty(def.getType()).isEmpty()) {
def.setType(AgsConnector.TYPE);
} else if (!AgsConnector.TYPE.equals(def.getType())) {
throw new InvalidDefinitionException("Broker definition doesn't match");
} else {
try {
hostUrl = new URL(get(P_HOST_URL));
} catch (MalformedURLException ex) {
throw new InvalidDefinitionException(String.format("Invalid %s: %s", P_HOST_URL,get(P_HOST_URL)), ex);
}
enableLayers = BooleanUtils.toBoolean(get(P_ENABLE_LAYERS));
emitXml = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_XML)), true);
emitJson = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(get(P_EMIT_JSON)), false);
}
}
项目:weixin-java-tools
文件:WxBooleanTypeAdapter.java
@Override
public Boolean read(JsonReader in) throws IOException {
JsonToken peek = in.peek();
switch (peek) {
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
case NUMBER:
return BooleanUtils.toBoolean(in.nextInt());
case STRING:
return BooleanUtils.toBoolean(in.nextString());
default:
throw new JsonParseException("Expected BOOLEAN or NUMBER but was " + peek);
}
}
项目:tc
文件:TcHttpxService.java
protected <T> ResponseEntity<T> execute(String url,
HttpMethod httpMethod,
HttpEntity<?> httpEntity,
ParameterizedTypeReference<T> typeReference,
Map<String, String> uriVariables) {
if (Objects.isNull(uriVariables)) {
uriVariables = Maps.newHashMap();
}
if (BooleanUtils.isTrue(swallowException)) {
try {
return doExecute(url, httpMethod, httpEntity, typeReference, uriVariables);
} catch (Exception e) {
// camouflage exception
log.error("http call failed, url [{}], http method [{}], http entity [{}], uri vars [{}]",
url, httpMethod, httpEntity, uriVariables, e);
return doCamouflageException();
}
} else {
return doExecute(url, httpMethod, httpEntity, typeReference, uriVariables);
}
}
项目:tc
文件:TcAccountService.java
private TcAccount findOriginalTcAccount(@Nonnull String accountId, @Nonnull Boolean containsPassword) {
checkNotNull(accountId);
checkNotNull(containsPassword);
TcAccountExample tcAccountExample = new TcAccountExample();
tcAccountExample.setStartLine(0);
tcAccountExample.setPageSize(1);
tcAccountExample.createCriteria()
.andIdEqualTo(accountId)
.andDelectedEqualTo(false);
List<TcAccount> tcAccounts = tcAccountMapper.selectByExample(tcAccountExample);
if (CollectionUtils.isEmpty(tcAccounts)) {
return null;
}
TcAccount tcAccount = tcAccounts.get(0);
if (BooleanUtils.isFalse(containsPassword)) {
tcAccount.setPassword(null);
}
return tcAccount;
}
项目:aet
文件:LoginModifierConfig.java
public LoginModifierConfig(Map<String, String> params) throws ParametersException {
this.loginPage = params.get(LOGIN_PAGE_PARAM);
this.login = getParameter(params, LOGIN_PARAM, DEFAULT_LOGIN);
this.password = getParameter(params, PASSWORD_PARAM, DEFAULT_PASSWORD);
this.loginInputSelector = getParameter(params, LOGIN_INPUT_SELECTOR_PARAM,
DEFAULT_LOGIN_INPUT_SELECTOR);
this.passwordInputSelector = getParameter(params, PASSWORD_INPUT_SELECTOR_PARAM,
DEFAULT_PASSWORD_INPUT_SELECTOR);
this.submitButtonSelector = getParameter(params, SUBMIT_BUTTON_SELECTOR_PARAM,
DEFAULT_SUBMIT_BUTTON_SELECTOR);
this.loginTokenKey = getParameter(params, LOGIN_TOKEN_KEY_PARAM, DEFAULT_LOGIN_TOKEN);
this.forceLogin = BooleanUtils.toBoolean(params.get(FORCE_LOGIN));
this.delayBeforeLoginCheckOrReattempt = NumberUtils
.toInt(getParameter(params, LOGIN_CHECK_TIMEOUT_PARAM, DEFAULT_CHECK_TIMEOUT_PARAM));
this.retrialNumber = NumberUtils
.toInt(getParameter(params, RETRIAL_NUMBER_PARAM, DEFAULT_RETRIAL_NUMBER));
ParametersValidator.checkNotBlank(loginPage, "`login-page` parameter is mandatory");
ParametersValidator.checkRange(delayBeforeLoginCheckOrReattempt, 0, 10000,
"Timeout duration should be greater than 0 and less than 10 seconds");
ParametersValidator
.checkRange(retrialNumber, 1, Integer.MAX_VALUE, "Retrial number has to be at least 1");
}
项目:struts2
文件:DefaultObjectTypeDeterminer.java
/**
* Determines the createIfNull property for a Collection or Map by getting it from the @CreateIfNull annotation.
*
* As fallback, it determines the boolean CreateIfNull property for a Collection or Map by getting it from the
* conversion properties file using the CreateIfNull_ prefix. CreateIfNull_${property}=true|false
*
* @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
* @param property the property of the Map or Collection for the given parent class
* @param target the target object
* @param keyProperty the keyProperty value
* @param isIndexAccessed <tt>true</tt>, if the collection or map is accessed via index, <tt>false</tt> otherwise.
* @return <tt>true</tt>, if the Collection or Map should be created, <tt>false</tt> otherwise.
* @see ObjectTypeDeterminer#getKeyProperty(Class, String)
*/
public boolean shouldCreateIfNew(Class parentClass, String property, Object target, String keyProperty, boolean isIndexAccessed) {
CreateIfNull annotation = getAnnotation(parentClass, property, CreateIfNull.class);
if (annotation != null) {
return annotation.value();
}
String configValue = (String) xworkConverter.getConverter(parentClass, CREATE_IF_NULL_PREFIX + property);
//check if a value is in the config
if (configValue != null) {
return BooleanUtils.toBoolean(configValue);
}
//default values depend on target type
//and whether this is accessed by an index
//in the case of List
return (target instanceof Map) || isIndexAccessed;
}
项目:ModPackDownloader
文件:ForgeHandler.java
public void downloadForge(String minecraftVersion, List<ModLoader> modLoaders) {
if (CollectionUtils.isEmpty(modLoaders) || Strings.isNullOrEmpty(minecraftVersion)) {
log.debug("No Forge or Minecraft version found in manifest, skipping");
return;
}
for (ModLoader modLoader : modLoaders) {
if (BooleanUtils.isTrue(modLoader.getDownloadInstaller())) {
log.debug("Downloading Forge installer version {}", modLoader.getId());
downloadForgeFile(minecraftVersion, modLoader, true);
}
if (BooleanUtils.isTrue(modLoader.getDownloadUniversal())) {
log.debug("Downloading Forge universal version {}", modLoader.getId());
downloadForgeFile(minecraftVersion, modLoader, false);
}
}
}
项目:meazza
文件:DefaultControllerAdvice.java
/**
* 处理异常。如果是 AJAX 请求,以 JSON 格式返回;如果是普通请求,dispatch 到错误页面。
*/
private Object handleException(Exception e, int status, String message, ServletWebRequest request) {
Map<String, Object> errorResponse = getErrorResponse(e, message);
// 如果开启 debug,则将 debug 标记写入 error response 中
boolean isDebug = BooleanUtils.toBoolean(request.getParameter("debug"));
logger.debug("Debug is {}", isDebug ? "on" : "off");
if (isDebug) {
errorResponse.put("debug", true);
}
// AJAX 请求需要手工指定 status
if (isAjaxRequest(request)) {
request.getResponse().setStatus(status);
return errorResponse;
}
// 如果是普通请求,dispatch 到错误页面
String exName = e.getClass().getName();
String exView = StringUtils.defaultString(exceptionMappings.get(exName), defaultErrorView);
return new ModelAndView(exView, errorResponse);
}
项目:meazza
文件:P3PHeaderFilter.java
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String enableValue = filterConfig.getInitParameter("enable");
logger.debug("Read enable param: {}", enableValue);
if (!StringUtils.isEmpty(enableValue)) {
isEnable = BooleanUtils.toBoolean(enableValue);
}
String patternRegex = filterConfig.getInitParameter("pattern");
logger.debug("Read pattern param: {}", patternRegex);
if (!StringUtils.isEmpty(patternRegex)) {
uriPattern = Pattern.compile(filterConfig.getServletContext().getContextPath() + patternRegex);
}
String p3pValue = filterConfig.getInitParameter("p3pValue");
logger.debug("Read p3pValue param: {}", p3pValue);
if (!StringUtils.isEmpty(p3pValue)) {
headerValue = p3pValue;
}
logger.info("{} initialized with {}", getClass(), isEnable ? "enable" : "disable");
}
项目:gvnix1
文件:QuerydslUtils.java
/**
* Return an expression for {@code entityPath.fieldName} (for Booleans) with
* the {@code operator} or "equal" by default.
* <p/>
* Expr: {@code entityPath.fieldName eq searchObj}
*
* @param entityPath
* @param fieldName
* @param searchObj
* @param operator
* @return
*/
public static <T> BooleanExpression createBooleanExpression(
PathBuilder<T> entityPath, String fieldName, Object searchObj,
String operator) {
Boolean value = BooleanUtils.toBooleanObject((String) searchObj);
if (value != null) {
if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
return entityPath.getBoolean(fieldName).goe(value);
}
else if (StringUtils.equalsIgnoreCase(operator, "gt")) {
return entityPath.getBoolean(fieldName).gt(value);
}
else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
return entityPath.getBoolean(fieldName).loe(value);
}
else if (StringUtils.equalsIgnoreCase(operator, "lt")) {
return entityPath.getBoolean(fieldName).lt(value);
}
}
return entityPath.get(fieldName).eq(searchObj);
}
项目:gvnix1
文件:QuerydslUtils.java
/**
* Return where clause expression for {@code Boolean} fields by transforming
* the given {@code searchStr} to {@code Boolean} before check its value.
* <p/>
* Expr: {@code entityPath.fieldName eq (TRUE | FALSE)}
*
* @param entityPath Full path to entity and associations. For example:
* {@code Pet} , {@code Pet.owner}
* @param fieldName Property name in the given entity path. For example:
* {@code weight} in {@code Pet} entity, {@code age} in
* {@code Pet.owner} entity.
* @param searchStr the boolean value to find, may be null. Supported string
* are: si, yes, true, on, no, false, off
* @return BooleanExpression
*/
public static <T> BooleanExpression createBooleanExpression(
PathBuilder<T> entityPath, String fieldName, String searchStr) {
if (StringUtils.isBlank(searchStr)) {
return null;
}
Boolean value = null;
// I18N: Spanish (normalize search value: trim start-end and lower case)
if ("si".equals(StringUtils.trim(searchStr).toLowerCase())) {
value = Boolean.TRUE;
}
else {
value = BooleanUtils.toBooleanObject(searchStr);
}
// if cannot parse to boolean or null input
if (value == null) {
return null;
}
BooleanExpression expression = entityPath.getBoolean(fieldName).eq(
value);
return expression;
}
项目:gvnix1
文件:QuerydslUtilsBeanImpl.java
/**
* {@inheritDoc}
*/
@Override
public <T> BooleanExpression createBooleanExpression(
PathBuilder<T> entityPath, String fieldName, Object searchObj,
String operator) {
Boolean value = BooleanUtils.toBooleanObject((String) searchObj);
if (value != null) {
if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
return entityPath.getBoolean(fieldName).goe(value);
}
else if (StringUtils.equalsIgnoreCase(operator, "gt")) {
return entityPath.getBoolean(fieldName).gt(value);
}
else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
return entityPath.getBoolean(fieldName).loe(value);
}
else if (StringUtils.equalsIgnoreCase(operator, "lt")) {
return entityPath.getBoolean(fieldName).lt(value);
}
}
return entityPath.get(fieldName).eq(searchObj);
}
项目:web2app
文件:Setup.java
@Override
public void e() throws Exception {
if (BooleanUtils.isTrue(clear)) {
FileUtils.deleteDirectory(frontendDirectory);
FileUtils.deleteDirectory(frontendWorkingDirectory);
}
generatNpmPackage(frontendWorkingDirectory);
execMojo("com.github.eirslett", "frontend-maven-plugin",
configuration(element(name("nodeVersion"), getVersion("node")),
element(name("npmVersion"), getVersion("npm")),
element(name("installDirectory"), frontendDirectory.getAbsolutePath())),
"install-node-and-npm");
execMojo("com.github.eirslett", "frontend-maven-plugin",
configuration(element(name("arguments"), "install"),
element(name("installDirectory"), frontendDirectory.getAbsolutePath()),
element(name("workingDirectory"), frontendWorkingDirectory.getAbsolutePath())),
"npm");
}
项目:invesdwin-context-persistence
文件:SynchronousChannels.java
public static synchronized boolean createNamedPipe(final File file) {
if (BooleanUtils.isFalse(namedPipeSupportedCached)) {
return false;
}
try {
//linux
execCommand("mkfifo", file.getAbsolutePath());
} catch (final Exception e) {
//mac os
try {
execCommand("mknod", file.getAbsolutePath());
} catch (final Exception e2) {
return false;
}
}
return true;
}
项目:aet
文件:AccessibilityReportConfiguration.java
public AccessibilityReportConfiguration(Map<String, String> params) {
if (params.containsKey(PARAM_SHOW_EXCLUDED)) {
showExcluded = BooleanUtils.toBoolean(params.get(PARAM_SHOW_EXCLUDED));
}
if (params.containsKey(PARAM_IGNORE_NOTICE)) {
ignoreNotice = BooleanUtils.toBoolean(params.get(PARAM_IGNORE_NOTICE));
}
String reportLevelString = StringUtils
.defaultString(params.get(PARAM_REPORT_LEVEL), DEFAULT_REPORT_LEVEL);
if (!ignoreNotice) {
reportLevelString = IssueType.NOTICE.toString();
}
IssueType reportLevel;
reportLevel = IssueType.valueOf(reportLevelString.toUpperCase());
showNotice = IssueType.NOTICE.compareTo(reportLevel) <= 0;
showWarning = IssueType.WARN.compareTo(reportLevel) <= 0;
}
项目:SVNAutoMerger
文件:SvnUtils.java
/**
* Creates the String to include SVN user and password in the command if necessary.
* @return
*/
public static String createSvnCredentials() {
boolean isSvnUsingCredentials =
BooleanUtils.toBoolean( PropertiesUtil.getString("svn.enable.password.auth"));
String credentials;
if (isSvnUsingCredentials){
String user = PropertiesUtil.getString("svn.username");
String password = PropertiesUtil.getString("svn.password");
credentials = String.format(SvnOperationsEnum.SVN_CREDENTIALS, user, password);
} else {
credentials = "";
}
return credentials;
}
项目:sipsoup
文件:SipSoupPredicteJudgeFunction.java
@Override
public Object call(Element element, List<SyntaxNode> params) {
if (element == null) {
return false;
}
Object ret = params.get(0).calc(element);
if (ret == null) {
return false;
}
if (ret instanceof Number) {
int i = ((Number) ret).intValue();
return XpathUtil.getElIndexInSameTags(element) == i;
}
if (ret instanceof Boolean) {
return ret;
}
if (ret instanceof CharSequence) {
String s = ret.toString();
Boolean booleanValue = BooleanUtils.toBooleanObject(s);
if (booleanValue != null) {
return booleanValue;
}
return StringUtils.isNotBlank(s);
}
log.warn("can not recognize predicate expression calc result:" + ret);
return false;
}
项目:cas-5.1.0
文件:DefaultRelyingPartyTokenProducer.java
private static String serializeRelyingPartyToken(final Element rpToken) {
try {
final StringWriter sw = new StringWriter();
final Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, BooleanUtils.toStringYesNo(Boolean.TRUE));
t.transform(new DOMSource(rpToken), new StreamResult(sw));
return sw.toString();
} catch (final TransformerException e) {
throw Throwables.propagate(e);
}
}
项目:cas-5.1.0
文件:OAuth20AuthenticationServiceSelectionStrategy.java
@Override
public boolean supports(final Service service) {
final RegisteredService svc = this.servicesManager.findServiceBy(service);
final boolean res = svc != null && service.getId().startsWith(this.callbackUrl);
LOGGER.debug("Authentication request is{}identified as an OAuth request",
BooleanUtils.toString(res, StringUtils.EMPTY, " not "));
return res;
}
项目:cas-5.1.0
文件:AbstractCasBanner.java
/**
* Collect environment info with
* details on the java and os deployment
* versions.
*
* @param environment the environment
* @param sourceClass the source class
* @return environment info
*/
private String collectEnvironmentInfo(final Environment environment, final Class<?> sourceClass) {
final Properties properties = System.getProperties();
if (properties.containsKey("CAS_BANNER_SKIP")) {
try (Formatter formatter = new Formatter()) {
formatter.format("CAS Version: %s%n", CasVersion.getVersion());
return formatter.toString();
}
}
try (Formatter formatter = new Formatter()) {
formatter.format("CAS Version: %s%n", CasVersion.getVersion());
formatter.format("CAS Commit Id: %s%n", CasVersion.getSpecificationVersion());
formatter.format("CAS Build Date/Time: %s%n", CasVersion.getDateTime());
formatter.format("Spring Boot Version: %s%n", SpringBootVersion.getVersion());
formatter.format("%s%n", LINE_SEPARATOR);
formatter.format("System Date/Time: %s%n", LocalDateTime.now());
formatter.format("System Temp Directory: %s%n", FileUtils.getTempDirectoryPath());
formatter.format("%s%n", LINE_SEPARATOR);
formatter.format("Java Home: %s%n", properties.get("java.home"));
formatter.format("Java Vendor: %s%n", properties.get("java.vendor"));
formatter.format("Java Version: %s%n", properties.get("java.version"));
formatter.format("JCE Installed: %s%n", BooleanUtils.toStringYesNo(isJceInstalled()));
formatter.format("%s%n", LINE_SEPARATOR);
formatter.format("OS Architecture: %s%n", properties.get("os.arch"));
formatter.format("OS Name: %s%n", properties.get("os.name"));
formatter.format("OS Version: %s%n", properties.get("os.version"));
formatter.format("%s%n", LINE_SEPARATOR);
injectEnvironmentInfoIntoBanner(formatter, environment, sourceClass);
return formatter.toString();
}
}
项目:cas-5.1.0
文件:DefaultPasswordEncoder.java
@Override
public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
final String encodedRawPassword = StringUtils.isNotBlank(rawPassword) ? encode(rawPassword.toString()) : null;
final boolean matched = StringUtils.equals(encodedRawPassword, encodedPassword);
LOGGER.debug("Provided password does{}match the encoded password", BooleanUtils.toString(matched, StringUtils.EMPTY, " not "));
return matched;
}
项目:NEILREN4J
文件:StringUtils.java
/**
* 转换为Boolean类型
* 'true', 'on', 'y', 't', 'yes' or '1' (case insensitive) will return true. Otherwise, false is returned.
*/
public static Boolean toBoolean(final Object val) {
if (val == null) {
return false;
}
return BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString());
}
项目:PTEAssistant
文件:UserSettingDao.java
public boolean saveUserSetting(UserSetting us) {
String startCalendarStr = CalendarUtils.formatYMDHM(us.apptSearchRule.startCalendar);
String endCalendarStr = us.apptSearchRule.endCalendar != null ? CalendarUtils.formatYMDHM(us.apptSearchRule.endCalendar) : "";
String format = "INSERT INTO usersetting("
+ "username,password,examCode,countryCode,city,stateCode,type,startCalendar,endCalendar,"
+ "applyType,paramVoucherNumber,"
+ "paymentType,cardNumber,cardHoldersName,cardExpYear,cardExpMonth,cardSecCode,"
+ "searchSeatOnly,loopRequestIntervalMS)"
+ "VALUES('%s','%s','%s','%s','%s','%s',%d,'%s','%s',%d,'%s',%d,'%s','%s',%d,%d,'%s',%d,%d)";
int rows = dbUtil.executeUpdate(
String.format(format,
us.user.username,
us.user.password,
us.examCode,
us.testCentersCriteria.get("countryCode"),
us.testCentersCriteria.get("city"),
us.testCentersCriteria.get("stateCode"),
us.apptSearchRule.type,
startCalendarStr,
endCalendarStr,
us.applyType,
us.paramVoucherNumber,
us.creditCard.get("paymentType"),
us.creditCard.get("cardNumber"),
us.creditCard.get("cardHoldersName"),
us.creditCard.get("cardExpYear"),
us.creditCard.get("cardExpMonth"),
us.creditCard.get("cardSecCode"),
BooleanUtils.toInteger(us.searchSeatOnly),
us.loopRequestIntervalMS));
return rows > 0;
}
项目:PTEAssistant
文件:UserSettingDao.java
public boolean updateUserSettingByUid(UserSetting us) {
String startCalendarStr = CalendarUtils.formatYMDHM(us.apptSearchRule.startCalendar);
String endCalendarStr = us.apptSearchRule.endCalendar != null ? CalendarUtils.formatYMDHM(us.apptSearchRule.endCalendar) : "";
String format = "UPDATE usersetting SET "
+ "username='%s',password='%s',"
+ "examCode='%s',countryCode='%s',city='%s',stateCode='%s',"
+ "type=%d,startCalendar='%s',endCalendar='%s',"
+ "applyType=%d,paramVoucherNumber='%s',"
+ "paymentType=%d,cardNumber='%s',cardHoldersName='%s',cardExpYear=%d,cardExpMonth=%d,cardSecCode='%s',"
+ "searchSeatOnly=%d,loopRequestIntervalMS=%d"
+ " WHERE uid=%d";
return dbUtil.executeUpdate(
String.format(format,
us.user.username,
us.user.password,
us.examCode,
us.testCentersCriteria.get("countryCode"),
us.testCentersCriteria.get("city"),
us.testCentersCriteria.get("stateCode"),
us.apptSearchRule.type,
startCalendarStr,
endCalendarStr,
us.applyType,
us.paramVoucherNumber,
us.creditCard.get("paymentType"),
us.creditCard.get("cardNumber"),
us.creditCard.get("cardHoldersName"),
us.creditCard.get("cardExpYear"),
us.creditCard.get("cardExpMonth"),
us.creditCard.get("cardSecCode"),
BooleanUtils.toInteger(us.searchSeatOnly),
us.loopRequestIntervalMS,
us.user.uid)) > 0;
}
项目:newrelic-alerts-configurator
文件:EmailChannelTypeSupport.java
@Override
public AlertsChannelConfiguration generateAlertsChannelConfiguration(NewRelicApi api) {
EmailChannel emailChannel = (EmailChannel) channel;
AlertsChannelConfiguration.AlertsChannelConfigurationBuilder builder = AlertsChannelConfiguration.builder();
builder.recipients(emailChannel.getEmailAddress());
if (BooleanUtils.isTrue(emailChannel.getIncludeJsonAttachment())) {
builder.includeJsonAttachment(emailChannel.getIncludeJsonAttachment());
}
return builder.build();
}
项目:airsonic
文件:MainController.java
private <T> boolean trimToSize(Boolean showAll, List<T> list, int userPaginationPreference) {
boolean trimmed = false;
if(!BooleanUtils.isTrue(showAll)) {
if(list.size() > userPaginationPreference) {
trimmed = true;
list.subList(userPaginationPreference, list.size()).clear();
}
}
return trimmed;
}
项目:oscm
文件:OperationRecordCtrl.java
public void onFilterOperationsChange(final AjaxBehaviorEvent event) {
final Boolean myOpsOnlyNegated = BooleanUtils.negate(this.isMyOperationsOnly());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
"onFilterOperationsChange(event=%s) triggered, reloading records with myOperationsFlag=%s", event,
myOpsOnlyNegated));
}
this.loadOperationRecords(myOpsOnlyNegated);
}
项目:plugin-prov
文件:ProvQuoteInstanceResource.java
/**
* Save or update the given entity from the {@link QuoteInstanceEditionVo}. The
* computed cost are recursively updated from the instance to the quote total
* cost.
*/
private UpdatedCost saveOrUpdate(final ProvQuoteInstance entity, final QuoteInstanceEditionVo vo) {
// Compute the unbound cost delta
final int deltaUnbound = BooleanUtils.toInteger(vo.getMaxQuantity() == null) - BooleanUtils.toInteger(entity.isUnboundCost());
// Check the associations and copy attributes to the entity
final ProvQuote configuration = getQuoteFromSubscription(vo.getSubscription());
entity.setConfiguration(configuration);
final Subscription subscription = configuration.getSubscription();
final String providerId = subscription.getNode().getRefined().getId();
DescribedBean.copy(vo, entity);
entity.setPrice(ipRepository.findOneExpected(vo.getPrice()));
entity.setLocation(resource.findLocation(subscription.getId(), vo.getLocation()));
entity.setUsage(Optional.ofNullable(vo.getUsage()).map(u -> resource.findConfigured(usageRepository, u)).orElse(null));
entity.setOs(ObjectUtils.defaultIfNull(vo.getOs(), entity.getPrice().getOs()));
entity.setRam(vo.getRam());
entity.setCpu(vo.getCpu());
entity.setConstant(vo.getConstant());
entity.setEphemeral(vo.isEphemeral());
entity.setInternet(vo.getInternet());
entity.setMaxVariableCost(vo.getMaxVariableCost());
entity.setMinQuantity(vo.getMinQuantity());
entity.setMaxQuantity(vo.getMaxQuantity());
resource.checkVisibility(entity.getPrice().getType(), providerId);
checkConstraints(entity);
checkOs(entity);
// Update the unbound increment of the global quote
configuration.setUnboundCostCounter(configuration.getUnboundCostCounter() + deltaUnbound);
// Save and update the costs
final UpdatedCost cost = newUpdateCost(entity);
final Map<Integer, FloatingCost> storagesCosts = new HashMap<>();
CollectionUtils.emptyIfNull(entity.getStorages())
.forEach(s -> storagesCosts.put(s.getId(), addCost(s, storageResource::updateCost)));
cost.setRelatedCosts(storagesCosts);
cost.setTotalCost(toFloatingCost(entity.getConfiguration()));
return cost;
}