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

The following examples show how to use org.apache.commons.lang.StringUtils#isEmpty() . 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
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void persistServiceGroup(ServiceGroup servicegroup) {
    try {
        startTenantFlow();
        if (servicegroup == null || StringUtils.isEmpty(servicegroup.getName())) {
            throw new IllegalArgumentException("Cartridge group or group name can not be null");
        }
        String resourcePath = AutoscalerConstants.AUTOSCALER_RESOURCE + AutoscalerConstants.SERVICE_GROUP + "/"
                + servicegroup.getName();
        persist(servicegroup, resourcePath);
        if (log.isDebugEnabled()) {
            log.debug(
                    String.format("Persisted cartridge group %s at path %s", servicegroup.getName(), resourcePath));
        }
    } finally {
        endTenantFlow();
    }
}
 
Example 2
Source File: PublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/api/servicedef/name/{name}")
@PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@Produces({ "application/json", "application/xml" })
public RangerServiceDef updateServiceDefByName(RangerServiceDef serviceDef,
                                     @PathParam("name") String name) {
	// serviceDef.name is immutable
	// if serviceDef.name is specified, it should be same as the param 'name'
	if(serviceDef.getName() == null) {
		serviceDef.setName(name);
	} else if(!serviceDef.getName().equals(name)) {
		throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "serviceDef name mismatch", true);
	}

	// ignore serviceDef.id - if specified. Retrieve using the given name and use id from the retrieved object
	RangerServiceDef existingServiceDef = getServiceDefByName(name);
	serviceDef.setId(existingServiceDef.getId());
	if(StringUtils.isEmpty(serviceDef.getGuid())) {
		serviceDef.setGuid(existingServiceDef.getGuid());
	}

	return serviceREST.updateServiceDef(serviceDef);
}
 
Example 3
Source File: PurchasingAccountsPayableReportDaoOjb.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get Document type code selection
 *
 * @param fieldValues
 * @return
 */
protected Collection getDocumentType(Map fieldValues) {
    Collection docTypeCodes = new ArrayList<String>();

    if (fieldValues.containsKey(CabPropertyConstants.GeneralLedgerEntry.FINANCIAL_DOCUMENT_TYPE_CODE)) {
        String fieldValue = (String) fieldValues.get(CabPropertyConstants.GeneralLedgerEntry.FINANCIAL_DOCUMENT_TYPE_CODE);
        if (StringUtils.isEmpty(fieldValue)) {
            docTypeCodes.add(CabConstants.PREQ);
            docTypeCodes.add(CabConstants.CM);
        }
        else {
            docTypeCodes.add(fieldValue);
        }
        // truncate the non-property filed
        fieldValues.remove(CabPropertyConstants.GeneralLedgerEntry.FINANCIAL_DOCUMENT_TYPE_CODE);
    }

    return docTypeCodes;
}
 
Example 4
Source File: TemCardApplicationAction.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    ActionForward forward = super.docHandler(mapping, form, request, response);

    Person currentUser = GlobalVariables.getUserSession().getPerson();
    TemCardApplicationForm applicationForm = (TemCardApplicationForm)form;

    String command = applicationForm.getCommand();
    if (StringUtils.equals(KewApiConstants.INITIATE_COMMAND,command)) {
        final TemProfile profile = SpringContext.getBean(TemProfileService.class).findTemProfileByPrincipalId(currentUser.getPrincipalId());
        if (profile == null){
            applicationForm.setEmptyProfile(true);
            forward =  mapping.findForward(ERROR_FORWARD);
        } else {
            if (StringUtils.isEmpty(profile.getDefaultAccount())){
                applicationForm.setEmptyAccount(true);
                forward =  mapping.findForward(ERROR_FORWARD);
            }
        }
    }

    return forward;
}
 
Example 5
Source File: TemDocumentExpenseLineValidation.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method validated following rules
 *
 * 1.Raises warning if note is not entered
 *
 * @param actualExpense
 * @param document
 * @return boolean
 */
protected boolean validateAirfareRules(ActualExpense actualExpense, TravelDocument document) {
    boolean success = true;
    MessageMap message = GlobalVariables.getMessageMap();

    if (actualExpense.isAirfare() && StringUtils.isEmpty(actualExpense.getDescription())) {
        boolean justificationAdded = false;

        for ( TemExpense expenseDetail : actualExpense.getExpenseDetails()) {
            justificationAdded = StringUtils.isEmpty(expenseDetail.getDescription()) ? false : true;
        }

        if (!message.containsMessageKey(TemPropertyConstants.TEM_ACTUAL_EXPENSE_NOTCE) && !justificationAdded){
            if (isWarningOnly()) {
                message.putWarning(TemPropertyConstants.TEM_ACTUAL_EXPENSE_NOTCE, TemKeyConstants.WARNING_NOTES_JUSTIFICATION);
            } else {
                removeWarningsForProperty(TemPropertyConstants.TEM_ACTUAL_EXPENSE_NOTCE);
                message.putError(TemPropertyConstants.TEM_ACTUAL_EXPENSE_NOTCE, TemKeyConstants.WARNING_NOTES_JUSTIFICATION);
                success = false;
            }
        }
    }

    return success;
}
 
Example 6
Source File: FSUtil.java    From griffin with Apache License 2.0 6 votes vote down vote up
private static void initFileSystem() {
    Configuration conf = new Configuration();
    if (!StringUtils.isEmpty(fsDefaultName)) {
        conf.set("fs.defaultFS", fsDefaultName);
        LOGGER.info("Setting fs.defaultFS:{}", fsDefaultName);
    }

    if (StringUtils.isEmpty(conf.get("fs.hdfs.impl"))) {
        LOGGER.info("Setting fs.hdfs.impl:{}", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
        conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
    }
    if (StringUtils.isEmpty(conf.get("fs.file.impl"))) {
        LOGGER.info("Setting fs.file.impl:{}", org.apache.hadoop.fs.LocalFileSystem.class.getName());
        conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
    }
    try {
        fileSystem = FileSystem.get(conf);
    } catch (Exception e) {
        LOGGER.error("Can not get hdfs file system. {}", e);
        fileSystem = defaultFS;
    }

}
 
Example 7
Source File: IgnoreEntryOccurrence.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Static helper to read {@link IgnoreEntryOccurrence} from the input stream.
 *
 * @param in input stream
 * @return read {@link IgnoreEntryOccurrence}
 */
@NotNull
public static synchronized IgnoreEntryOccurrence deserialize(@NotNull DataInput in) throws IOException {
    final String url = in.readUTF();
    final ArrayList<Pair<String, Boolean>> items = new ArrayList<>();

    if (!StringUtils.isEmpty(url)) {
        final int size = in.readInt();
        for (int i = 0; i < size; i++) {
            String pattern = in.readUTF();
            Boolean isNegated = in.readBoolean();
            items.add(Pair.create(pattern, isNegated));
        }
    }

    return new IgnoreEntryOccurrence(url, items);
}
 
Example 8
Source File: NameExpressionFilter.java    From molicode with Apache License 2.0 6 votes vote down vote up
public void initNameFilter(){
	if(StringUtils.isEmpty(nameExpression) || initialed){
		return;
	}
	

	if(nameExpression.charAt(0)=='^'){	
		nameExpression=nameExpression.substring(1).trim();
		if(nameExpression.charAt(0)=='('||nameExpression.charAt(0)=='('){
			nameExpression=nameExpression.substring(1).trim();
		}
		if(nameExpression.endsWith(")")||nameExpression.endsWith(")")){
			nameExpression=nameExpression.substring(0,nameExpression.length()-1).trim();
		}
			not=true;
	}
	String[] filters=nameExpression.toLowerCase().split("[,,]"); 
	filterTypes=ColumnFilterType.getColumnFilterType(filters);
	initialed=true;
}
 
Example 9
Source File: RestServiceDispatcher.java    From iaf with Apache License 2.0 5 votes vote down vote up
private String unifyUriPattern(String uriPattern) {
	if (StringUtils.isEmpty(uriPattern)) {
		uriPattern="/";
	} else {
		if (!uriPattern.startsWith("/")) {
			uriPattern="/"+uriPattern;
		}
	}
	return uriPattern;
}
 
Example 10
Source File: EsInstance.java    From soundwave with Apache License 2.0 5 votes vote down vote up
public void setState(String state) throws InvalidStateTransitionException {
  if (StringUtils.isEmpty(this.state)) {
    this.state = state;
  } else if (!StringUtils.equals(this.state, state)) {
    if (STATE_TRANSITION_MAP.containsKey(this.state) && STATE_TRANSITION_MAP.get(this.state)
        .contains(state)) {
      this.state = state;
    } else {
      throw new InvalidStateTransitionException(
          String.format("Invalid transit state from %s to %s", this.state, state));
    }
  }
}
 
Example 11
Source File: LocalBinlogEventParser.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
@Override
protected EntryPosition findStartPosition(ErosaConnection connection) {
    // 处理逻辑
    // 1. 首先查询上一次解析成功的最后一条记录
    // 2. 存在最后一条记录,判断一下当前记录是否发生过主备切换
    // // a. 无机器切换,直接返回
    // // b. 存在机器切换,按最后一条记录的stamptime进行查找
    // 3. 不存在最后一条记录,则从默认的位置开始启动
    LogPosition logPosition = logPositionManager.getLatestIndexBy(destination);
    if (logPosition == null) {// 找不到历史成功记录
        EntryPosition entryPosition = masterPosition;

        // 判断一下是否需要按时间订阅
        if (StringUtils.isEmpty(entryPosition.getJournalName())) {
            // 如果没有指定binlogName,尝试按照timestamp进行查找
            if (entryPosition.getTimestamp() != null) {
                return new EntryPosition(entryPosition.getTimestamp());
            }
        } else {
            if (entryPosition.getPosition() != null) {
                // 如果指定binlogName + offest,直接返回
                return entryPosition;
            } else {
                return new EntryPosition(entryPosition.getTimestamp());
            }
        }
    } else {
        return logPosition.getPostion();
    }

    return null;
}
 
Example 12
Source File: ProcessValidator.java    From uflo with Apache License 2.0 5 votes vote down vote up
public void validate(Element element, List<String> errors,List<String> nodeNames) {
	boolean hasStart=false;
	boolean hasEnd=false;
	String name=element.getAttribute("name");
	if(StringUtils.isEmpty(name)){
		errors.add("流程模版未定义名称");
	}
	NodeList nodeList=element.getChildNodes();
	for(int i=0;i<nodeList.getLength();i++){
		Node node=nodeList.item(i);
		if(!(node instanceof Element)){
			continue;
		}
		Element childElement=(Element)node;
		for(Validator validator:validators){
			if(validator.support(childElement)){
				if(validator instanceof StartNodeValidator){
					hasStart=true;
				}
				if(validator instanceof EndNodeValidator){
					hasEnd=true;
				}
				validator.validate(childElement, errors,nodeNames);
			}
		}
	}
	if(!hasStart){
		errors.add("流程模版中未定义开始节点。");				
	}
	if(!hasEnd){
		errors.add("流程模版中未定义结束节点。");				
	}
}
 
Example 13
Source File: ExtendedContentIngestHelper.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected void addSecurityMetadataFromParms(CharSequence key, Object value, RawRecordContainer event) {
    // If fieldName is a security marking field (as configured by EVENT_SECURITY_MARKING_FIELD_NAMES),
    // then put the marking value into this.securityMarkings, where 'key' maps to the domain for the marking
    // (as configured by EVENT_SECURITY_MARKING_FIELD_DOMAINS)
    if (!StringUtils.isEmpty(key.toString()) && !StringUtils.isEmpty(value.toString())) {
        event.addSecurityMarking(this.helper.getSecurityMarkingFieldDomainMap().get(key.toString()), value.toString());
    }
}
 
Example 14
Source File: ConfigAclHandler.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Whether the config channel of the current context is of the given type.
 * The possible types are the labels of the different <code>ConfigChannelType</code>
 * statics found in com.redhat.rhn.domain.config.ConfigurationFactory.
 * @param ctx The current context.
 * @param params The params, must include desired channel type label.
 * @return Whether the current channel is of the given type.
 */
public boolean aclConfigChannelType(Object ctx, String[] params) {
    if (params.length < 1 || StringUtils.isEmpty(params[0])) {
        throw new IllegalArgumentException("Parameters must include type.");
    }
    ConfigChannel cc = getChannel((Map)ctx, params);
    //does the type in params match the channels type.
    return cc.getConfigChannelType().getLabel().equalsIgnoreCase(params[0]);
}
 
Example 15
Source File: ColumnBuilder.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
protected String getId(Column column){
	String id = column.getName();
	if (StringUtils.isEmpty(id)) {
		id = column.getCaption();
	}
	return id;
}
 
Example 16
Source File: PlayerGetProperties.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public String getPropertyValue(String property) {
    String paramProperty = getParamProperty(property);
    if (!item.containsKey(paramProperty)) {
        return null;
    }

    Object value = item.get(paramProperty);

    if (value instanceof List<?>) {
        List<?> values = (List<?>) value;

        // check if list contains any values
        if (values.size() == 0) {
            return null;
        }

        // some properties come back as a list with an indexer
        String paramPropertyIndex = getPropertyValue(paramProperty + "id");
        int propertyIndex;
        if (!StringUtils.isEmpty(paramPropertyIndex)) {
            // attempt to parse the property index
            try {
                propertyIndex = Integer.parseInt(paramPropertyIndex);
            } catch (NumberFormatException e) {
                return null;
            }

            // check if the index is valid
            if (propertyIndex < 0 || propertyIndex >= values.size()) {
                return null;
            }
        } else {
            // some properties come back as a list without an indexer,
            // e.g. artist, for these we return the first in the list
            propertyIndex = 0;
        }

        value = values.get(propertyIndex);
    }

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

    return value.toString();
}
 
Example 17
Source File: RequestUtil.java    From qconfig with MIT License 4 votes vote down vote up
private static boolean emptyIp(String ip) {
    return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
}
 
Example 18
Source File: PuppetComponentProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
protected void startAwsVolume(Long componentNo, Long instanceNo) {
    // デバイス名の取得
    String device = getAwsVolumeDevice();
    if (StringUtils.isEmpty(device)) {
        // デバイス名を取得できない場合はスキップ
        return;
    }

    // ボリューム情報の取得
    AwsVolume awsVolume = awsVolumeDao.readByComponentNoAndInstanceNo(componentNo, instanceNo);

    // ボリューム情報がない場合は作成する
    if (awsVolume == null) {
        // ディスクサイズの取得
        Integer diskSize = null;
        ComponentConfig diskSizeConfig = componentConfigDao.readByComponentNoAndConfigName(componentNo,
                ComponentConstants.CONFIG_NAME_DISK_SIZE);
        if (diskSizeConfig != null) {
            try {
                diskSize = Integer.valueOf(diskSizeConfig.getConfigValue());
            } catch (NumberFormatException ignore) {
            }
        }
        if (diskSize == null) {
            // ディスクサイズが指定されていない場合はスキップ
            return;
        }

        Instance instance = instanceDao.read(instanceNo);
        AwsInstance awsInstance = awsInstanceDao.read(instanceNo);

        awsVolume = new AwsVolume();
        awsVolume.setFarmNo(instance.getFarmNo());
        awsVolume.setVolumeName("vol");
        awsVolume.setPlatformNo(instance.getPlatformNo());
        awsVolume.setComponentNo(componentNo);
        awsVolume.setInstanceNo(instanceNo);
        awsVolume.setSize(diskSize);
        awsVolume.setAvailabilityZone(awsInstance.getAvailabilityZone());
        awsVolume.setDevice(device);
        awsVolumeDao.create(awsVolume);
    }
    // ディスクがアタッチされておらず、アタッチするデバイスが異なる場合は変更する
    else if (StringUtils.isEmpty(awsVolume.getInstanceId()) && !StringUtils.equals(device, awsVolume.getDevice())) {
        awsVolume.setDevice(device);
        awsVolumeDao.update(awsVolume);
    }

    // AwsProcessClientの作成
    Farm farm = farmDao.read(awsVolume.getFarmNo());
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(farm.getUserNo(),
            awsVolume.getPlatformNo());

    // ボリュームの開始処理
    awsVolumeProcess.startVolume(awsProcessClient, instanceNo, awsVolume.getVolumeNo());
}
 
Example 19
Source File: BookAnalysisServiceImpl.java    From DouBiNovel with Apache License 2.0 4 votes vote down vote up
@Override
public MvcResult searchByName(String name) {
    MvcResult result = MvcResult.create();
    if (StringUtils.isEmpty(name)) {
        result.setSuccess(false);
        result.setMessage("搜索名称不能为空");
    } else {
        List<BookInfo> list = new ArrayList<>();
        List<BookSource> bookSources = bookSourceService.getAll();
        if (bookSources== null || bookSources.size() == 0){
            result.setSuccess(false);
            result.setMessage("请添加书源");
        }else {
            List<Future<MvcResult>> futureList = new ArrayList<>(bookSources.size());
            for (BookSource bookSource : bookSources){
                futureList.add(bookSourceAnalysisService.searchByName(name,bookSource));
            }

            boolean isAllError = true;
            StringBuffer errorMsg = new StringBuffer();

            for (int index = 0; index < futureList.size(); index++){
                Future<MvcResult> future = futureList.get(index);
                try {
                    MvcResult searchResult = future.get();
                    if (searchResult.isSuccess()){
                        list.addAll(searchResult.getVal("list"));
                        isAllError = false;
                    }else {
                        errorMsg.append("书源【"+bookSources.get(index)+"】查询出错:");
                        if (StringUtils.isBlank(searchResult.getMessage())){
                            errorMsg.append("未知原因");
                        }else {
                            errorMsg.append(searchResult.getMessage());
                        }
                        errorMsg.append(";\n");
                    }
                }catch (Exception e){
                    errorMsg.append("书源【"+bookSources.get(index)+"】加载出错:");
                    if (StringUtils.isBlank(e.getMessage())){
                        errorMsg.append("未知原因");
                    }else {
                        errorMsg.append(e.getMessage());
                    }
                    errorMsg.append(";\n");
                }
            }

            if (isAllError){
                result.setSuccess(false);
                result.setMessage(errorMsg.toString());
                logger.error("书籍搜素出错:"+result.getMessage());
            }else {
                result.addVal("list", list);
            }
        }
    }
    return result;
}
 
Example 20
Source File: MultiNodeCluster.java    From pxf with Apache License 2.0 2 votes vote down vote up
/**
 * escape spaces in file name, so command line commands will work.
 *
 * @param file
 * @return escaped file name
 */
private String escapeSpaces(String file) {
    if (StringUtils.isEmpty(file))
        return file;
    return file.replace(" ", "\\ ");
}