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

The following are Jave code examples for showing how to use defaultIfBlank() 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: cas-5.1.0   File: SecurityTokenServiceClientBuilder.java   View Source Code Vote up 6 votes
/**
 * Build client for security token requests.
 *
 * @param service the rp
 * @return the security token service client
 */
public SecurityTokenServiceClient buildClientForSecurityTokenRequests(final WSFederationRegisteredService service) {
    final Bus cxfBus = BusFactory.getDefaultBus();
    final SecurityTokenServiceClient sts = new SecurityTokenServiceClient(cxfBus);
    sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
    sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
    sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
    sts.setWsdlLocation(prepareWsdlLocation(service));
    if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
        sts.setWspNamespace(service.getPolicyNamespace());
    }
    final String namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
    sts.setServiceQName(new QName(namespace, StringUtils.defaultIfBlank(service.getWsdlService(), WSFederationConstants.SECURITY_TOKEN_SERVICE)));
    sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
    sts.getProperties().putAll(new HashMap<>());
    return sts;
}
 
Example 2
Project: cas-5.1.0   File: SecurityTokenServiceClientBuilder.java   View Source Code Vote up 6 votes
/**
 * Build client for relying party token responses.
 *
 * @param securityToken the security token
 * @param service       the service
 * @return the security token service client
 */
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses(final SecurityToken securityToken,
                                                                           final WSFederationRegisteredService service) {
    final Bus cxfBus = BusFactory.getDefaultBus();
    final SecurityTokenServiceClient sts = new SecurityTokenServiceClient(cxfBus);
    sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
    sts.setWsdlLocation(prepareWsdlLocation(service));
    final String namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
    sts.setServiceQName(new QName(namespace, service.getWsdlService()));
    sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
    sts.setEnableAppliesTo(StringUtils.isNotBlank(service.getAppliesTo()));
    sts.setOnBehalfOf(securityToken.getToken());
    sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
    sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));

    if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
        sts.setWspNamespace(service.getPolicyNamespace());
    }

    return sts;
}
 
Example 3
Project: cas-5.1.0   File: CloudWatchAppender.java   View Source Code Vote up 6 votes
/**
 * Create appender cloud watch appender.
 *
 * @param name                             the name
 * @param awsLogStreamName                 the aws log stream name
 * @param awsLogGroupName                  the aws log group name
 * @param awsLogStreamFlushPeriodInSeconds the aws log stream flush period in seconds
 * @param credentialAccessKey              the credential access key
 * @param credentialSecretKey              the credential secret key
 * @param awsLogRegionName                 the aws log region name
 * @param layout                           the layout
 * @return the cloud watch appender
 */
@PluginFactory
public static CloudWatchAppender createAppender(@PluginAttribute("name") final String name,
                                                @PluginAttribute("awsLogStreamName") final String awsLogStreamName,
                                                @PluginAttribute("awsLogGroupName") final String awsLogGroupName,
                                                @PluginAttribute("awsLogStreamFlushPeriodInSeconds") final String awsLogStreamFlushPeriodInSeconds,
                                                @PluginAttribute("credentialAccessKey") final String credentialAccessKey,
                                                @PluginAttribute("credentialSecretKey") final String credentialSecretKey,
                                                @PluginAttribute("awsLogRegionName") final String awsLogRegionName,
                                                @PluginElement("Layout") final Layout<Serializable> layout) {
    return new CloudWatchAppender(
            name,
            awsLogGroupName,
            awsLogStreamName,
            awsLogStreamFlushPeriodInSeconds,
            StringUtils.defaultIfBlank(credentialAccessKey, System.getProperty("AWS_ACCESS_KEY")),
            StringUtils.defaultIfBlank(credentialSecretKey, System.getProperty("AWS_SECRET_KEY")),
            StringUtils.defaultIfBlank(awsLogRegionName, System.getProperty("AWS_REGION_NAME")),
            layout);
}
 
Example 4
Project: bird-java   File: AbstractController.java   View Source Code Vote up 6 votes
/** 异常处理 */
@ExceptionHandler(Exception.class)
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
        throws Exception {
    logger.error(Constants.Exception_Head, ex);
    OperationResult result=new OperationResult();
    if (ex instanceof AbstractException) {
        ((AbstractException) ex).handler(result);
    } /*else if (ex instanceof IllegalArgumentException) {
        new IllegalParameterException(ex.getMessage()).handler(modelMap);
    } else if (ex instanceof UnauthorizedException) {
        modelMap.put("httpCode", HttpCode.FORBIDDEN.value());
        modelMap.put("msg", StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.FORBIDDEN.msg()));
    } */else {
        result.setCode(HttpCode.INTERNAL_SERVER_ERROR.value());
        String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg());
        result.setMessage(msg.length() > 100 ? "系统走神了,请稍候再试." : msg);
    }
    response.setContentType("application/json;charset=UTF-8");
    logger.info(JSON.toJSONString(result));
    byte[] bytes = JSON.toJSONBytes(result, SerializerFeature.DisableCircularReferenceDetect);
    response.getOutputStream().write(bytes);
}
 
Example 5
Project: cyberduck   File: MantaAccountHomeInfo.java   View Source Code Vote up 6 votes
private Path buildNormalizedHomePath(final String rawHomePath) {
    final String defaultPath = StringUtils.defaultIfBlank(rawHomePath, Path.HOME);
    final String accountRootRegex = String.format("^/?(%s|~~?)/?", accountRoot.getAbsolute());
    final String subdirectoryRawPath = defaultPath.replaceFirst(accountRootRegex, "");

    if(StringUtils.isEmpty(subdirectoryRawPath)) {
        return accountRoot;
    }

    final String[] subdirectoryPathSegments = StringUtils.split(subdirectoryRawPath, Path.DELIMITER);
    Path homePath = accountRoot;

    for(final String pathSegment : subdirectoryPathSegments) {
        EnumSet<Path.Type> types = EnumSet.of(Path.Type.directory);
        if(homePath.getParent().equals(accountRoot)
            && StringUtils.equalsAny(pathSegment, HOME_PATH_PRIVATE, HOME_PATH_PUBLIC)) {
            types.add(Path.Type.volume);
        }

        homePath = new Path(homePath, pathSegment, types);
    }

    return homePath;
}
 
Example 6
Project: plugin-bt-jira   File: JiraBaseResource.java   View Source Code Vote up 5 votes
/**
 * Return the data source of JIRA database server.
 * 
 * @param parameters
 *            the subscription parameters containing at least the data source
 *            configuration.
 * @return the data source of JIRA database server.
 */
protected DataSource getDataSource(final Map<String, String> parameters) {
	try {
		return new SimpleDriverDataSource(
				(Driver) Class.forName(StringUtils.defaultIfBlank(parameters.get(PARAMETER_JDBC_DRIVER), "com.mysql.cj.jdbc.Driver"))
						.newInstance(),
				StringUtils.defaultIfBlank(parameters.get(PARAMETER_JDBC_URL),
						"jdbc:mysql://localhost:3306/jira6?useColumnNamesInFindColumn=true&useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true&maxReconnects=3"),
				parameters.get(PARAMETER_JDBC_USER), parameters.get(PARAMETER_JDBC_PASSSWORD));
	} catch (final Exception e) {
		log.error("Database connection issue for JIRA", e);
		throw new TechnicalException("Database connection issue for JIRA", e);
	}
}
 
Example 7
Project: cas-5.1.0   File: OAuth20CasAuthenticationBuilder.java   View Source Code Vote up 5 votes
/**
 * Create an authentication from a user profile.
 *
 * @param profile           the given user profile
 * @param registeredService the registered service
 * @param context           the context
 * @param service           the service
 * @return the built authentication
 */
public Authentication build(final UserProfile profile,
                            final OAuthRegisteredService registeredService,
                            final J2EContext context,
                            final Service service) {

    final Map<String, Object> profileAttributes = getPrincipalAttributesFromProfile(profile);
    final Principal newPrincipal = this.principalFactory.createPrincipal(profile.getId(), profileAttributes);
    LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);

    final String authenticator = profile.getClass().getCanonicalName();
    final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
    final HandlerResult handlerResult = new DefaultHandlerResult(authenticator, metadata, newPrincipal, new ArrayList<>());

    final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.STATE), StringUtils.EMPTY);
    final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.NONCE), StringUtils.EMPTY);
    LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce);

    /**
     * pac4j UserProfile.getPermissions() and getRoles() returns UnmodifiableSet which Jackson Serializer
     * happily serializes to json but is unable to deserialize.
     * We have to wrap it to HashSet to avoid such problem
     */
    final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance()
            .addAttribute("permissions", new HashSet<>(profile.getPermissions()))
            .addAttribute("roles", new HashSet<>(profile.getRoles()))
            .addAttribute(OAuth20Constants.STATE, state)
            .addAttribute(OAuth20Constants.NONCE, nonce)
            .addCredential(metadata)
            .setPrincipal(newPrincipal)
            .setAuthenticationDate(ZonedDateTime.now())
            .addSuccess(profile.getClass().getCanonicalName(), handlerResult);

    collectionAuthenticationAttributesIfNecessary(profile, bldr);
    return bldr.build();
}
 
Example 8
Project: JAVA-   File: SendMsgService.java   View Source Code Vote up 5 votes
/** 设置参数 */
private void setParams(String sender, SendMsg sendMsg) {
	String cacheKey1, cacheKey2;
	switch (sendMsg.getMsgType()) {
	case "1":// 用户注册验证码
		cacheKey2 = "REGIN_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "2":// 登录确认验证码
		cacheKey1 = "LOGIN_" + DateUtil.getDate() + "_" + sendMsg.getPhone();
		cacheKey2 = "LOGIN_" + sendMsg.getPhone();
		String times = StringUtils.defaultIfBlank(paramService.getValue("LOGIN_DAILY_TIMES"), "3");
		String msg = StringUtils.defaultIfBlank(paramService.getValue("LOGIN_LIMIT_MSG"), "您今天登录的次数已达到最大限制。");
		refreshSendTimes(cacheKey1, 60 * 60 * 24, Integer.parseInt(times), msg);
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "3":// 修改密码验证码
		cacheKey2 = "CHGPWD_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "4":// 身份验证验证码
		cacheKey2 = "VLDID_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "5":// 信息变更验证码
		cacheKey2 = "CHGINFO_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "6":// 活动确认验证码
		cacheKey2 = "AVTCMF_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	default:
		break;
	}
}
 
Example 9
Project: cas-5.1.0   File: CasPersonDirectoryConfiguration.java   View Source Code Vote up 5 votes
private IPersonAttributeDao composeMergedAndCachedAttributeRepositories(final List<IPersonAttributeDao> list) {
    final MergingPersonAttributeDaoImpl mergingDao = new MergingPersonAttributeDaoImpl();

    final String merger = StringUtils.defaultIfBlank(casProperties.getAuthn().getAttributeRepository().getMerger(), "replace".trim());
    LOGGER.debug("Configured merging strategy for attribute sources is [{}]", merger);
    switch (merger.toLowerCase()) {
        case "merge":
            mergingDao.setMerger(new MultivaluedAttributeMerger());
            break;
        case "add":
            mergingDao.setMerger(new NoncollidingAttributeAdder());
            break;
        case "replace":
        default:
            mergingDao.setMerger(new ReplacingAttributeAdder());
            break;
    }

    final CachingPersonAttributeDaoImpl impl = new CachingPersonAttributeDaoImpl();
    impl.setCacheNullResults(false);

    final Cache graphs = CacheBuilder.newBuilder()
            .concurrencyLevel(2)
            .weakKeys()
            .maximumSize(casProperties.getAuthn().getAttributeRepository().getMaximumCacheSize())
            .expireAfterWrite(casProperties.getAuthn().getAttributeRepository().getExpireInMinutes(), TimeUnit.MINUTES)
            .build();
    impl.setUserInfoCache(graphs.asMap());
    mergingDao.setPersonAttributeDaos(list);
    impl.setCachedPersonAttributesDao(mergingDao);

    if (list.isEmpty()) {
        LOGGER.debug("No attribute repository sources are available/defined to merge together.");
    } else {
        LOGGER.debug("Configured attribute repository sources to merge together: [{}]", list);
        LOGGER.debug("Configured cache expiration policy for merging attribute sources to be [{}] minute(s)",
                casProperties.getAuthn().getAttributeRepository().getExpireInMinutes());
    }
    return impl;
}
 
Example 10
Project: xm-commons   File: TimelineEventProducer.java   View Source Code Vote up 5 votes
private static String getResourceName(String path) {
    String name = StringUtils.removeStart(path, "/api/");
    if (StringUtils.startsWith(name, "_search")) {
        name = StringUtils.substringAfter(name, "/");
    }
    return StringUtils.defaultIfBlank(StringUtils.substringBefore(name, "/"), "unknown");
}
 
Example 11
Project: automat   File: SendMsgService.java   View Source Code Vote up 5 votes
/** 设置参数 */
private void setParams(String sender, SendMsg sendMsg) {
	String cacheKey1, cacheKey2;
	switch (sendMsg.getMsgType()) {
	case "1":// 用户注册验证码
		cacheKey2 = "REGIN_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "2":// 登录确认验证码
		cacheKey1 = "LOGIN_" + DateUtil.getDate() + "_" + sendMsg.getPhone();
		cacheKey2 = "LOGIN_" + sendMsg.getPhone();
		String times = StringUtils.defaultIfBlank(paramService.getValue("LOGIN_DAILY_TIMES"), "3");
		String msg = StringUtils.defaultIfBlank(paramService.getValue("LOGIN_LIMIT_MSG"), "您今天登录的次数已达到最大限制。");
		refreshSendTimes(cacheKey1, 60 * 60 * 24, Integer.parseInt(times), msg);
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "3":// 修改密码验证码
		cacheKey2 = "CHGPWD_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "4":// 身份验证验证码
		cacheKey2 = "VLDID_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "5":// 信息变更验证码
		cacheKey2 = "CHGINFO_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	case "6":// 活动确认验证码
		cacheKey2 = "AVTCMF_" + sendMsg.getPhone();
		sendRandomCode(sender, sendMsg, cacheKey2);
		break;
	default:
		break;
	}
}
 
Example 12
Project: smockin   File: MockedRestServerEngine.java   View Source Code Vote up 5 votes
String processRequest(final RestfulMock mock, final Request req, final Response res) {

        RestfulResponseDTO outcome;

        switch (mock.getMockType()) {
            case RULE:
                outcome = ruleEngine.process(req, mock.getRules());
                break;
            case PROXY_HTTP:
                outcome = proxyService.waitForResponse(req.pathInfo(), mock);
                break;
            case SEQ:
            default:
                outcome = mockOrderingCounterService.process(mock);
                break;
        }

        if (outcome == null) {
            // Load in default values
            outcome = getDefault(mock);
        }

        res.status(outcome.getHttpStatusCode());
        res.type(outcome.getResponseContentType());

        // Apply any response headers
        for (Map.Entry<String, String> e : outcome.getHeaders().entrySet()) {
            res.header(e.getKey(), e.getValue());
        }

        final String response = inboundParamMatchService.enrichWithInboundParamMatches(req, outcome.getResponseBody());

        return StringUtils.defaultIfBlank(response,"");
    }
 
Example 13
Project: cas-5.1.0   File: WSFederationRegisteredService.java   View Source Code Vote up 4 votes
public String getAppliesTo() {
    return StringUtils.defaultIfBlank(appliesTo, this.realm);
}
 
Example 14
Project: cas-5.1.0   File: JdbcCloudConfigBootstrapConfiguration.java   View Source Code Vote up 4 votes
public String getSql() {
    return StringUtils.defaultIfBlank(getSetting(environment, "sql"), SQL);
}
 
Example 15
Project: cas-5.1.0   File: JdbcCloudConfigBootstrapConfiguration.java   View Source Code Vote up 4 votes
@Override
public String getUrl() {
    return StringUtils.defaultIfBlank(getSetting(environment, "url"), super.getUrl());
}
 
Example 16
Project: cas-5.1.0   File: JdbcCloudConfigBootstrapConfiguration.java   View Source Code Vote up 4 votes
@Override
public String getPassword() {
    return StringUtils.defaultIfBlank(getSetting(environment, "password"), super.getPassword());
}
 
Example 17
Project: cas-5.1.0   File: JdbcCloudConfigBootstrapConfiguration.java   View Source Code Vote up 4 votes
@Override
public String getUser() {
    return StringUtils.defaultIfBlank(getSetting(environment, "user"), super.getUser());
}
 
Example 18
Project: cas-5.1.0   File: JdbcCloudConfigBootstrapConfiguration.java   View Source Code Vote up 4 votes
@Override
public String getDriverClass() {
    return StringUtils.defaultIfBlank(getSetting(environment, "driverClass"), super.getDriverClass());
}
 
Example 19
Project: cas-5.1.0   File: LdapAuthorizationProperties.java   View Source Code Vote up 4 votes
public String getGroupBaseDn() {
    return StringUtils.defaultIfBlank(groupBaseDn, this.baseDn);
}
 
Example 20
Project: jboot   File: ControllerReaderExtension.java   View Source Code Vote up 4 votes
private static String getResponseContainer(ApiOperation apiOperation) {
    return apiOperation == null ? null : StringUtils.defaultIfBlank(apiOperation.responseContainer(), null);
}