下面列出了怎么用org.apache.commons.lang.BooleanUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 读取数据字典
*
* @return
*/
@PostMapping("meta")
public Response meta() {
MetaEntity metaEntity = MetaEntity.localEntity(getEntityName());
JSONObject json = (JSONObject) JSONObject.toJSON(metaEntity);
JSONObject properties = json.getJSONObject("properties");
// 判断是否开启编号必填,如果是必填,需要修改编号校验必填
SysOrgConfig config = sysOrgConfigService.getSysOrgConfig();
if (BooleanUtils.isTrue(config.getIsNoRequired())) {
JSONObject fdNo = properties.getJSONObject("fdNo");
fdNo.put("notNull", true);
}
if (BooleanUtils.isTrue(config.getKeepGroupUnique())) {
JSONObject fdName = properties.getJSONObject("fdName");
fdName.put("unique", true);
}
return Response.ok(json);
}
@Override
public void loadState(Element state) {
Element fwList = state.getChild("compilers");
if (fwList != null) {
Element fw = fwList.getChild("compiler");
if (fw != null) {
String url = fw.getAttributeValue("url");
if (url != null) {
boolean noWarn = BooleanUtils.toBoolean(fw.getAttributeValue("nowarn"));
boolean strict = BooleanUtils.toBoolean(fw.getAttributeValue("strict"));
boolean verbose = BooleanUtils.toBoolean(fw.getAttributeValue("verbose"));
boolean recurse = BooleanUtils.toBoolean(fw.getAttributeValue("recurse"));
boolean debug = BooleanUtils.toBoolean(fw.getAttributeValue("debug"));
boolean allowNegKeys = BooleanUtils.toBoolean(fw.getAttributeValue("allownegkeys"));
boolean allow64bitConsts = BooleanUtils.toBoolean(fw.getAttributeValue("allow64bitconsts"));
myConfig = new ThriftConfig(url, noWarn, strict, verbose, recurse, debug, allowNegKeys, allow64bitConsts);
}
}
}
}
private void initValidation() {
String message = ViewMessages.getMessage("IUI-000003");
commentField.addValidator(new StringLengthValidator(message, -1, 100, true));
if (PCCConstant.LOAD_BALANCER_ELB.equals(loadBalancerType)) {
if (BooleanUtils.isTrue(awsVpc)) {
message = ViewMessages.getMessage("IUI-000029");
securityGroupSelect.setRequired(true);
securityGroupSelect.setRequiredError(message);
message = ViewMessages.getMessage("IUI-000108");
subnetSelect.setRequired(true);
subnetSelect.setRequiredError(message);
}
}
}
public DnsProcessClient createDnsProcessClient() {
DnsProcessClient client = new DnsProcessClient();
// dnsStrategy
DnsStrategy dnsStrategy = createDnsStrategy();
client.setDnsStrategy(dnsStrategy);
// reverseEnabled
String reverseEnabled = Config.getProperty("dns.reverseEnabled");
client.setReverseEnabled(BooleanUtils.toBoolean(StringUtils.defaultIfEmpty(reverseEnabled, "true")));
return client;
}
/**
* {@inheritDoc}
*/
@Override
public InstanceStatus getInstanceStatus(Instance instance) {
// 有効無効に応じてステータスを変更する(画面表示用)
InstanceStatus instanceStatus = InstanceStatus.fromStatus(instance.getStatus());
if (BooleanUtils.isTrue(instance.getEnabled())) {
if (instanceStatus == InstanceStatus.STOPPED) {
instance.setStatus(InstanceStatus.STARTING.toString());
}
} else {
if (instanceStatus == InstanceStatus.RUNNING || instanceStatus == InstanceStatus.WARNING) {
instance.setStatus(InstanceStatus.STOPPING.toString());
}
}
// 画面表示用にステータスの変更
// サーバステータス 協調設定ステータス 変換後サーバステータス
// Running Coodinating Configuring
// Running Warning Warning
instanceStatus = InstanceStatus.fromStatus(instance.getStatus());
InstanceCoodinateStatus insCoodiStatus = InstanceCoodinateStatus.fromStatus(instance.getCoodinateStatus());
// サーバステータス(Running)かつ協調設定ステータス(Coodinating)⇒「Configuring」
if (instanceStatus == InstanceStatus.RUNNING && insCoodiStatus == InstanceCoodinateStatus.COODINATING) {
instance.setStatus(InstanceStatus.CONFIGURING.toString());
// サーバステータス(Running)かつ協調設定ステータス(Warning)⇒「Warning」
} else if (instanceStatus == InstanceStatus.RUNNING && insCoodiStatus == InstanceCoodinateStatus.WARNING) {
instance.setStatus(InstanceStatus.WARNING.toString());
}
return InstanceStatus.fromStatus(instance.getStatus());
}
private static boolean chooseIndex(Map<String, Object> extraCmd) {
String ifChooseIndex = ObjectUtils.toString(GeneralUtil.getExtraCmdString(extraCmd,
ExtraCmd.CHOOSE_INDEX));
// 默认返回true
if (StringUtils.isEmpty(ifChooseIndex)) {
return true;
} else {
return BooleanUtils.toBoolean(ifChooseIndex);
}
}
/** {@inheritDoc} */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm formIn,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm daForm = (DynaActionForm) formIn;
RequestContext ctx = new RequestContext(request);
User user = ctx.getCurrentUser();
if (!user.hasRole(RoleFactory.ORG_ADMIN)) {
throw new PermissionException(RoleFactory.ORG_ADMIN);
}
Org org = user.getOrg();
if (ctx.isSubmitted()) {
Boolean createDefaultSG = BooleanUtils.toBoolean(
(Boolean) daForm.get(CREATE_DEFAULT_SG));
// store the value
org.getOrgConfig().setCreateDefaultSg(createDefaultSG);
createSuccessMessage(request, "message.sg.configupdated", null);
return mapping.findForward("success");
}
// not submitted
setupForm(request, daForm, org);
return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public AddAwsAddressResponse addAwsAddress(@QueryParam(PARAM_NAME_PLATFORM_NO) String platformNo) {
// 入力チェック
ApiValidate.validatePlatformNo(platformNo);
// ユーザ取得
User user = checkAndGetUser();
// プラットフォーム取得
Platform platform = platformDao.read(Long.parseLong(platformNo));
// プラットフォームが存在しない場合
if (platform == null) {
throw new AutoApplicationException("EAPI-100000", "Platform", PARAM_NAME_PLATFORM_NO, platformNo);
}
// プラットフォームを選択できない場合
if (BooleanUtils.isNotTrue(platform.getSelectable())) {
throw new AutoApplicationException("EAPI-000020", "Platform", PARAM_NAME_PLATFORM_NO, platformNo);
}
// プラットフォームを利用できない場合
if (!platformService.isUsablePlatform(user.getUserNo(), platform)) {
throw new AutoApplicationException("EAPI-000020", "Platform", PARAM_NAME_PLATFORM_NO, platformNo);
}
// AWSアドレスを作成
AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(user.getUserNo(),
platform.getPlatformNo());
AwsAddress awsAddress = awsAddressProcess.createAddress(awsProcessClient);
AwsAddressResponse awsAddressResponse = new AwsAddressResponse(awsAddress);
AddAwsAddressResponse response = new AddAwsAddressResponse(awsAddressResponse);
return response;
}
public void stop(Long loadBalancerNo) {
LoadBalancer loadBalancer = loadBalancerDao.read(loadBalancerNo);
if (log.isInfoEnabled()) {
log.info(MessageUtils.getMessage("IPROCESS-200228", loadBalancerNo, loadBalancer.getLoadBalancerName()));
}
// DNSサーバからの削除
deleteDns(loadBalancerNo);
//Zabbixからの削除
Boolean useZabbix = BooleanUtils.toBooleanObject(Config.getProperty("zabbix.useZabbix"));
if (BooleanUtils.isTrue(useZabbix)) {
zabbixLoadBalancerProcess.stopHost(loadBalancerNo);
}
//IaasGatewayWrapper作成
Farm farm = farmDao.read(loadBalancer.getFarmNo());
IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(),
loadBalancer.getPlatformNo());
// ELBの停止
gateway.stopLoadBalancer(loadBalancer.getLoadBalancerNo());
if (log.isInfoEnabled()) {
log.info(MessageUtils.getMessage("IPROCESS-200229", loadBalancerNo, loadBalancer.getLoadBalancerName()));
}
}
public NiftyInstanceResponse(NiftyInstance niftyInstance) {
this.instanceType = niftyInstance.getInstanceType();
this.status = niftyInstance.getStatus();
this.dnsName = niftyInstance.getDnsName();
this.privateDnsName = niftyInstance.getPrivateDnsName();
this.ipAddress = niftyInstance.getIpAddress();
this.privateIpAddress = niftyInstance.getPrivateIpAddress();
this.initialized = BooleanUtils.isTrue(niftyInstance.getInitialized());
}
/**
* @param name
* @param defaultValue
* @return
*/
public boolean getParameterAsBool(String name, boolean defaultValue) {
String value = getParameterMap().get(name);
if (StringUtils.isBlank(value)) {
return defaultValue;
}
return BooleanUtils.toBoolean(value);
}
/**
* Simple util to check if the Form was submitted
* @param form to check
* @return if or not it was submitted.
*/
protected boolean isSubmitted(DynaActionForm form) {
if (form != null) {
try {
return BooleanUtils.toBoolean((Boolean)form.get(SUBMITTED));
}
catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("Your form-bean failed to define '" +
SUBMITTED + "'");
}
}
return false;
}
public Boolean getBool(String header) {
String val = get(header);
if (StringUtils.isEmpty(val)) {
return null;
} else {
return BooleanUtils.toBoolean(val);
}
}
/**
* {@inheritDoc}
*/
@Override
public void startComponents(Long farmNo, Long componentNo, List<Long> instanceNos) {
// コンポーネントを有効にする
List<ComponentInstance> componentInstances = componentInstanceDao.readByComponentNo(componentNo);
for (ComponentInstance componentInstance : componentInstances) {
if (!instanceNos.contains(componentInstance.getInstanceNo())) {
continue;
}
if (BooleanUtils.isNotTrue(componentInstance.getAssociate())) {
// 関連付けが無効なコンポーネントは無効にする
if (BooleanUtils.isTrue(componentInstance.getEnabled())
|| BooleanUtils.isNotTrue(componentInstance.getConfigure())) {
componentInstance.setEnabled(false);
componentInstance.setConfigure(true);
componentInstanceDao.update(componentInstance);
}
continue;
}
if (BooleanUtils.isNotTrue(componentInstance.getEnabled())
|| BooleanUtils.isNotTrue(componentInstance.getConfigure())) {
componentInstance.setEnabled(true);
componentInstance.setConfigure(true);
componentInstanceDao.update(componentInstance);
}
}
// インスタンスが起動していない場合は起動する
List<Instance> instances = instanceDao.readInInstanceNos(instanceNos);
for (Instance instance : instances) {
if (BooleanUtils.isNotTrue(instance.getEnabled())) {
instance.setEnabled(true);
instanceDao.update(instance);
}
}
// ファームを更新処理対象として登録
scheduleFarm(farmNo);
}
private void transferFlagEdits(DynaActionForm form,
SystemDetailsCommand command) {
command.enableConfigManagement(BooleanUtils.toBoolean(form
.getString("configManagement")));
command.enableRemoteCommands(BooleanUtils.toBoolean(form
.getString("remoteCommands")));
}
/**
* On networks with security group, it removes the network rules related to the migrated VM from the source host.
*/
protected void destroyMigratedVmNetworkRulesOnSourceHost(final MigrateCommand command, final CitrixResourceBase citrixResourceBase, final Connection conn, Host dsthost)
throws BadServerResponse, XenAPIException, XmlRpcException {
if (citrixResourceBase.canBridgeFirewall()) {
final String result = citrixResourceBase.callHostPlugin(conn, "vmops", "destroy_network_rules_for_vm", "vmName", command.getVmName());
if (BooleanUtils.toBoolean(result)) {
s_logger.debug(String.format("Removed network rules from source host [%s] for migrated vm [%s]", dsthost.getHostname(conn), command.getVmName()));
} else {
s_logger.warn(String.format("Failed to remove network rules from source host [%s] for migrated vm [%s]", dsthost.getHostname(conn), command.getVmName()));
}
}
}
private void loadData() {
// プラットフォーム情報を取得
LoadBalancerService loadBalancerService = BeanContext.getBean(LoadBalancerService.class);
platforms = loadBalancerService.getPlatforms(ViewContext.getUserNo());
// 有効でないプラットフォーム情報を除外
for (int i = platforms.size() - 1; i >= 0; i--) {
if (BooleanUtils.isNotTrue(platforms.get(i).getPlatform().getSelectable())) {
platforms.remove(i);
}
}
// プラットフォーム情報をソート
Collections.sort(platforms, new Comparator<LoadBalancerPlatformDto>() {
@Override
public int compare(LoadBalancerPlatformDto o1, LoadBalancerPlatformDto o2) {
int order1 = (o1.getPlatform().getViewOrder() != null) ? o1.getPlatform().getViewOrder()
: Integer.MAX_VALUE;
int order2 = (o2.getPlatform().getViewOrder() != null) ? o2.getPlatform().getViewOrder()
: Integer.MAX_VALUE;
return order1 - order2;
}
});
// サービス情報を取得
ComponentService componentService = BeanContext.getBean(ComponentService.class);
components = componentService.getComponents(ViewContext.getFarmNo());
}
private boolean md5cryptRootPw(List<Map> options) {
for (Map m : options) {
if ("md5_crypt_rootpw".equals(m.get("name"))) {
return BooleanUtils.toBoolean((String)m.get("arguments"));
}
}
return false;
}
/**
* Converts the object to a boolean.
*/
protected Boolean toBoolean(Object object) {
if (object == null || object instanceof Boolean) {
return (Boolean) object;
}
return BooleanUtils.toBoolean(ObjectUtils.toString(object));
}
/**
* Returns true if the document handler should open in a new window.
*/
protected boolean isDocumentHandlerPopup() {
return BooleanUtils.toBooleanDefaultIfNull(
CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(
KewApiConstants.KEW_NAMESPACE,
KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE,
KewApiConstants.DOCUMENT_SEARCH_DOCUMENT_POPUP_IND),
DOCUMENT_HANDLER_POPUP_DEFAULT);
}
public static boolean isSkipPaging( Boolean skipPaging, Boolean paging )
{
if ( skipPaging != null )
{
return BooleanUtils.toBoolean( skipPaging );
}
else if ( paging != null )
{
return !BooleanUtils.toBoolean( paging );
}
return false;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Instant start = now();
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
throw new ServletException("LoggingFilter just supports HTTP requests");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (!BooleanUtils.toBoolean(appConfiguration.getHttpLoggingEnabled())) {
chain.doFilter(httpRequest, httpResponse);
return;
}
Set<String> excludedPaths = appConfiguration.getHttpLoggingExludePaths();
if (!CollectionUtils.isEmpty(excludedPaths)) {
for (String excludedPath : excludedPaths) {
String requestURI = httpRequest.getRequestURI();
if (requestURI.startsWith(excludedPath)) {
chain.doFilter(httpRequest, httpResponse);
return;
}
}
}
RequestWrapper requestWrapper = new RequestWrapper(httpRequest);
ResponseWrapper responseWrapper = new ResponseWrapper(httpResponse);
chain.doFilter(httpRequest, httpResponse);
Duration duration = duration(start);
// yuriyz: log request and response only after filter handling.
// #914 - we don't want to effect server functionality due to logging. Currently content can be messed if it is InputStream.
if (log.isDebugEnabled()) {
log.debug(getRequestDescription(requestWrapper, duration));
log.debug(getResponseDescription(responseWrapper));
}
}
public String updateHost(String hostid, String hostname, String fqdn, List<Hostgroup> hostgroups, Boolean status,
Boolean userIp, String ip, String proxyHostid) {
HostUpdateParam param = new HostUpdateParam();
param.setHostid(hostid);
param.setHost(hostname);
param.setGroups(hostgroups);
param.setDns(fqdn);
param.setPort(10050);
if (status != null) {
param.setStatus(status ? 0 : 1);// 有効の場合は0、無効の場合は1
}
if (userIp != null) {
param.setUseip(BooleanUtils.toInteger(userIp));// DNSの場合は0、IPの場合は1
param.setIp(StringUtils.isEmpty(ip) ? "0.0.0.0" : ip);
}
if (StringUtils.isNotEmpty(proxyHostid)) {
param.setProxyHostid(proxyHostid);
}
List<String> hostids = zabbixClient.host().update(param);
hostid = hostids.get(0);
if (log.isInfoEnabled()) {
List<String> groupids = new ArrayList<String>();
if (hostgroups != null) {
for (Hostgroup hostgroup : hostgroups) {
groupids.add(hostgroup.getGroupid());
}
}
log.info(MessageUtils.getMessage("IPROCESS-100312", hostid, fqdn, groupids, status));
}
return hostid;
}
/**
* TODO: メソッドコメント
*
* @param instanceNo
*/
public void startDns(Long instanceNo) {
Instance instance = instanceDao.read(instanceNo);
Platform platform = platformDao.read(instance.getPlatformNo());
if (BooleanUtils.isTrue(platform.getInternal())) {
// 内部のプラットフォームの場合
PlatformAws platformAws = platformAwsDao.read(platform.getPlatformNo());
if (BooleanUtils.isTrue(platformAws.getEuca())) {
// Eucalyptusの場合
startDnsEuca(instanceNo);
} else {
// Amazon EC2の場合
if (BooleanUtils.isTrue(platformAws.getVpc())) {
// VPC環境の場合
startDnsNormal(instanceNo);
} else {
// 非VPC環境の場合
startDnsClassic(instanceNo);
}
}
} else {
// 外部のプラットフォームの場合
Image image = imageDao.read(instance.getImageNo());
if (StringUtils.startsWithIgnoreCase(image.getOs(), "windows")) {
// Windowsイメージの場合、VPNを使用していないものとする
startDnsClassic(instanceNo);
} else {
// VPNを使用している場合
startDnsVpn(instanceNo);
}
}
// イベントログ出力
instance = instanceDao.read(instanceNo);
processLogger.debug(null, instance, "DnsRegist", new Object[] { instance.getFqdn(), instance.getPublicIp() });
}
/**
* 使用可能なイメージ番号のリストを取得する
*
* @return 使用可能なイメージ番号のリスト
*/
private List<Long> getEnabledImageNos() {
List<Long> imageNos = new ArrayList<Long>();
List<Image> images = imageDao.readAll();
for (Image image : images) {
if (BooleanUtils.isNotTrue(image.getSelectable())) {
//有効イメージではない場合、ロードバランサーイメージの場合はリストに含めない
continue;
}
imageNos.add(image.getImageNo());
}
return imageNos;
}
private void loadData() {
// サーバに関連付けられたサービスを取得
componentNos = new ArrayList<Long>();
List<ComponentInstanceDto> componentInstances = instance.getComponentInstances();
for (ComponentInstanceDto componentInstance : componentInstances) {
if (BooleanUtils.isTrue(componentInstance.getComponentInstance().getAssociate())) {
componentNos.add(componentInstance.getComponentInstance().getComponentNo());
}
}
}
@GET
@Path("/topologies/{topologyId}/testhistories/{historyId}")
@Timed
public Response getHistoryOfTestRunTopology (@Context UriInfo urlInfo,
@PathParam("topologyId") Long topologyId,
@PathParam("historyId") Long historyId,
@QueryParam("simplify") Boolean simplify,
@Context SecurityContext securityContext) throws Exception {
SecurityUtil.checkRoleOrPermissions(authorizer, securityContext, Roles.ROLE_TOPOLOGY_USER,
Topology.NAMESPACE, topologyId, READ);
TopologyTestRunHistory history = catalogService.getTopologyTestRunHistory(historyId);
if (history == null) {
throw EntityNotFoundException.byId(String.valueOf(historyId));
}
if (!history.getTopologyId().equals(topologyId)) {
throw BadRequestException.message("Test history " + historyId + " is not belong to topology " + topologyId);
}
if (BooleanUtils.isTrue(simplify)) {
return WSUtils.respondEntity(new SimplifiedTopologyTestRunHistory(history), OK);
} else {
return WSUtils.respondEntity(history, OK);
}
}
@GET
@Path("/namespaces")
@Timed
public Response listNamespaces(@Context UriInfo uriInfo,
@Context SecurityContext securityContext) {
List<QueryParam> queryParams = new ArrayList<>();
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
Collection<Namespace> namespaces;
Boolean detail = false;
if (params.isEmpty()) {
namespaces = environmentService.listNamespaces();
} else {
MultivaluedMap<String, String> copiedParams = new MultivaluedHashMap<>();
copiedParams.putAll(params);
List<String> detailOption = copiedParams.remove("detail");
if (detailOption != null && !detailOption.isEmpty()) {
detail = BooleanUtils.toBooleanObject(detailOption.get(0));
}
queryParams = WSUtils.buildQueryParameters(copiedParams);
namespaces = environmentService.listNamespaces(queryParams);
}
if (namespaces != null) {
boolean environmentUser = SecurityUtil.hasRole(authorizer, securityContext, Roles.ROLE_ENVIRONMENT_USER);
if (environmentUser) {
LOG.debug("Returning all environments since user has role: {}", Roles.ROLE_ENVIRONMENT_USER);
} else {
namespaces = SecurityUtil.filter(authorizer, securityContext, Namespace.NAMESPACE, namespaces, READ);
}
return buildNamespacesGetResponse(namespaces, detail);
}
throw EntityNotFoundException.byFilter(queryParams.toString());
}
private Response buildNamespacesGetResponse(Collection<Namespace> namespaces, Boolean detail) {
if (BooleanUtils.isTrue(detail)) {
List<CatalogResourceUtil.NamespaceWithMapping> namespacesWithMapping = namespaces.stream()
.map(namespace -> CatalogResourceUtil.enrichNamespace(namespace, environmentService))
.collect(toList());
return WSUtils.respondEntities(namespacesWithMapping, OK);
} else {
return WSUtils.respondEntities(namespaces, OK);
}
}
/**
* 使用可能なコンポーネントタイプ番号のリストを取得する
*
* @return 使用可能なコンポーネントタイプ番号のリスト
*/
private List<Long> getEnabledComponentTypeNos() {
List<Long> componentTypeNos = new ArrayList<Long>();
List<ComponentType> componentTypes = componentTypeDao.readAll();
for (ComponentType componentType : componentTypes) {
if (BooleanUtils.isNotTrue(componentType.getSelectable())) {
//有効コンポーネントタイプではない場合、ロードバランサーイメージの場合はリストに含めない
continue;
}
componentTypeNos.add(componentType.getComponentTypeNo());
}
return componentTypeNos;
}