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

The following are Jave code examples for showing how to use isNotBlank() 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: springboot-shiro-cas-mybatis   File: BaseSpnegoKnownClientSystemsFilterAction.java   View Source Code Vote up 6 votes
/**
 * Pulls the remote IP from the current HttpServletRequest, or grabs the value
 * for the specified alternative attribute (say, for proxied requests).  Falls
 * back to providing the "normal" remote address if no value can be retrieved
 * from the specified alternative header value.
 * @param context the context
 * @return the remote ip
 */
private String getRemoteIp(@NotNull final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    String userAddress = request.getRemoteAddr();
    logger.debug("Remote Address = {}", userAddress);

    if (StringUtils.isNotBlank(this.alternativeRemoteHostAttribute)) {

        userAddress = request.getHeader(this.alternativeRemoteHostAttribute);
        logger.debug("Header Attribute [{}] = [{}]", this.alternativeRemoteHostAttribute, userAddress);

        if (StringUtils.isBlank(userAddress)) {
            userAddress = request.getRemoteAddr();
            logger.warn("No value could be retrieved from the header [{}]. Falling back to [{}].",
                    this.alternativeRemoteHostAttribute, userAddress);
        }
    }
    return userAddress;
}
 
Example 2
Project: xxpay-master   File: MchNotifyController.java   View Source Code Vote up 6 votes
@RequestMapping("/view.html")
public String viewInput(String orderId, ModelMap model) {
    MchNotify item = null;
    if(StringUtils.isNotBlank(orderId)) {
        item = mchNotifyService.selectMchNotify(orderId);
    }
    if(item == null) {
        item = new MchNotify();
        model.put("item", item);
        return "mch_notify/view";
    }
    JSONObject object = (JSONObject) JSON.toJSON(item);
    if(item.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(item.getCreateTime()));
    if(item.getUpdateTime() != null) object.put("updateTime", DateUtil.date2Str(item.getUpdateTime()));
    if(item.getLastNotifyTime() != null) object.put("lastNotifyTime", DateUtil.date2Str(item.getLastNotifyTime()));
    model.put("item", object);
    return "mch_notify/view";
}
 
Example 3
Project: JAVA-   File: Realm.java   View Source Code Vote up 6 votes
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 4
Project: KettleUtil   File: JobEntryEasyExpand.java   View Source Code Vote up 6 votes
/**
 * Execute this job entry and return the result. In this case it means, just
 * set the result boolean in the Result class.
 * 
 * @param prev_result
 *            The result of the previous execution
 * @return The Result of the execution.
 */
public Result execute(Result prev_result, int nr) {
    boolean result = true;
    if(StringUtils.isNotBlank(className)){
        try {
            //实例化配置的类
            JobEntryEasyExpandRunBase kui = (JobEntryEasyExpandRunBase) Class.forName(
                    environmentSubstitute(className)).newInstance();
            kui.setJeku(this);
            result = kui.run();
        } catch (Exception e) {
            prev_result.setNrErrors(1);
            result = false;
            logError("运行失败,"+className+","+environmentSubstitute(configInfo), e);
        }
    }
    prev_result.setResult(result);
    return prev_result;
}
 
Example 5
Project: cyberduck   File: TerminalLoginService.java   View Source Code Vote up 6 votes
@Override
public void validate(final Host bookmark, final String message, final LoginOptions options) throws LoginCanceledException {
    final Credentials credentials = bookmark.getCredentials();
    if(input.hasOption(TerminalOptionsBuilder.Params.username.name())) {
        credentials.setUsername(input.getOptionValue(TerminalOptionsBuilder.Params.username.name()));
    }
    if(input.hasOption(TerminalOptionsBuilder.Params.password.name())) {
        credentials.setPassword(input.getOptionValue(TerminalOptionsBuilder.Params.password.name()));
    }
    if(input.hasOption(TerminalOptionsBuilder.Params.identity.name())) {
        credentials.setIdentity(LocalFactory.get(input.getOptionValue(TerminalOptionsBuilder.Params.identity.name())));
    }
    if(StringUtils.isNotBlank(credentials.getUsername()) && StringUtils.isNotBlank(credentials.getPassword())) {
        return;
    }
    super.validate(bookmark, message, options);
}
 
Example 6
Project: spring-cloud-samples   File: WebUtils.java   View Source Code Vote up 6 votes
/**
 * @param req
 * @return
 */
public static String getRemoteAddr(HttpServletRequest req) {
    String ip = req.getHeader("X-Forwarded-For");
    if (StringUtils.isNotBlank(ip)) {
        String[] ips = StringUtils.split(ip, ',');
        if (ips != null) {
            for (String tmpip : ips) {
                if (StringUtils.isBlank(tmpip))
                    continue;
                tmpip = tmpip.trim();
                if (isIPAddr(tmpip) && !tmpip.startsWith("10.") && !tmpip.startsWith("192.168.")
                        && !"127.0.0.1".equals(tmpip)) {
                    return tmpip.trim();
                }
            }
        }
    }
    ip = req.getHeader("x-real-ip");
    if (isIPAddr(ip))
        return ip;
    ip = req.getRemoteAddr();
    if (ip.indexOf('.') == -1)
        ip = "127.0.0.1";
    return ip;
}
 
Example 7
Project: java-restclient   File: CacheControl.java   View Source Code Vote up 6 votes
public CacheControl build() {
	CacheControl cacheControl = new CacheControl(0, 0, 0, 0);
	
	if (StringUtils.isNotBlank(ageHeaderValue) && StringUtils.isNumeric(ageHeaderValue)) {
		cacheControl.setAge(Integer.parseInt(ageHeaderValue));
	}
	
	if (StringUtils.isNotBlank(cacheControlHeaderValue)) {
		cacheControl.setMaxAge(extract(maxAge));
		cacheControl.setWhileRevalidate(extract(whileRevalidate));
		cacheControl.setIfError(extract(ifError));
	}
	
	cacheControl.setExpiration();
	
	return cacheControl;
}
 
Example 8
Project: dragoman   File: GroovySelectClauseListener.java   View Source Code Vote up 6 votes
@Override
public String get() {
  StringBuilder sb = new StringBuilder();
  List<Projection> projections = getProjections();
  if (!projections.isEmpty()) {
    // create the object we are going to populate
    sb.append(tab(1)).append("Map<String, Object> response = new HashMap<>();").append(NEWLINE);

    // add any standard expressions
    sb.append(getExpressions(projections));

    sb.append(tab(2)).append("return response;").append(NEWLINE);
  }

  String s = sb.toString();

  if (StringUtils.isNotBlank(s)) {
    return TEMPLATE_SCRIPT.replace(SELECT_STAR, s);
  } else {
    return TEMPLATE_SCRIPT;
  }
}
 
Example 9
Project: bluegreen-manager   File: RdsAnalyzer.java   View Source Code Vote up 5 votes
/**
 * Finds the parameter-apply-status of the named parameter group inside the dbInstance.
 */
public RdsParameterApplyStatus findParameterApplyStatus(DBInstance dbInstance, String paramGroupName)
{
  if (dbInstance != null && dbInstance.getDBParameterGroups() != null && StringUtils.isNotBlank(paramGroupName))
  {
    for (DBParameterGroupStatus paramGroupStatus : dbInstance.getDBParameterGroups())
    {
      if (StringUtils.equals(paramGroupName, paramGroupStatus.getDBParameterGroupName()))
      {
        return RdsParameterApplyStatus.fromString(paramGroupStatus.getParameterApplyStatus());
      }
    }
  }
  return null;
}
 
Example 10
Project: mybatis-dynamic-query   File: EntityHelper.java   View Source Code Vote up 5 votes
static String getColumnNameByProperty(final String propertyName, final Field[] properties) {
    Field matchProperty = getPropertyField(propertyName, properties);
    Column column = getColumnByProperty(propertyName, properties);
    if (column != null && StringUtils.isNotBlank(column.name())) {
        return column.name();
    }


    String usePropertyName = matchProperty.getName();
    return camelCaseToUnderscore(usePropertyName);
}
 
Example 11
Project: plugin-id-ldap   File: LdapPluginResource.java   View Source Code Vote up 5 votes
@Override
public void create(final int subscription) throws Exception {
	final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
	final String group = parameters.get(IdentityResource.PARAMETER_GROUP);
	final String parentGroup = parameters.get(IdentityResource.PARAMETER_PARENT_GROUP);
	final String ou = parameters.get(IdentityResource.PARAMETER_OU);
	final Project project = subscriptionRepository.findOne(subscription).getProject();
	final String pkey = project.getPkey();

	// Check the relationship between group, OU and project
	validateGroup(group, ou, pkey);

	// Check the relationship between group, and parent
	final String parentDn = validateAndCreateParent(group, parentGroup, ou, pkey);

	// Create the group inside the parent (OU or parent CN)
	final String groupDn = "cn=" + group + "," + parentDn;
	log.info("New Group CN would be created {} project {} and subscription {}", group, pkey);
	final GroupLdapRepository repository = getGroup();
	final GroupOrg groupLdap = repository.create(groupDn, group);

	// Complete as needed the relationship between parent and this new group
	if (StringUtils.isNotBlank(parentGroup)) {
		// This group will be added as "uniqueMember" of its parent
		repository.addGroup(groupLdap, parentGroup);
	}

	// Associate the project to this group in the cache
	final CacheProjectGroup projectGroup = new CacheProjectGroup();
	projectGroup.setProject(project);
	projectGroup.setGroup(repository.getCacheRepository().findOneExpected(groupLdap.getId()));
	cacheProjectGroupRepository.saveAndFlush(projectGroup);
}
 
Example 12
Project: Wechat-Group   File: TransferCustomerServiceBuilder.java   View Source Code Vote up 5 votes
@Override
public WxMpXmlOutTransferKefuMessage build() {
  WxMpXmlOutTransferKefuMessage m = new WxMpXmlOutTransferKefuMessage();
  setCommon(m);
  if(StringUtils.isNotBlank(this.kfAccount)){
    WxMpXmlOutTransferKefuMessage.TransInfo transInfo = new WxMpXmlOutTransferKefuMessage.TransInfo();
    transInfo.setKfAccount(this.kfAccount);
    m.setTransInfo(transInfo);
  }
  return m;
}
 
Example 13
Project: chat-sdk-android-push-firebase   File: SaveDetailTextWatcher.java   View Source Code Vote up 5 votes
@Override
public void run() {
    if (StringUtils.isBlank(editable.toString()))
        return;

    BUser user = BNetworkManager.sharedManager().getNetworkAdapter().currentUserModel();
    String metadata = user.metaStringForKey(metaKey);

    if (StringUtils.isNotBlank(metadata) && metadata.equals(editable.toString()))
        return;

    user.setMetadataString(metaKey, editable.toString());
    BNetworkManager.sharedManager().getNetworkAdapter().pushUser();
}
 
Example 14
Project: mumu   File: ThirdPartyLoginController.java   View Source Code Vote up 5 votes
@RequestMapping("/callback/qq")
public String qqCallback(HttpServletRequest request, ModelMap modelMap) {
	String host = request.getHeader("host");
	try {
		String code = request.getParameter("code");
		if (StringUtils.isNotBlank(code)) {// 如果不为空
			// 获取token和openid
			Map<String, String> map = ThirdPartyLoginHelper.getQQTokenAndOpenid(code, host);
			String openId = map.get("openId");
			if (StringUtils.isNotBlank(openId)) {// 如果openID存在
				// 获取第三方用户信息存放到session中
				ThirdPartyUser thirdUser = ThirdPartyLoginHelper.getQQUserinfo(map.get("access_token"), openId);
				thirdUser.setProvider("QQ");
				thirdPartyLogin(request, thirdUser);
				// 跳转到登录成功界面
				modelMap.put("retUrl", Resources.THIRDPARTY.getString("third_login_success"));
			} else {// 如果未获取到OpenID
				modelMap.put("retUrl", "-1");
			}
		} else {// 如果没有返回令牌,则直接返回到登录页面
			modelMap.put("retUrl", "-1");
		}
	} catch (Exception e) {
		modelMap.put("retUrl", "-1");
		e.printStackTrace();
	}

	return "/sns/redirect";
}
 
Example 15
Project: java-restclient   File: Request.java   View Source Code Vote up 5 votes
private void fillParameters(String raw) {
    for (String pair : raw.split("&")) {
        String[] p = pair.split("=");
        if (StringUtils.isNotBlank(p[0]))
            parameters.put(p[0], p.length == 2 ? p[1] : "");
    }
}
 
Example 16
Project: fastdfs-quickstart   File: Constants.java   View Source Code Vote up 5 votes
public static final Long getProtocolMaxSize() {
  if (protocolMaxSize == null) {
    String protocolMaxsizeValue = configure.get("filecloud.protocol-maxsize");
    if (StringUtils.isNotBlank(protocolMaxsizeValue) && NumberUtils.isNumber(protocolMaxsizeValue.trim())) {
      protocolMaxSize = NumberUtils.toLong(protocolMaxsizeValue.trim());
    } else {
      protocolMaxSize = DEFAULT_PROTOCOL_MAXSIZE;
    }
  }
  return protocolMaxSize;
}
 
Example 17
Project: cas-5.1.0   File: QueryAndEncodeDatabaseAuthenticationHandler.java   View Source Code Vote up 5 votes
/**
 * Digest encoded password.
 *
 * @param encodedPassword the encoded password
 * @param values          the values retrieved from database
 * @return the digested password
 */
protected String digestEncodedPassword(final String encodedPassword, final Map<String, Object> values) {
    final ConfigurableHashService hashService = new DefaultHashService();

    if (StringUtils.isNotBlank(this.staticSalt)) {
        hashService.setPrivateSalt(ByteSource.Util.bytes(this.staticSalt));
    }
    hashService.setHashAlgorithmName(this.algorithmName);

    Long numOfIterations = this.numberOfIterations;
    if (values.containsKey(this.numberOfIterationsFieldName)) {
        final String longAsStr = values.get(this.numberOfIterationsFieldName).toString();
        numOfIterations = Long.valueOf(longAsStr);
    }

    hashService.setHashIterations(numOfIterations.intValue());
    if (!values.containsKey(this.saltFieldName)) {
        throw new RuntimeException("Specified field name for salt does not exist in the results");
    }

    final String dynaSalt = values.get(this.saltFieldName).toString();
    final HashRequest request = new HashRequest.Builder()
            .setSalt(dynaSalt)
            .setSource(encodedPassword)
            .build();
    return hashService.computeHash(request).toHex();
}
 
Example 18
Project: iBase4J-Common   File: TokenFilter.java   View Source Code Vote up 4 votes
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest)servletRequest;
    boolean filter = DataUtil.isEmpty(PropertiesUtil.getString("token.filter.test"));
    String token = request.getHeader("UUID");
    logger.info("UUID==>" + token);
    if (StringUtils.isNotBlank(token)) {
        try {
            Token tokenInfo = TokenUtil.getTokenInfo(token);
            if (tokenInfo != null) {
                WebUtil.saveCurrentUser(request, tokenInfo.getValue());
                if (DataUtil.isNotEmpty(expire)) {
                    if (System.currentTimeMillis() - tokenInfo.getTime() > Long.valueOf(expire) * 1000) {
                        WebUtil.saveCurrentUser(request, null);
                    }
                }
            } else if (filter) {
                WebUtil.saveCurrentUser(request, null);
            }
        } catch (Exception e) {
            logger.error("token检查发生异常:", e);
        }
    } else if (filter) {
        WebUtil.saveCurrentUser(request, null);
    }
    String url = request.getRequestURI();
    if (isWhiteReq(url.toLowerCase())) {
        chain.doFilter(request, response);
    } else if (DataUtil.isEmpty(WebUtil.getCurrentUser(request)) && filter) {
        response.setContentType("text/html; charset=UTF-8");
        Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
        modelMap.put("code", HttpCode.UNAUTHORIZED.value().toString());
        modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
        modelMap.put("timestamp", System.currentTimeMillis());
        String result = JSON.toJSONString(modelMap);
        logger.warn(url + " ====> " + result);
        PrintWriter out = response.getWriter();
        out.println(result);
        out.flush();
        out.close();
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 19
Project: cyberduck   File: LaunchServicesApplicationFinder.java   View Source Code Vote up 4 votes
/**
 * Determine the human readable application name for a given bundle identifier.
 *
 * @param search Bundle identifier
 * @return Application human readable name
 */
@Override
public Application getDescription(final String search) {
    if(applicationNameCache.containsKey(search)) {
        return applicationNameCache.get(search);
    }
    if(log.isDebugEnabled()) {
        log.debug(String.format("Find application for %s", search));
    }
    final String identifier;
    final String name;
    synchronized(NSWorkspace.class) {
        final NSWorkspace workspace = NSWorkspace.sharedWorkspace();
        final String path;
        if(null != workspace.absolutePathForAppBundleWithIdentifier(search)) {
            path = workspace.absolutePathForAppBundleWithIdentifier(search);
        }
        else {
            log.warn(String.format("Cannot determine installation path for bundle identifier %s. Try with name.", search));
            path = workspace.fullPathForApplication(search);
        }
        if(StringUtils.isNotBlank(path)) {
            final NSBundle app = NSBundle.bundleWithPath(path);
            if(null == app) {
                log.error(String.format("Loading bundle %s failed", path));
                identifier = search;
                name = FilenameUtils.removeExtension(LocalFactory.get(path).getDisplayName());
            }
            else {
                NSDictionary dict = app.infoDictionary();
                if(null == dict) {
                    log.error(String.format("Loading application dictionary for bundle %s failed", path));
                    applicationNameCache.put(search, Application.notfound);
                    return null;
                }
                else {
                    final NSObject bundlename = dict.objectForKey("CFBundleName");
                    if(null == bundlename) {
                        log.warn(String.format("No CFBundleName in bundle %s", path));
                        name = FilenameUtils.removeExtension(LocalFactory.get(path).getDisplayName());
                    }
                    else {
                        name = bundlename.toString();
                    }
                    final NSObject bundleIdentifier = dict.objectForKey("CFBundleIdentifier");
                    if(null == bundleIdentifier) {
                        log.warn(String.format("No CFBundleName in bundle %s", path));
                        identifier = search;
                    }
                    else {
                        identifier = bundleIdentifier.toString();
                    }

                }
            }
        }
        else {
            log.warn(String.format("Cannot determine installation path for %s", search));
            applicationNameCache.put(search, Application.notfound);
            return Application.notfound;
        }
    }
    final Application application = new Application(identifier, name);
    applicationNameCache.put(search, application);
    return application;
}
 
Example 20
Project: azeroth   File: TopicProducerSpringProvider.java   View Source Code Vote up 4 votes
@Override
public void afterPropertiesSet() throws Exception {

    Validate.notEmpty(this.configs, "configs is required");

    routeEnv = StringUtils.trimToNull(ResourceUtils.get(KafkaConst.PROP_ENV_ROUTE));

    if (routeEnv != null)
        log.info("current route Env value is:", routeEnv);
    //移除错误的或者未定义变量的配置
    Set<String> propertyNames = configs.stringPropertyNames();
    for (String propertyName : propertyNames) {
        String value = configs.getProperty(propertyName);
        if (StringUtils.isBlank(value) || value.trim().startsWith("$")) {
            configs.remove(propertyName);
            log.warn("remove prop[{}],value is:{}", propertyName, value);
        }
    }

    if (!configs.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
            StringSerializer.class.getName()); // key serializer
    }

    if (!configs.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
            KyroMessageSerializer.class.getName());
    }

    if (!configs.containsKey(ProducerConfig.PARTITIONER_CLASS_CONFIG)) {
        configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,
            DefaultPartitioner.class.getName());
    }

    //默认重试一次
    if (!configs.containsKey(ProducerConfig.RETRIES_CONFIG)) {
        configs.put(ProducerConfig.RETRIES_CONFIG, "1");
    }

    if (!configs.containsKey(ProducerConfig.COMPRESSION_TYPE_CONFIG)) {
        configs.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
    }

    if (!configs.containsKey("client.id")) {
        configs.put("client.id",
            (producerGroup == null ? "" : "_" + producerGroup) + NodeNameHolder.getNodeId());
    }

    KafkaProducer<String, Object> kafkaProducer = new KafkaProducer<String, Object>(configs);

    this.producer = new DefaultTopicProducer(kafkaProducer, defaultAsynSend);

    //hanlder
    if (StringUtils.isNotBlank(monitorZkServers)) {
        Validate.notBlank(producerGroup,
            "enable producer monitor property[producerGroup] is required");
        this.producer.addEventHandler(new SendCounterHandler(producerGroup, monitorZkServers));
    }
    if (delayRetries > 0) {
        this.producer.addEventHandler(
            new SendErrorDelayRetryHandler(producerGroup, kafkaProducer, delayRetries));
    }
}