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

The following are Jave code examples for showing how to use isEmpty() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: elastic-db-tools-for-java   File: ApplicationNameHelper.java   View Source Code Vote up 6 votes
/**
 * Adds suffix to the application name, but not exceeding certain length().
 *
 * @param originalApplicationName
 *            Application provided application name.
 * @param suffixToAppend
 *            Suffix to append to the application name.
 * @return Application name with suffix appended.
 */
public static String addApplicationNameSuffix(String originalApplicationName,
        String suffixToAppend) {
    if (originalApplicationName == null || StringUtils.isEmpty(originalApplicationName)) {
        return suffixToAppend;
    }

    if (suffixToAppend == null || StringUtils.isEmpty(suffixToAppend)) {
        return originalApplicationName;
    }

    int maxAppNameSubStringAllowed = MAX_APPLICATION_NAME_LENGTH - suffixToAppend.length();

    if (originalApplicationName.length() <= maxAppNameSubStringAllowed) {
        return originalApplicationName + suffixToAppend;
    }
    else {
        // Take the substring of application name that will be fit within the 'program_name' column in dm_exec_sessions.
        return originalApplicationName.substring(0, maxAppNameSubStringAllowed) + suffixToAppend;
    }
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: LoadbalanceHandler.java   View Source Code Vote up 6 votes
private void loadFilter(String filter, LoadBalancer lb) {
  String className = Configuration.getStringProperty(null,
      String.format(Configuration.SERVER_LIST_FILTER_CLASS_HOLDER, filter));
  if (!StringUtils.isEmpty(className)) {
    try {
      Class<?> filterClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
      if (ServerListFilterExt.class.isAssignableFrom(filterClass)) {
        ServerListFilterExt ext = (ServerListFilterExt) filterClass.newInstance();
        ext.setName(filter);
        ext.setLoadBalancer(lb);
        lb.putFilter(filter, ext);
      }
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
      LOGGER.warn("Unable to load filter class: " + className);
    }
  }
}
 
Example 3
Project: solo-spring   File: PropsUtil.java   View Source Code Vote up 6 votes
public static void addLibraryPath(String path) {
	String javaLibraryPath = System.getProperty("java.library.path");
	String[] paths = new String[0];
	if (StringUtils.isNotEmpty(javaLibraryPath)) {
		paths = javaLibraryPath.split(File.pathSeparator, -1);
	}
	StringBuilder sb = new StringBuilder();
	sb.append(path);
	sb.append(File.pathSeparator);
	for (String p : paths) {
		if (StringUtils.isEmpty(p))
			continue;
		if (p.equals(path))
			continue;
		sb.append(p);
		sb.append(File.pathSeparator);
	}
	if (sb.length() > 0)
		sb.deleteCharAt(sb.length() - 1);
	javaLibraryPath = sb.toString();
	System.setProperty("java.library.path", javaLibraryPath);
}
 
Example 4
Project: OperatieBRP   File: GeefDetailsPersoonVerzoekParser.java   View Source Code Vote up 6 votes
@Override
public void vulParameters(final GeefDetailsPersoonVerzoek verzoek, final Node node, final XPath xPath) {
    super.vulParameters(verzoek, node, xPath);
    // Historiefilter
    final String historieVorm = getNodeTextContent(getPrefix() + "/brp:parameters/brp:historievorm", xPath, node);
    if (!StringUtils.isEmpty(historieVorm)) {
        verzoek.getParameters().setHistorieVorm(HistorieVorm.getByNaam(historieVorm));
    }
    //peilmoment formeel
    final String peilMomentFormeelResultaat = getNodeTextContent(getPrefix() + "/brp:parameters/brp:peilmomentFormeelResultaat", xPath, node);
    if (!StringUtils.isEmpty(peilMomentFormeelResultaat)) {
        verzoek.getParameters()
                .setPeilMomentFormeelResultaat(peilMomentFormeelResultaat);
    }
    //peilmoment materieel resultaat
    final String peilMomentMaterieelResultaat = getNodeTextContent(getPrefix() + "/brp:parameters/brp:peilmomentMaterieelResultaat", xPath, node);
    if (!StringUtils.isEmpty(peilMomentMaterieelResultaat)) {
        verzoek.getParameters()
                .setPeilMomentMaterieelResultaat(peilMomentMaterieelResultaat);
    }
    //verantwoording
    final String verantwoording = getNodeTextContent(getPrefix() + "/brp:parameters/brp:verantwoording", xPath, node);
    if (!StringUtils.isEmpty(verantwoording)) {
        verzoek.getParameters().setVerantwoording(verantwoording);
    }
}
 
Example 5
Project: spring_mybatis_shiro   File: IpUtil.java   View Source Code Vote up 6 votes
public static String getIpAddr(HttpServletRequest request) {
	if (request != null) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	return null;
}
 
Example 6
Project: SECP   File: ChatSocketCreator.java   View Source Code Vote up 6 votes
@Override
@UnitOfWork
public Object createWebSocket(
    ServletUpgradeRequest servletUpgradeRequest,
    ServletUpgradeResponse servletUpgradeResponse) {

    String path = servletUpgradeRequest.getRequestPath();

    if(!StringUtils.isEmpty(path)) {
        String[] paths = servletUpgradeRequest.getRequestPath().split("/");

        String userID = paths[paths.length - 1];
        try {
            long id = Long.parseLong(userID);
            Optional<User> optionalUser = userRepository.getUserWithGroups(id);
            if (optionalUser.isPresent())
                return new ChatSocketListener(optionalUser.get(), this.messageHandler);
            log.error("Invalid user id was passed in");
        } catch (NumberFormatException exception) {
            log.error("Value passed in for user id is not a number", exception);
        }
    }

    return null;
}
 
Example 7
Project: Biliomi   File: TextUtils.java   View Source Code Vote up 6 votes
/**
 * Chunkify strings to a set length, but do not break words
 *
 * @param string The string to chunkify
 * @param length The max length of the chunks
 * @return A list containing the resulting chunks
 */
public static List<String> chunkify(String string, int length) {
  List<String> chunks = new ArrayList<>();

  if (StringUtils.isEmpty(string) || string.length() <= length) {
    chunks.add(string);
    return chunks;
  }

  Iterator<String> words = Iterators.forArray(string.split(" "));
  int chunkCount = (int) Math.ceil(((double) string.length()) / length);

  IntStream.rangeClosed(1, chunkCount).forEach(ci -> {
    StringBuilder newChunk = new StringBuilder();

    while (newChunk.length() < length) {
      if (!words.hasNext()) break;
      newChunk.append(" ").append(words.next());
    }

    if (StringUtils.isNotEmpty(newChunk)) chunks.add(newChunk.toString().trim());
  });

  return chunks;
}
 
Example 8
Project: clemon   File: RoleController.java   View Source Code Vote up 6 votes
@SystemControllerLog(description="权限管理-角色列表")
@RequestMapping(value = "/data")
@ResponseBody
public String data(String params) {
	try {
		ObjectMapper om = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(params)) {
			// 参数处理
			map = om.readValue(params, new TypeReference<Map<String, Object>>() {});
		}
		PagerModel<Role> pg = roleService.findPaginated(map);
		// 序列化查询结果为JSON
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pg.getTotal());
		result.put("rows", pg.getData());
		return om.writeValueAsString(result);
	} catch (Exception e) {
		e.printStackTrace();
		return "{ \"total\" : 0, \"rows\" : [] }";
	}
}
 
Example 9
Project: smarti   File: MltConfig.java   View Source Code Vote up 5 votes
public MltConfig addSimilarityFields(String lang, String field){
    if(StringUtils.isEmpty(field)){
        return this;
    }
    lang = StringUtils.lowerCase(lang, Locale.ROOT);
    Collection<String> langFields = langSimilarityFields.get(lang);
    if(langFields == null){
        langFields = new LinkedHashSet<>();
        langSimilarityFields.put(lang, langFields);
    }
    langFields.add(field);
    return this;
}
 
Example 10
Project: Yidu   File: UserListAction.java   View Source Code Vote up 5 votes
@Override
protected void loadData() {
    // 初始化类别下拉列表选项
    initCollections(new String[] { "collectionProperties.user.sex", "collectionProperties.user.type" });
    UserSearchBean searchBean = new UserSearchBean();
    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn("userno");
    }
    searchBean.setPagination(pagination);
    // 总件数设置
    pagination.setPreperties(userService.getCount(searchBean));
    userList = userService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(userList.size());
}
 
Example 11
Project: raven   File: PushMessageService.java   View Source Code Vote up 5 votes
@Deprecated
public boolean validateMessage(PushMessage pushMessage)
{
	//校验必选参数
	if (null == pushMessage || StringUtils.isEmpty(pushMessage.getText()) 
			|| StringUtils.isEmpty(pushMessage.getClientType().name())
			|| null == pushMessage.getPushChannel())
	{
		LOGGER.error("Invalid request params.");
		return false;
	}
	
	// 安卓推送, ticker和title不能为空
	if ("ANDROID".equals(pushMessage.getClientType().name()) 
			&& StringUtils.isEmpty(pushMessage.getTicker()) && StringUtils.isEmpty(pushMessage.getTitle()))
	{
		LOGGER.error("Invalid request params. ticker or title is empty");
		return false;
	}
	
	// 如果是单播, topicList参数必须不能为空
	if (PushMessage.PushType.UNICAST == pushMessage.getPushType()
			&& CollectionUtils.isEmpty(pushMessage.getAudiences()))
	{
		LOGGER.error("Invalid request params. topicList is empty.");
		return false;
	}
	return true;
}
 
Example 12
Project: JuniperBotJ   File: CommonUtils.java   View Source Code Vote up 5 votes
public static String parseVkLinks(String string, boolean noLink) {
    if (StringUtils.isEmpty(string)) return string;
    Matcher m = VK_LINK_TAG.matcher(string);
    StringBuffer sb = new StringBuffer(string.length());
    while (m.find()) {
        m.appendReplacement(sb, noLink ? m.group(2)
                : String.format("[%s](https://vk.com/%s)", m.group(2), m.group(1)));
    }
    m.appendTail(sb);

    string = sb.toString();

    if (!noLink) {
        try {
            m = VK_HASH_TAG.matcher(string);
            sb = new StringBuffer(string.length());
            while (m.find()) {
                m.appendReplacement(sb, noLink ? m.group(2)
                        : String.format("[%s](https://vk.com/feed?section=search&q=%s)", m.group(1), UriUtils.encode(m.group(1), "UTF-8")));
            }
            m.appendTail(sb);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        string = sb.toString();
    }
    return maskDiscordFormat(string);
}
 
Example 13
Project: SECP   File: AdminController.java   View Source Code Vote up 5 votes
public Response updateRoles(RolesOrPermissionDTO request, String id) {
    if(StringUtils.isEmpty(request.getColor()))
    {
        throw new WebApplicationException(AdminErrorMessage.REGISTER_ROLES_FAIL_INVALID_COLOR, Response.Status.BAD_REQUEST);
    }

    Role role = getRoleFromID(id);
    role.setColor(request.getColor());
    Role savedRole = rolesDAO.save(role);


    return Response.status(Response.Status.CREATED).
        entity(new RolesOrPermissionDTO(savedRole.getId(),savedRole.getRole(),savedRole.getColor())).build();
}
 
Example 14
Project: weixin_api   File: OpenApi.java   View Source Code Vote up 5 votes
/**
 * 消息处理
 * 
 * @param request
 *            HTTP请求对象
 * @return 解析后的消息对象,如果不能解析则返回null。
 */
public UserMsg onMessage(HttpServletRequest request) {
	String openid = request.getParameter("openid");
	String appid = request.getParameter("appid");

	final UserMsg msg = parseMessage(request);
	if (msg == null) {
		log.warn(String.format("未能解析消息请求"));
		return null;
	}

	// 消息ID去重
	String msgid = msg.getMsgId();
	if (StringUtils.isEmpty(msgid)) {
		msgid = String.format("%s_%s", msg.getFromUserName(), msg.getCreateTime());
	}
	if (distinctMsgIdCache.containsKey(msgid)) {
		if (log.isInfoEnabled()) {
			log.info(String.format("丢弃重复消息[%s],", msgid));
		}
		return null;
	}
	distinctMsgIdCache.put(msgid, null);

	if (log.isInfoEnabled()) {
		log.info(String.format("消息 %s", new Gson().toJson(msg)));
	}

	msg.setAppid(appid);
	msg.setOpenid(openid);
	return msg;
}
 
Example 15
Project: OutsourcedProject   File: MD5Util.java   View Source Code Vote up 5 votes
/**
 * @param fields {@link String []}
 * @return md5
 * @description MD5 33位加密
 */
public static String getMD5Encode(String... fields) {
    if (ArrayUtils.isEmpty(fields)) {
        return null;
    }
    StringBuilder builder = new StringBuilder(60);
    for (String field : fields) {
        if (!StringUtils.isEmpty(field)) {
            builder.append(field);
        }
    }
    return DigestUtils.md5Hex(builder.toString());
}
 
Example 16
Project: AndroidBackendlessChat   File: ChatSDKShareWithContactsActivity.java   View Source Code Vote up 5 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_sdk_fragment_activity);

    String action = getIntent().getAction();
    String type = getIntent().getType();

    if (StringUtils.isEmpty(action) && StringUtils.isEmpty(type))
    {
        showAlertToast(getString(R.string.share_activity_error_getting_share_data));
        return;
    }

    if (!action.equals(Intent.ACTION_SEND))
    {
        showAlertToast(getString(R.string.share_activity_error_getting_share_data));
        return;
    }

    if (getIntent().getExtras() != null)
    {
        Object extraData = null;

        if (type.equals("text/plain"))
        {
            extraData = getIntent().getStringExtra(Intent.EXTRA_TEXT);
        }
        else if (type.startsWith("image/"))
        {
            extraData = getIntent().getExtras().get(Intent.EXTRA_STREAM);
        }

        ChatSDKContactsFragment fragment = ChatSDKContactsFragment.newInstance(ChatSDKContactsFragment.MODE_LOAD_CONTACTS, ChatSDKContactsFragment.CLICK_MODE_SHARE_CONTENT, extraData);
        getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
    }
    else showAlertToast(getString(R.string.share_activity_error_getting_share_data));
}
 
Example 17
Project: xm-uaa   File: AccountResource.java   View Source Code Vote up 4 votes
private boolean checkPasswordLength(String password) {
    return !StringUtils.isEmpty(password)
        && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH
        && password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH;
}
 
Example 18
Project: sdudoc   File: LogInterceptor.java   View Source Code Vote up 4 votes
@Override
public String intercept(ActionInvocation invocation) throws Exception {
	log.info("LogIntercepetor intercept");
	String result = invocation.invoke();

	String methodName = invocation.getProxy().getMethod();
	if (StringUtils.isEmpty(methodName)) {
		return result;
	}
	// 排除set和get方法
	if (methodName.startsWith("set") || methodName.startsWith("get")) {
		return result;
	}

	Class<?> targetClass = invocation.getAction().getClass();
	Method method = targetClass.getMethod(methodName);
	if (method == null || !method.isAnnotationPresent(MethodDesc.class))
		return result;
	Map<String, Object> session = ActionContext.getContext().getSession();
	User user = (User) session.get(Constants.USER);
	if (user == null)
		return result;

	MethodDesc methodDesc = method.getAnnotation(MethodDesc.class);
	String desc = methodDesc.description();
	int opType = methodDesc.opType();
	if(opType == Constants.OP_CLICK) {
		Click click = new Click();
		Book book = (Book) session.get("book");
		if(book != null) {
			click.setUser(user);
			click.setBook(book);
			clickService.addClick(click);
			session.remove("book");
		}
	}

	/*Field[] fields = targetClass.getSuperclass().getDeclaredFields();
	for(Field field : fields) {
		System.out.println(field.getName());
	}*/
	Field field = targetClass.getSuperclass().getDeclaredField("logMessage");
	field.setAccessible(true);
	String logMessage = (String) field.get(invocation.getAction());
	System.out.println("logMessage:" + logMessage);

	/*Field field = targetClass.getDeclaredField("logMessage");
	field.setAccessible(true);
	String logMessage = (String) field.get(invocation.getAction());
	System.out.println("logMessage:" + logMessage);*/
	try {
		SysLog sysLog = new SysLog();
		/*sysLog.setUserId(user.getId());
		sysLog.setUserName(user.getUsername());*/
		sysLog.setUser(user);
		if (logMessage != null && !logMessage.equals(""))
			sysLog.setMethod(desc + ": " + logMessage);
		else
			sysLog.setMethod(desc);
		sysLog.setTime(new Date());
		logService.addLog(sysLog);
	} catch (Exception e) {
		log.error(e.getMessage());
	}
	return result;
}
 
Example 19
Project: spring-boot-seed   File: HttpClientUtilImpl.java   View Source Code Vote up 3 votes
/**
 * Http post 请求.
 *
 * @param <R>            返回数据泛型
 * @param <T>            请求的body数据类型数据
 * @param url            请求路径 url
 * @param params         请求的body
 * @param typeReference  返回的数据类型
 * @param noNeedResponse 是否需要数据返回
 * @return the r
 */
@Override
public <R, T> R httpPostReturnTypeRef(String url, T params, TypeReference typeReference, boolean noNeedResponse) {
    String resultData = httpReturnString(url,params, noNeedResponse,"post");
    if (StringUtils.isEmpty(resultData)) {
        return null;
    }
    return JsonUtil.fromJsonType(resultData, typeReference);
}
 
Example 20
Project: management-sdk-for-kafka   File: TopicService.java   View Source Code Vote up 2 votes
/**
 * Validate Topic Name.
 *
 * @param topicName Topic Name to be validated
 * @throws IllegalArgumentException when topicName is empty or null
 */
private void validateTopicName(final String topicName) {
    if (StringUtils.isEmpty(topicName)) {
        throw new IllegalArgumentException("Topic name cannot be null or empty");
    }
}