Java Code Examples for org.springframework.util.StringUtils

The following are top voted examples for showing how to use org.springframework.util.StringUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SkillWill   File: OAuthMock.java   View source code 7 votes vote down vote up
@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);
}
 
Example 2
Project: openmrs-contrib-addonindex   File: Bintray.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 3
Project: gemini.blueprint   File: StandardAttributeCallback.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: mirrorgate   File: ServerSentEventsHandler.java   View source code 6 votes vote down vote up
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);
                }
            }
        }
    }
 
Example 5
Project: spring-backend-boilerplate   File: UserAccountServiceImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 6
Project: spring-cloud-skipper   File: AboutController.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: springDemos   File: ExceptionHandlerAspect.java   View source code 6 votes vote down vote up
@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;
}
 
Example 8
Project: spring-backend-boilerplate   File: UserAccountServiceImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 9
Project: esup-ecandidat   File: SiScolApogeeWSServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @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;
}
 
Example 10
Project: hdfs-shell   File: BashUtils.java   View source code 6 votes vote down vote up
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()]);
    }
 
Example 11
Project: springboot_cwenao   File: HbaseFindBuilder.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: lams   File: BeanPropertyRowMapper.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 13
Project: JavaQuarkBBS   File: ShiroService.java   View source code 6 votes vote down vote up
/**
 * 初始化权限
 */
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;
}
 
Example 14
Project: saluki   File: TokenController.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: springboot-shiro-cas-mybatis   File: CommonController.java   View source code 6 votes vote down vote up
/**
 * 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
    }
}
 
Example 16
Project: springboot-shiro-cas-mybatis   File: SimpleMetadataUIInfo.java   View source code 6 votes vote down vote up
/**
 * 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, ".");
}
 
Example 17
Project: spring-backend-boilerplate   File: UserRepositoryImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 18
Project: spring-backend-boilerplate   File: SystemSettingServiceImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: mapper-boot-starter   File: MapperAutoConfiguration.java   View source code 6 votes vote down vote up
@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)");
    }
}
 
Example 20
Project: springboot-shiro-cas-mybatis   File: SimpleMetadataUIInfo.java   View source code 6 votes vote down vote up
/**
 * Gets description.
 *
 * @return the description
 */
public String getDescription() {
    final Collection<String> items = getDescriptions();
    if (items.isEmpty()) {
        return this.registeredService.getDescription();
    }
    return StringUtils.collectionToDelimitedString(items, ".");
}
 
Example 21
Project: CampusHelp   File: MyInterceptor.java   View source code 6 votes vote down vote up
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;
}
 
Example 22
Project: CampusHelp   File: LoginServiceImpl.java   View source code 6 votes vote down vote up
@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("验证码已失效");
    }
}
 
Example 23
Project: gemini.blueprint   File: BlueprintParser.java   View source code 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 24
Project: lams   File: BeanDefinitionParserDelegate.java   View source code 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 25
Project: bdf2   File: DataTabInterceptor.java   View source code 5 votes vote down vote up
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);
		}

	}
}
 
Example 26
Project: spring-cloud-etcd   File: EtcdAutoSerivceRegistrationAutoConfiguration.java   View source code 5 votes vote down vote up
@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());
}
 
Example 27
Project: spring-cloud-dashboard   File: DeploymentPropertiesUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 28
Project: lams   File: FacesRequestAttributes.java   View source code 5 votes vote down vote up
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];
	}
}
 
Example 29
Project: klask-io   File: AngularCookieLocaleResolver.java   View source code 5 votes vote down vote up
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)));
    }
}
 
Example 30
Project: JRediClients   File: RedissonHttpSessionConfiguration.java   View source code 5 votes vote down vote up
@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;
}
 
Example 31
Project: configx   File: RefreshBeanDependencyFactory.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 32
Project: spring-cloud-skipper   File: AboutController.java   View source code 5 votes vote down vote up
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;
}
 
Example 33
Project: iotgateway   File: WiotpMqttBrokerMonitor.java   View source code 5 votes vote down vote up
@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);
            }
        }
    });
}
 
Example 34
Project: versioning-spring-boot-starter   File: VersionRange.java   View source code 5 votes vote down vote up
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");
    }
}
 
Example 35
Project: gemini.blueprint   File: BlueprintReferenceBeanDefinitionParser.java   View source code 5 votes vote down vote up
@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;
}
 
Example 36
Project: spring-io   File: JWTFilter.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: cas-5.1.0   File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java   View source code 5 votes vote down vote up
@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;
}
 
Example 38
Project: cas4.0.x-server-wechat   File: TestOneTimePasswordAuthenticationHandler.java   View source code 5 votes vote down vote up
@Override
public String getName() {
    if (StringUtils.hasText(this.name)) {
        return this.name;
    } else {
        return getClass().getSimpleName();
    }
}
 
Example 39
Project: azeroth   File: MybatisInterceptor.java   View source code 5 votes vote down vote up
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());
        }
    });

}
 
Example 40
Project: spring-cloud-dashboard   File: AbstractRdbmsKeyValueRepository.java   View source code 5 votes vote down vote up
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);
}