Java Code Examples for org.apache.commons.lang3.BooleanUtils#toBoolean()

The following examples show how to use org.apache.commons.lang3.BooleanUtils#toBoolean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
protected List<Route> inquiring(AeiObjects aeiObjects, Choice choice) throws Exception {
	List<Route> results = new ArrayList<>();
	/* 多条路由进行判断 */
	for (Route o : aeiObjects.getRoutes()) {
		ScriptContext scriptContext = aeiObjects.scriptContext();
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_ROUTE, o);
		Object obj = aeiObjects.business().element()
				.getCompiledScript(aeiObjects.getWork().getApplication(), o, Business.EVENT_ROUTE)
				.eval(scriptContext);
		if (BooleanUtils.toBoolean(StringUtils.trimToNull(Objects.toString(obj))) == true) {
			results.add(o);
			break;
		}
	}
	return results;
}
 
Example 2
Source Project: gocd   File: EnvironmentVariableConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setConfigAttributes(Object attributes) {
    Map attributeMap = (Map) attributes;
    this.name = (String) attributeMap.get(EnvironmentVariableConfig.NAME);
    String value = (String) attributeMap.get(EnvironmentVariableConfig.VALUE);
    if (StringUtils.isBlank(name) && StringUtils.isBlank(value)) {
        throw new IllegalArgumentException(String.format("Need not null/empty name & value %s:%s", this.name, value));
    }
    this.isSecure = BooleanUtils.toBoolean((String) attributeMap.get(EnvironmentVariableConfig.SECURE));
    Boolean isChanged = BooleanUtils.toBoolean((String) attributeMap.get(EnvironmentVariableConfig.ISCHANGED));
    if (isSecure) {
        this.encryptedValue = isChanged ? new EncryptedVariableValueConfig(encrypt(value)) : new EncryptedVariableValueConfig(value);
    } else {
        this.value = new VariableValueConfig(value);
    }
    this.secretParamsForValue = parseSecretParams();
}
 
Example 3
Source Project: jinjava   File: IndentFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  int width = 4;
  if (args.length > 0) {
    width = NumberUtils.toInt(args[0], 4);
  }

  boolean indentFirst = false;
  if (args.length > 1) {
    indentFirst = BooleanUtils.toBoolean(args[1]);
  }

  List<String> indentedLines = new ArrayList<>();
  for (String line : NEWLINE_SPLITTER.split(Objects.toString(var, ""))) {
    int thisWidth = indentedLines.size() == 0 && !indentFirst ? 0 : width;
    indentedLines.add(StringUtils.repeat(' ', thisWidth) + line);
  }

  return NEWLINE_JOINER.join(indentedLines);
}
 
Example 4
Source Project: sailfish-core   File: EncodingUtility.java    License: Apache License 2.0 6 votes vote down vote up
@Description("Encodes string to base64.<br/>"+
        "<b>content</b> - string to encode.<br/>" +
        "<b>compress</b> - perform compression of the result string (y / Y / n / N).<br/>" +
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"n\") returns \"VGVzdCBjb250ZW50\"<br/>"+
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"y\") returns \"eJwLSS0uUUjOzytJzSsBAB2pBLw=\"<br/>")
@UtilityMethod
public String EncodeBase64(String content, Object compress) throws Exception{
    Boolean doCompress = BooleanUtils.toBoolean((String)compress);
    byte[] result;
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
         try (OutputStream b64 = new Base64OutputStream(os, true, -1, new byte[0]);
                InputStream ba = new ByteArrayInputStream(content.getBytes());
                InputStream is = doCompress ? new DeflaterInputStream(ba) : ba) {
            IOUtils.copy(is, b64);
        }
        os.flush();
        result = os.toByteArray();
    }
    return new String(result);
}
 
Example 5
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
    super.postProcessModelProperty(model, property);

    //Add imports for Jackson
    if (!BooleanUtils.toBoolean(model.isEnum)) {
        model.imports.add("JsonProperty");

        if (BooleanUtils.toBoolean(model.hasEnums)) {
            model.imports.add("JsonValue");
        }
    }
}
 
Example 6
Source Project: hub-detect   File: DetectPropertyMap.java    License: Apache License 2.0 5 votes vote down vote up
private Boolean convertBoolean(final String booleanString) {
    if (null == booleanString) {
        return null;
    }
    if (booleanString.equals("")) { //Support defaulting to true (--key is equivalent to --key=true)
        return true;
    }
    return BooleanUtils.toBoolean(booleanString);
}
 
Example 7
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
    // Add imports for Jackson
    if (!BooleanUtils.toBoolean(model.isEnum)) {
        model.imports.add("JsonProperty");

        if (BooleanUtils.toBoolean(model.hasEnums)) {
            model.imports.add("JsonValue");
    }
}
}
 
Example 8
Source Project: cuba   File: DynamicAttributesCondition.java    License: Apache License 2.0 5 votes vote down vote up
public DynamicAttributesCondition(Element element, String messagesPack, String filterComponentName, com.haulmont.chile.core.model.MetaClass metaClass) {
    super(element, messagesPack, filterComponentName, metaClass);

    propertyPath = element.attributeValue("propertyPath");

    MessageTools messageTools = AppBeans.get(MessageTools.NAME);
    locCaption = isBlank(caption)
            ? element.attributeValue("locCaption")
            : messageTools.loadString(messagesPack, caption);

    entityAlias = element.attributeValue("entityAlias");
    text = element.getText();
    join = element.attributeValue("join");
    categoryId = UUID.fromString(element.attributeValue("category"));
    String categoryAttributeValue = element.attributeValue("categoryAttribute");
    if (!Strings.isNullOrEmpty(categoryAttributeValue)) {
        categoryAttributeId = UUID.fromString(categoryAttributeValue);
    } else {
        //for backward compatibility
        List<Element> paramElements = element.elements("param");
        for (Element paramElement : paramElements) {
            if (BooleanUtils.toBoolean(paramElement.attributeValue("hidden", "false"), "true", "false")) {
                categoryAttributeId = UUID.fromString(paramElement.getText());
                String paramName = paramElement.attributeValue("name");
                text = text.replace(":" + paramName, "'" + categoryAttributeId + "'");
            }
        }
    }

    isCollection = Boolean.parseBoolean(element.attributeValue("isCollection"));
    resolveParam(element);
}
 
Example 9
public List<PackageDependency> parse(final List<String> packageDependenciesLines) throws IntegrationException {
    final List<PackageDependency> packageDependencies = new ArrayList<>();

    boolean started = false;
    for (final String rawLine : packageDependenciesLines) {
        final String line = rawLine.trim();

        if (!started) {
            started = line.startsWith(START_TOKEN);
            continue;
        } else if (StringUtils.isBlank(line) || line.startsWith("Required") || line.startsWith("REQUIRED")) {
            continue;
        }

        final String[] entry = line.split(" +");
        if (entry.length < 3) {
            throw new IntegrationException("Unable to parse package-dependencies");
        }

        final boolean required = BooleanUtils.toBoolean(entry[0]);
        final String type = entry[1].trim();
        final String[] namePieces = entry[2].split("/");
        final String name = namePieces[namePieces.length - 1].trim();

        if ("Package".equalsIgnoreCase(type)) {
            final PackageDependency packageDependency = new PackageDependency(name, required);
            packageDependencies.add(packageDependency);
        }
    }

    return packageDependencies;
}
 
Example 10
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
    //Add imports for Jackson
    if(!BooleanUtils.toBoolean(model.isEnum)) {
        model.imports.add("JsonProperty");

        if(BooleanUtils.toBoolean(model.hasEnums)) {
            model.imports.add("JsonValue");
        }
    }
}
 
Example 11
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
    super.postProcessModelProperty(model, property);

    //Add imports for Jackson
    if(!BooleanUtils.toBoolean(model.isEnum)) {
        model.imports.add("JsonProperty");

        if(BooleanUtils.toBoolean(model.hasEnums)) {
            model.imports.add("JsonValue");
        }
    }
}
 
Example 12
Source Project: easyweb   File: StringUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 转换为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());
}
 
Example 13
Source Project: cloudstack   File: TemplateAdapterBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TemplateProfile prepare(GetUploadParamsForTemplateCmd cmd) throws ResourceAllocationException {
    UploadParams params = new TemplateUploadParams(CallContext.current().getCallingUserId(), cmd.getName(),
            cmd.getDisplayText(), cmd.getBits(), BooleanUtils.toBoolean(cmd.isPasswordEnabled()),
            BooleanUtils.toBoolean(cmd.getRequiresHvm()), BooleanUtils.toBoolean(cmd.isPublic()),
            BooleanUtils.toBoolean(cmd.isFeatured()), BooleanUtils.toBoolean(cmd.isExtractable()), cmd.getFormat(), cmd.getOsTypeId(),
            cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), cmd.getChecksum(),
            cmd.getTemplateTag(), cmd.getEntityOwnerId(), cmd.getDetails(), BooleanUtils.toBoolean(cmd.isSshKeyEnabled()),
            BooleanUtils.toBoolean(cmd.isDynamicallyScalable()), BooleanUtils.toBoolean(cmd.isRoutingType()));
    return prepareUploadParamsInternal(params);
}
 
Example 14
Source Project: jinjava   File: XmlAttrFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  if (var == null || !Map.class.isAssignableFrom(var.getClass())) {
    return var;
  }

  @SuppressWarnings("unchecked")
  Map<String, Object> dict = (Map<String, Object>) var;
  List<String> attrs = new ArrayList<>();

  for (Map.Entry<String, Object> entry : dict.entrySet()) {
    attrs.add(
      new StringBuilder(entry.getKey())
        .append("=\"")
        .append(StringEscapeUtils.escapeXml10(Objects.toString(entry.getValue(), "")))
        .append("\"")
        .toString()
    );
  }

  String space = " ";
  if (args.length > 0 && !BooleanUtils.toBoolean(args[0])) {
    space = "";
  }

  return space + StringUtils.join(attrs, "\n");
}
 
Example 15
Source Project: oneops   File: NotificationFilter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Build a new message notification filter from the sink CI.
 *
 * @param sink {@link CmsCI} sink CI
 * @return newly built NotificationFilter. <code>null</code> if the message
 * filter is not enabled or N/A.
 */
public static NotificationFilter fromSinkCI(CmsCI sink) {
    // For backward compatibility, check if the filter attributes are present.
    CmsCIAttribute attr = sink.getAttribute("filter_enabled");
    if (attr != null) {
        boolean filterEnabled = Boolean.valueOf(attr.getDjValue());
        if (filterEnabled) {
            NotificationType eventType = NotificationType.valueOf(sink.getAttribute("event_type").getDjValue());
            NotificationSeverity eventSeverity = NotificationSeverity.valueOf(sink.getAttribute("severity_level").getDjValue());

            // NS Paths
            attr = sink.getAttribute("ns_paths");
            String[] nsPaths = null;
            if (attr != null) {
                nsPaths = toArray(attr.getDjValue());
            }
            // Monitoring clouds
            attr = sink.getAttribute("monitoring_clouds");
            String[] clouds = null;
            if (attr != null) {
                clouds = toArray(attr.getDjValue());
            }
            // Message selector pattern
            attr = sink.getAttribute("msg_selector_regex");
            String pattern = null;
            if (attr != null) {
                pattern = attr.getDjValue();
            }
            //Env profile
            attr = sink.getAttribute("env_profile");
            String envProfilePattern = null;
            if (attr != null) {
                envProfilePattern = attr.getDjValue();
            }
            //notification for action add/update
            attr = sink.getAttribute("notify_on");
            String notifyOn = null;
            if (attr != null) {
                notifyOn = attr.getDjValue();
            }

          // class Names
          attr = sink.getAttribute("cname");
          String[] classNames = null;
          if (attr != null) {
            classNames = toArray(attr.getDjValue());
          }
          // Monitoring clouds
          attr = sink.getAttribute("include_cis");
          boolean includeCi = false;
          if (attr != null) {
            includeCi = BooleanUtils.toBoolean(attr.getDjValue());
          }
            NotificationFilter filter = new NotificationFilter()
                    .eventType(eventType)
                    .eventSeverity(eventSeverity)
                    .clouds(clouds)
                    .nsPaths(nsPaths)
                    .selectorPattern(pattern)
                    .envProfilePattern(envProfilePattern)
                    .actions(notifyOn)
                    .classNames(classNames)
                    .includeCi(includeCi)  ;

            logger.info("Notification filter : " + filter);
            return filter;
        }
    }
    return null;
}
 
Example 16
private boolean isTrackingAvailableForMailing(int mailingId, int companyId) {
	String mailTrackTableName = String.format("mailtrack_%d_tbl", companyId);
	String query = String.format("SELECT COUNT(mailing_id) FROM %s WHERE mailing_id = ?", mailTrackTableName);
	return BooleanUtils.toBoolean(selectInt(logger, query, mailingId));
}
 
Example 17
private void setPrintInnerJoinOnClause(Session session) {
    boolean useInnerJoinOnClause = BooleanUtils.toBoolean(
            AppContext.getProperty("cuba.useInnerJoinOnClause"));
    session.getPlatform().setPrintInnerJoinInWhereClause(!useInnerJoinOnClause);
}
 
Example 18
Source Project: hygieia-core   File: HygieiaUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean allowSync(FeatureFlag featureFlag, CollectorType collectorType){
	if(featureFlag == null) return true;
	String key = StringUtils.lowerCase(collectorType.toString());
	if(MapUtils.isEmpty(featureFlag.getFlags()) || Objects.isNull(featureFlag.getFlags().get(key)) ) return true;
	return !BooleanUtils.toBoolean(featureFlag.getFlags().get(StringUtils.lowerCase(collectorType.toString())));
}
 
Example 19
Source Project: vscrawler   File: TypeCastUtils.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
static <T> T cast(Object obj, Class<T> clazz, final Class helpClazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("clazz is null");
    }

    if (Boolean.class.isAssignableFrom(clazz) || boolean.class.isAssignableFrom(clazz)) {
        //转化为boolean
        if (obj instanceof Boolean) {
            return (T) obj;
        }
        if (obj instanceof String) {
            return (T) (Boolean) BooleanUtils.toBoolean(obj.toString());
        }
        if (obj instanceof Collection) {
            return (T) (Boolean) (((Collection) obj).size() > 0);
        }
        return (T) (Boolean) (obj != null);
    }

    if (obj == null) {
        return null;
    }


    if (obj instanceof Collection) {
        Collection collection = (Collection) obj;
        if (helpClazz != Object.class && List.class.isAssignableFrom(clazz) || clazz == ArrayList.class || clazz == LinkedList.class) {
            collection = Collections2.transform(collection, new Function() {
                @Override
                public Object apply(Object input) {
                    if (input instanceof Element) {
                        return ((Element) input).ownText();
                    }
                    return TypeUtils.cast(input, helpClazz, ParserConfig.getGlobalInstance());
                }
            });
        }
        if (List.class.isAssignableFrom(clazz) || clazz == ArrayList.class) {
            return (T) Lists.newArrayList(collection);
        }
        if (clazz == LinkedList.class) {
            return (T) Lists.newLinkedList(collection);
        }
    }


    if (obj instanceof Element && !Element.class.isAssignableFrom(clazz)) {
        return (T) ((Element) obj).ownText();
    }


    return null;
}
 
Example 20
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    boolean disableFlattening = BooleanUtils.toBoolean(
            XmlUtils.selectSingleNodeValue(contentTypeField, disableFlatteningXPath));

    if (disableFlattening) {
        // Flattening is disabled, so use the generic item include type
        logger.debug("Flattening is disabled for node selector '{}'. Won't generate additional schema " +
            "types and fields for its items", graphQLFieldName);

        graphQLField.type(ITEM_INCLUDE_WRAPPER_TYPE);
        return;
    }

    String datasourceName = XmlUtils.selectSingleNodeValue(contentTypeField, datasourceNameXPath);
    String itemType = XmlUtils.selectSingleNodeValue(
        contentTypeDefinition, String.format(datasourceItemTypeXPathFormat, datasourceName));
    String itemGraphQLType = StringUtils.isNotEmpty(itemType)? getGraphQLName(itemType) : null;

    if (StringUtils.isEmpty(itemGraphQLType)) {
        // If there is no item content-type set in the datasource, use the generic item include type
        logger.debug("No specific item type found for node selector '{}'. Won't generate additional schema " +
            "types and fields for its items", graphQLFieldName);

        graphQLField.type(CONTENT_INCLUDE_WRAPPER_TYPE);
    } else {
        // If there is an item content-type, then create a specific GraphQL type for it
        logger.debug("Item type found for node selector '{}': '{}'. Generating additional schema types and " +
            "fields for the items...", itemGraphQLType, graphQLFieldName);

        GraphQLObjectType flattenedType = GraphQLObjectType.newObject()
            .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + "_flattened_item")
            .description("Contains the data from another item in the site")
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_VALUE)
                .description("The name of the item")
                .type(nonNull(GraphQLString)))
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_KEY)
                .description("The path of the item")
                .type(nonNull(GraphQLString)))
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_COMPONENT)
                .description("The content of the item")
                .type(GraphQLTypeReference.typeRef(itemGraphQLType)))
            .build();

        GraphQLObjectType wrapperType = GraphQLObjectType.newObject()
            .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEMS)
            .description("Wrapper for flattened items")
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_ITEM)
                .description("List of flattened items")
                .type(list(nonNull(flattenedType))))
            .build();

        graphQLField.type(wrapperType);
    }
}