Java 类org.springframework.util.StringUtils 实例源码

项目:SkillWill    文件:OAuthMock.java   
@RequestMapping(path = "/oauthmock", method = RequestMethod.GET)
public ResponseEntity<String> getOAuthMock(@CookieValue("_oauth2_proxy") String oAuthToken) {
  if (StringUtils.isEmpty(mockOAuth) || !mockOAuth.equals("true")) {
    return new ResponseEntity<>(new StatusJSON("mocking disabled").getJSON().toString(), HttpStatus.LOCKED);
  }

  if (userRepository.findByMail(sessionService.extractMail(oAuthToken)) != null) {
    return new ResponseEntity<>(new StatusJSON("ok").getJSON().toString(), HttpStatus.ACCEPTED);
  }

  return new ResponseEntity<>(new StatusJSON("forbidden").getJSON().toString(), HttpStatus.FORBIDDEN);
}
项目:spring-cloud-skipper    文件:AboutController.java   
private String getChecksum(String defaultValue, String url,
        String version) {
    String result = defaultValue;
    if (result == null && StringUtils.hasText(url)) {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        url = constructUrl(url, version);
        try {
            ResponseEntity<String> response
                    = new RestTemplate(requestFactory).exchange(
                    url, HttpMethod.GET, null, String.class);
            if (response.getStatusCode().equals(HttpStatus.OK)) {
                result = response.getBody();
            }
        }
        catch (HttpClientErrorException httpException) {
            // no action necessary set result to undefined
            logger.debug("Didn't retrieve checksum because", httpException);
        }
    }
    return result;
}
项目:openmrs-contrib-addonindex    文件:Bintray.java   
@Override
public AddOnInfoAndVersions getInfoAndVersionsFor(AddOnToIndex addOnToIndex) throws Exception {
    if (StringUtils.isEmpty(bintrayUsername) || StringUtils.isEmpty(bintrayApiKey)) {
        logger.error("You need to specify the bintray.username and bintray.api_key configuration settings");
    }
    String url = packageUrlFor(addOnToIndex);
    ResponseEntity<String> entity = restTemplateBuilder.basicAuthorization(bintrayUsername, bintrayApiKey).build()
            .getForEntity(url, String.class);
    if (!entity.getStatusCode().is2xxSuccessful()) {
        logger.warn("Problem fetching " + url + " -> " + entity.getStatusCode() + " " + entity.getBody());
        return null;
    } else {
        String json = entity.getBody();
        return handlePackageJson(addOnToIndex, json);
    }
}
项目:gemini.blueprint    文件:StandardAttributeCallback.java   
public boolean process(Element parent, Attr attribute, BeanDefinitionBuilder builder) {
    String name = attribute.getLocalName();

    if (BeanDefinitionParserDelegate.ID_ATTRIBUTE.equals(name)) {
        return false;
    }

    if (BeanDefinitionParserDelegate.DEPENDS_ON_ATTRIBUTE.equals(name)) {
        builder.getBeanDefinition().setDependsOn(
            (StringUtils.tokenizeToStringArray(attribute.getValue(),
                BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS)));
        return false;
    }
    if (BeanDefinitionParserDelegate.LAZY_INIT_ATTRIBUTE.equals(name)) {
        builder.setLazyInit(Boolean.valueOf(attribute.getValue()));
        return false;
    }
    return true;
}
项目:mirrorgate    文件:ServerSentEventsHandler.java   
public synchronized void removeFromSessionsMap(SseEmitter session, String dashboardId){

        LOGGER.debug("Remove SseEmitter {} to sessions map", dashboardId);

        if(!StringUtils.isEmpty(dashboardId)){
            List<SseEmitter> dashboardEmitters = emittersPerDashboard.get(dashboardId);

            if(dashboardEmitters != null){
                dashboardEmitters.remove(session);

                if(dashboardEmitters.isEmpty()){
                    emittersPerDashboard.remove(dashboardId);
                }
            }
        }
    }
项目:spring-backend-boilerplate    文件:UserAccountServiceImpl.java   
@Override
public User changePassword(String userId, String newPassword) {
    User user = userRepository.findById(userId);
    if (user == null) {
        throw new UserNotFoundException(userId);
    }

    if (StringUtils.isEmpty(newPassword)) {
        throw new UserPasswordException("新设置的密码不能为空");
    }

    if (newPassword.length() < 8) {
        throw new UserPasswordException("新设置的密码长度不能少于8位");
    }

    String passwordHash = passwordEncoder.encode(newPassword);
    user.setPassword(passwordHash);
    return userRepository.save(user);
}
项目:springDemos    文件:ExceptionHandlerAspect.java   
@Around("@annotation(demoExceptionHandler)")
public Object arroundHandler(final ProceedingJoinPoint joinPoint, final DemoExceptionHandler demoExceptionHandler)
        throws Throwable {

    Object rval = null;

    try {
        rval = joinPoint.proceed();
    } catch (final RuntimeException re) {
        // log error.
        if (!StringUtils.isEmpty(demoExceptionHandler.fallbackMethod())) {
            rval = executeFallbackMethod(joinPoint, demoExceptionHandler);
        } else {
            throw re;
        }
    }

    return rval;
}
项目:spring-backend-boilerplate    文件:UserAccountServiceImpl.java   
@Override
public User findAccountByUsername(String username) {
    if (StringUtils.isEmpty(username)) {
        return null;
    }
    username = username.trim().toLowerCase();
    User account = userRepository.findByUsername(username);
    if (account == null) {
        return null;
    }

    User result = new User();
    BeanUtils.copyProperties(account, result, "roles");
    //populate sys roles
    result.getAuthorities().addAll(account.getRoles());
    //populate app role
    result.getAuthorities()
          .addAll(userRoleRelationshipRepository.findListByUser(account)
                                                .stream()
                                                .map(relationship -> relationship.getRole())
                                                .collect(Collectors.toList()));
    return result;
}
项目:esup-ecandidat    文件:SiScolApogeeWSServiceImpl.java   
/**
 * @param candidat
 * @return l'etat civil
 */
@Override
public MAJEtatCivilDTO getEtatCivil(Candidat candidat) {
    MAJEtatCivilDTO etatCivil = new MAJEtatCivilDTO();
    // Etat Civil
    etatCivil.setLibNomPatIndOpi(MethodUtils.cleanForApogee(candidat.getNomPatCandidat()));
    etatCivil.setLibNomUsuIndOpi(MethodUtils.cleanForApogee(candidat.getNomUsuCandidat()));
    etatCivil.setLibPr1IndOpi(MethodUtils.cleanForApogee(candidat.getPrenomCandidat()));
    etatCivil.setLibPr2IndOpi(MethodUtils.cleanForApogee(candidat.getAutrePrenCandidat()));
    // separer le clé du code nne
    if (StringUtils.hasText(candidat.getIneCandidat()) && StringUtils.hasText(candidat.getCleIneCandidat())) {
        etatCivil.setCodNneIndOpi(MethodUtils.cleanForApogee(candidat.getIneCandidat()));
        etatCivil.setCodCleNneIndOpi(MethodUtils.cleanForApogee(candidat.getCleIneCandidat()));
    }

    if (candidat.getCivilite() != null && candidat.getCivilite().getCodApo() != null) {
        String codSex = "";
        if (candidat.getCivilite().getCodApo().equals("1")) {
            codSex = "M";
        } else {
            codSex = "F";
        }
        etatCivil.setCodSexEtuOpi(codSex);
    }
    return etatCivil;
}
项目:hdfs-shell    文件:BashUtils.java   
public static String[] parseArguments(final String input) {
        if (StringUtils.isEmpty(input)) {
            return new String[0];
        }
        return ArgumentTokenizer.tokenize(input).toArray(new String[0]);
//        final Matcher m = ARG_PATTERN.matcher(input);
//        final List<String> list = new ArrayList<>();
//        while (m.find()) {
//            final String group3 = m.group(3);
//            if (group3 == null) {
//                list.add(m.group(1));
//            } else {
//                list.add(group3);
//            }
//        }
//        return list.toArray(new String[list.size()]);
    }
项目:springboot_cwenao    文件:HbaseFindBuilder.java   
/**
 * by map
 * @param map
 * @return
 */
public HbaseFindBuilder build(Map<String,String> map) {

    if (map == null || map.size() <= 0) {
        return this;
    }

    PropertyDescriptor p = null;
    byte[] qualifierByte = null;

    for (String value : map.values()) {
        if (StringUtils.isEmpty(value)) {
            continue;
        }

        p = fieldsMap.get(value.trim());
        qualifierByte = result.getValue(family.getBytes(), HumpNameOrMethodUtils.humpEntityForVar(value).getBytes());

        if (qualifierByte != null && qualifierByte.length > 0) {
            beanWrapper.setPropertyValue(p.getName(), Bytes.toString(qualifierByte));
            propertiesSet.add(p.getName());
        }
    }

    return this;
}
项目:lams    文件:BeanPropertyRowMapper.java   
/**
 * Convert a name in camelCase to an underscored name in lower case.
 * Any upper case letters are converted to lower case with a preceding underscore.
 * @param name the string containing original name
 * @return the converted name
 */
private String underscoreName(String name) {
    if (!StringUtils.hasLength(name)) {
        return "";
    }
    StringBuilder result = new StringBuilder();
    result.append(name.substring(0, 1).toLowerCase());
    for (int i = 1; i < name.length(); i++) {
        String s = name.substring(i, i + 1);
        String slc = s.toLowerCase();
        if (!s.equals(slc)) {
            result.append("_").append(slc);
        }
        else {
            result.append(s);
        }
    }
    return result.toString();
}
项目:JavaQuarkBBS    文件:ShiroService.java   
/**
 * 初始化权限
 */
public Map<String, String> loadFilterChainDefinitions() {
    // 权限控制map.从数据库获取
    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
    filterChainDefinitionMap.put("/logout", "logout");
    filterChainDefinitionMap.put("/css/**","anon");
    filterChainDefinitionMap.put("/js/**","anon");
    filterChainDefinitionMap.put("/img/**","anon");
    filterChainDefinitionMap.put("/font-awesome/**","anon");
    List<Permission> permissionList = permissionService.findAll();
    for(Permission p:permissionList){

        if (!StringUtils.isEmpty(p.getPerurl())) {
            String permission = "perms[" + p.getPerurl()+ "]";
            filterChainDefinitionMap.put(p.getPerurl(),permission);
        }
    }
    filterChainDefinitionMap.put("/**", "authc");
    return filterChainDefinitionMap;
}
项目:saluki    文件:TokenController.java   
private Collection<OAuth2AccessToken> enhance(Collection<OAuth2AccessToken> tokens) {
    Collection<OAuth2AccessToken> result = new ArrayList<OAuth2AccessToken>();
    for (OAuth2AccessToken prototype : tokens) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(prototype);
        OAuth2Authentication authentication = tokenStore.readAuthentication(token);
        if (authentication == null) {
            continue;
        }
        String userName = authentication.getName();
        if (StringUtils.isEmpty(userName)) {
            userName = "Unknown";
        }
        Map<String, Object> map = new HashMap<String, Object>(token.getAdditionalInformation());
        map.put("user_name", userName);
        token.setAdditionalInformation(map);
        result.add(token);
    }
    return result;
}
项目:springboot-shiro-cas-mybatis    文件:CommonController.java   
/**
 * do login
 * @param user userInfo
 * @param request requestInfo
 * @param response responseInfo
 * @param map data
 * @return login result
 * @throws IOException
 */
@RequestMapping(value="login",method = RequestMethod.POST)
public String doLogin(User user, HttpServletRequest request, HttpServletResponse response,ModelMap map) throws IOException{
    if(!StringUtils.isEmpty(user.getName())){
        request.getSession().setAttribute(Constant.SESSION_USER_KEY,user);

        //login success, redirect to home controller, change the url also. if return viewName,can't change url.
        response.sendRedirect("/home");
        return null;
    }else{
        map.put("welcomeMsg",this.msg);
        return "login"; //login failure, return login page
    }
}
项目:springboot-shiro-cas-mybatis    文件:SimpleMetadataUIInfo.java   
/**
 * Gets display name.
 *
 * @return the display name
 */
public String getDisplayName() {
    final Collection<String> items = getDisplayNames();
    if (items.isEmpty()) {
        return this.registeredService.getName();
    }
    return StringUtils.collectionToDelimitedString(items, ".");
}
项目:spring-backend-boilerplate    文件:UserRepositoryImpl.java   
@Override
public Page<User> queryPage(UsernameQueryRequest queryRequest) {
    int start = queryRequest.getStart();
    int limit = queryRequest.getLimit();
    Query query = new Query();
    if (!StringUtils.isEmpty(queryRequest.getUsername())) {
        query.addCriteria(Criteria.where("username").regex(queryRequest.getUsername()));
    }
    query.addCriteria(Criteria.where("deleted").ne(true));

    PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.ASC, "rank", "username"));
    query.with(pageable);
    long count = mongoTemplate.count(query, User.class);
    List<User> list = mongoTemplate.find(query, User.class);

    return new PageImpl<>(list, pageable, count);
}
项目:spring-backend-boilerplate    文件:SystemSettingServiceImpl.java   
@Override
public void saveSystemSetting(SaveSystemSettingRequest request, User byWho) {
    if (StringUtils.isEmpty(request.getName())) {
        throw new SystemSettingException("系统名称不能为空");
    }

    SystemSetting existedSystemSetting = getSystemSetting();
    if (existedSystemSetting == null) {
        existedSystemSetting = new SystemSetting();
        SystemSetting.onCreate(existedSystemSetting, byWho);
    }

    BeanUtils.copyProperties(request, existedSystemSetting);
    SystemSetting.onModify(existedSystemSetting, byWho);

    systemSettingRepository.save(existedSystemSetting);
}
项目:mapper-boot-starter    文件:MapperAutoConfiguration.java   
@PostConstruct
public void checkConfigFileExists() {
    if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
        Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
        Assert.state(resource.exists(), "Cannot find config location: " + resource
                + " (please add config file or check your Mybatis configuration)");
    }
}
项目:springboot-shiro-cas-mybatis    文件:SimpleMetadataUIInfo.java   
/**
 * Gets description.
 *
 * @return the description
 */
public String getDescription() {
    final Collection<String> items = getDescriptions();
    if (items.isEmpty()) {
        return this.registeredService.getDescription();
    }
    return StringUtils.collectionToDelimitedString(items, ".");
}
项目:CampusHelp    文件:MyInterceptor.java   
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    logger.debug(request.getRequestURI());
    if ("campus".equals(request.getHeader("accept-type"))) {
        if (!StringUtils.isEmpty(request.getHeader("token"))) {
            String token = request.getHeader("token");
            try {
                long endTime = tokenDao.getEndTime(token);
                long currentTime = System.currentTimeMillis() / 1000L;
                if (currentTime > endTime) {
                    response.getWriter().write("{code:300}");
                    return false;
                }
            } catch (Exception e) {
                response.setStatus(403);
                return false;
            }
        }
    } else {
        response.setStatus(403);
        return false;
    }
    logger.debug("preHandle");
    return true;
}
项目:CampusHelp    文件:LoginServiceImpl.java   
@Transactional
public String userLogin(long mobile, String captcha) throws LoginException {
    long now = System.currentTimeMillis() / 1000L;
    if (now - loginDao.getSendTime(mobile) < 300) {
        String uid = loginDao.login(mobile, captcha);
        if (StringUtils.isEmpty(uid)) {
            throw new LoginException("手机号或者验证码错误");
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setUid(Integer.parseInt(uid));
            userInfo.setGender("男");
            userInfo.setMobile(mobile);
            userInfo.setUname("互助" + uid);
            userInfo.setUavatar("http://172.16.0.9:8080/image/default.jpg");
            userDao.insertUserInfo(userInfo);
            String token = Md5Utils.getMD5Code(now + uid + mobile + key);
            tokenDao.insertToken(token, now + 11400000, Integer.parseInt(uid));
            return uid + "/" + token;
        }
    } else {
        throw new LoginException("验证码已失效");
    }
}
项目:gemini.blueprint    文件:BlueprintParser.java   
/**
 * Return a typed String value Object for the given value element.
 * 
 * @param ele element
 * @param defaultTypeName type class name
 * @return typed String value Object
 */
private Object parseValueElement(Element ele, String defaultTypeName) {
    // It's a literal value.
    String value = DomUtils.getTextValue(ele);
    String specifiedTypeName = ele.getAttribute(BeanDefinitionParserDelegate.TYPE_ATTRIBUTE);
    String typeName = specifiedTypeName;
    if (!StringUtils.hasText(typeName)) {
        typeName = defaultTypeName;
    }
    try {
        TypedStringValue typedValue = buildTypedStringValue(value, typeName);
        typedValue.setSource(extractSource(ele));
        typedValue.setSpecifiedTypeName(specifiedTypeName);
        return typedValue;
    } catch (ClassNotFoundException ex) {
        error("Type class [" + typeName + "] not found for <value> element", ele, ex);
        return value;
    }
}
项目:lams    文件:BeanDefinitionParserDelegate.java   
/**
 * Return a typed String value Object for the given value element.
 */
public Object parseValueElement(Element ele, String defaultTypeName) {
    // It's a literal value.
    String value = DomUtils.getTextValue(ele);
    String specifiedTypeName = ele.getAttribute(TYPE_ATTRIBUTE);
    String typeName = specifiedTypeName;
    if (!StringUtils.hasText(typeName)) {
        typeName = defaultTypeName;
    }
    try {
        TypedStringValue typedValue = buildTypedStringValue(value, typeName);
        typedValue.setSource(extractSource(ele));
        typedValue.setSpecifiedTypeName(specifiedTypeName);
        return typedValue;
    }
    catch (ClassNotFoundException ex) {
        error("Type class [" + typeName + "] not found for <value> element", ele, ex);
        return value;
    }
}
项目:bdf2    文件:DataTabInterceptor.java   
private void onInit(DataGrid dataGridData) throws Exception {
    DoradoContext dc = DoradoContext.getCurrent();
    String dbInfoId = (String) dc.getAttribute(DoradoContext.VIEW, "dbInfoId");
    String tableName = (String) dc.getAttribute(DoradoContext.VIEW, "tableName");
    String sql = (String) dc.getAttribute(DoradoContext.VIEW, "sql");
    String type = (String) dc.getAttribute(DoradoContext.VIEW, "type");
    List<ColumnInfo> columns = null;
    if (type.equals(SIMPLE_TYPE)) {
        if (StringUtils.hasText(tableName)) {
            columns = dbService.findColumnInfos(dbInfoId, tableName);
        }
        RowSelectorColumn selector = new RowSelectorColumn();
        selector.setVisible(true);
        selector.setIgnored(false);
        selector.setSupportsOptionMenu(true);
        dataGridData.addColumn(selector);
    } else {
        columns = dbService.findMultiColumnInfos(dbInfoId, sql);
    }
    DataColumn column;
    if (columns != null) {
        for (ColumnInfo info : columns) {
            column = new DataColumn();
            column.setName(info.getColumnName());
            column.setWidth(COLUMN_WIDTH);
            dataGridData.addColumn(column);
        }

    }
}
项目:spring-cloud-etcd    文件:EtcdAutoSerivceRegistrationAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean
public EtcdRegistration etcdAutoRegistration(InetUtils inetUtils, EtcdDiscoveryProperties properties) {
  if (StringUtils.isEmpty(properties.getAddress())) {
    String ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
    properties.setAddress(ipAddress);
  }
  return new EtcdRegistration(properties.getName(), properties.getAddress(), properties.getPort());
}
项目:spring-cloud-dashboard    文件:DeploymentPropertiesUtils.java   
private static String removeQuoting(String param) {
    param = removeQuote(param, '\'');
    param = removeQuote(param, '"');
    if (StringUtils.hasText(param)) {
        String[] split = param.split("=", 2);
        if (split.length == 2) {
            String value = removeQuote(split[1], '\'');
            value = removeQuote(value, '"');
            param = split[0] + "=" + value;
        }
    }
    return param;
}
项目:lams    文件:FacesRequestAttributes.java   
public static String[] getAttributeNames(ExternalContext externalContext) {
    Object session = externalContext.getSession(false);
    if (session instanceof PortletSession) {
        return StringUtils.toStringArray(
                ((PortletSession) session).getAttributeNames(PortletSession.APPLICATION_SCOPE));
    }
    else if (session != null) {
        return StringUtils.toStringArray(externalContext.getSessionMap().keySet());
    }
    else {
        return new String[0];
    }
}
项目:klask-io    文件:AngularCookieLocaleResolver.java   
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
    if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
        // Retrieve and parse cookie value.
        Cookie cookie = WebUtils.getCookie(request, getCookieName());
        Locale locale = null;
        TimeZone timeZone = null;
        if (cookie != null) {
            String value = cookie.getValue();

            // Remove the double quote
            value = StringUtils.replace(value, "%22", "");

            String localePart = value;
            String timeZonePart = null;
            int spaceIndex = localePart.indexOf(' ');
            if (spaceIndex != -1) {
                localePart = value.substring(0, spaceIndex);
                timeZonePart = value.substring(spaceIndex + 1);
            }
            locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
            if (timeZonePart != null) {
                timeZone = StringUtils.parseTimeZoneString(timeZonePart);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
                    "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
            }
        }
        request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
            (locale != null ? locale: determineDefaultLocale(request)));

        request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
            (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
    }
}
项目:JRediClients    文件:RedissonHttpSessionConfiguration.java   
@Bean
public RedissonSessionRepository sessionRepository(
        RedissonClient redissonClient, ApplicationEventPublisher eventPublisher) {
    RedissonSessionRepository repository = new RedissonSessionRepository(redissonClient, eventPublisher);
    if (StringUtils.hasText(keyPrefix)) {
        repository.setKeyPrefix(keyPrefix);
    }
    repository.setDefaultMaxInactiveInterval(maxInactiveIntervalInSeconds);
    return repository;
}
项目:configx    文件:RefreshBeanDependencyFactory.java   
/**
 * Return the names of all property that the specified bean depends on, if any.
 *
 * @param beanName the name of the bean
 * @return the array of dependent property names, or an empty array if none
 */
public String[] getDependentPropertyNames(String beanName) {
    beanName = ProxyUtils.getOriginalBeanName(beanName);
    Set<String> dependentPropertyNames = this.dependentPropertyMap.get(beanName);
    if (dependentPropertyNames == null) {
        return new String[0];
    }
    return StringUtils.toStringArray(dependentPropertyNames);
}
项目:spring-cloud-skipper    文件:AboutController.java   
private String constructUrl(String url, String version) {
    final String VERSION_TAG = "{version}";
    final String REPOSITORY_TAG = "{repository}";
    if (url.contains(VERSION_TAG)) {
        url = StringUtils.replace(url, VERSION_TAG, version);
        url = StringUtils.replace(url, REPOSITORY_TAG, repoSelector(version));
    }
    return url;
}
项目:iotgateway    文件:WiotpMqttBrokerMonitor.java   
@Override
public void onRpcCommand(String deviceName, RpcCommandData command) {
    int requestId = command.getRequestId();

    List<ServerSideRpcMapping> mappings = configuration.getServerSideRpc().stream()
            .filter(mapping -> deviceName.matches(mapping.getDeviceNameFilter()))
            .filter(mapping -> command.getMethod().matches(mapping.getMethodFilter())).collect(Collectors.toList());

    mappings.forEach(mapping -> {
        String requestTopic = replace(mapping.getRequestTopicExpression(), deviceName, command);
        String body = replace(mapping.getValueExpression(), deviceName, command);

        boolean oneway = StringUtils.isEmpty(mapping.getResponseTopicExpression());
        if (oneway) {
            publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
        } else {
            String responseTopic = replace(mapping.getResponseTopicExpression(), deviceName, command);
            try {
                log.info("[{}] Temporary subscribe to RPC response topic [{}]", deviceName, responseTopic);
                client.subscribe(responseTopic, 1,
                        new MqttRpcResponseMessageListener(requestId, deviceName, this::onRpcCommandResponse)
                ).waitForCompletion();
                scheduler.schedule(() -> {
                    unsubscribe(deviceName, requestId, responseTopic);
                }, mapping.getResponseTimeout(), TimeUnit.MILLISECONDS);
                publish(deviceName, requestTopic, new MqttMessage(body.getBytes(StandardCharsets.UTF_8)));
            } catch (MqttException e) {
                log.warn("[{}] Failed to subscribe to response topic and push RPC command [{}]", deviceName, requestId, e);
            }
        }
    });
}
项目:versioning-spring-boot-starter    文件:VersionRange.java   
public VersionRange(String from, String to) {
    if (StringUtils.isEmpty(from)) {
        throw new IllegalArgumentException("Define from in @VersionedResource");
    }
    this.from = new Version(from);
    this.to = new Version(to);
    if (this.from.compareTo(this.to) != -1 && this.from.compareTo(this.to) != 0) {
        throw new IllegalArgumentException("From is minor than to, bad definition");
    }
}
项目:gemini.blueprint    文件:BlueprintReferenceBeanDefinitionParser.java   
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
        throws BeanDefinitionStoreException {

    String id = element.getAttribute(ID_ATTRIBUTE);
    if (!StringUtils.hasText(id)) {
        id = generateBeanName("", definition, parserContext);
    }
    return id;
}
项目:spring-io    文件:JWTFilter.java   
private String resolveToken(HttpServletRequest request){
    String bearerToken = request.getHeader(JWTConfigurer.AUTHORIZATION_HEADER);
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
项目:cas-5.1.0    文件:PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java   
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        LOGGER.debug("Remote User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser));
    }
    return null;
}
项目:cas4.0.x-server-wechat    文件:TestOneTimePasswordAuthenticationHandler.java   
@Override
public String getName() {
    if (StringUtils.hasText(this.name)) {
        return this.name;
    } else {
        return getClass().getSimpleName();
    }
}
项目:azeroth    文件:MybatisInterceptor.java   
public void setInterceptorHandlers(String interceptorHandlers) {
    String[] handlerNames = StringUtils.tokenizeToStringArray(interceptorHandlers,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

    for (String name : handlerNames) {
        if (CacheHandler.NAME.equals(name)) {
            this.interceptorHandlers.add(new CacheHandler());
            cacheEnabled = true;
        } else if (RwRouteHandler.NAME.equals(name)) {
            this.interceptorHandlers.add(new RwRouteHandler());
            rwRouteEnabled = true;
        } else if (DatabaseRouteHandler.NAME.equals(name)) {
            this.interceptorHandlers.add(new DatabaseRouteHandler());
            dbShardEnabled = true;
        } else if (PaginationHandler.NAME.equals(name)) {
            this.interceptorHandlers.add(new PaginationHandler());
        }
    }
    //排序
    Collections.sort(this.interceptorHandlers, new Comparator<InterceptorHandler>() {
        @Override
        public int compare(InterceptorHandler o1, InterceptorHandler o2) {
            return Integer.compare(o1.interceptorOrder(), o2.interceptorOrder());
        }
    });

}
项目:spring-cloud-dashboard    文件:AbstractRdbmsKeyValueRepository.java   
private Page<D> queryForPageableResults(Pageable pageable, String selectClause, String tableName,
        String whereClause, Object[] queryParam, long totalCount) {
    //FIXME Possible performance improvement refactoring so factory isn't called every time.
    SqlPagingQueryProviderFactoryBean factoryBean = new SqlPagingQueryProviderFactoryBean();
    factoryBean.setSelectClause(selectClause);
    factoryBean.setFromClause(tableName);
    if (StringUtils.hasText(whereClause)) {
        factoryBean.setWhereClause(whereClause);
    }

    final Sort sort = pageable.getSort();
    final LinkedHashMap<String, Order> sortOrderMap = new LinkedHashMap<>();

    if (sort != null) {
        for (Sort.Order sortOrder : sort) {
            sortOrderMap.put(sortOrder.getProperty(), sortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);
        }
    }

    if (!CollectionUtils.isEmpty(sortOrderMap)) {
        factoryBean.setSortKeys(sortOrderMap);
    }
    else {
        factoryBean.setSortKeys(this.orderMap);
    }

    factoryBean.setDataSource(this.dataSource);
    PagingQueryProvider pagingQueryProvider;
    try {
        pagingQueryProvider = factoryBean.getObject();
        pagingQueryProvider.init(this.dataSource);
    }
    catch (Exception e) {
        throw new IllegalStateException(e);
    }
    String query = pagingQueryProvider.getPageQuery(pageable);
    List<D> resultList = jdbcTemplate.query(query, queryParam, rowMapper);
    return new PageImpl<>(resultList, pageable, totalCount);
}