Java Code Examples for org.springframework.core.env.Environment#containsProperty()

The following examples show how to use org.springframework.core.env.Environment#containsProperty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private boolean isSpringSecurityEnabled(ConditionContext ctx) {

        boolean enabled = true;

        Environment env = ctx.getEnvironment();

        for (String propName : props) {
            if (env.containsProperty(propName)) {
                if (!Boolean.parseBoolean(env.getProperty(propName))) {
                    enabled = false;
                    break;
                }
            }
        }

        if (enabled) {
            enabled = ClassUtils.isPresent(SPRING_SEC_CLASS_NAME, ctx.getClassLoader());
        }

        return enabled;
    }
 
Example 2
Source Project: Kafdrop   File: KafDrop.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event)
{
   Environment environment = event.getEnvironment();
   final String loggingFile = environment.getProperty(PROP_LOGGING_FILE);
   if (loggingFile != null)
   {
      System.setProperty(PROP_LOGGER, "FILE");
      try
      {
         System.setProperty("logging.dir", new File(loggingFile).getParent());
      }
      catch (Exception ex)
      {
         System.err.println("Unable to set up logging.dir from logging.file " + loggingFile + ": " +
                            Throwables.getStackTraceAsString(ex));
      }
   }
   if (environment.containsProperty("debug") &&
       !"false".equalsIgnoreCase(environment.getProperty("debug", String.class)))
   {
      System.setProperty(PROP_SPRING_BOOT_LOG_LEVEL, "DEBUG");
   }
   setProccessId();

}
 
Example 3
Source Project: Project   File: MagicExistsCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
	//获取环境
	Environment env = context.getEnvironment();
	//包含环境属性 magic 则返回true
	return env.containsProperty("magic");
}
 
Example 4
@Bean
public BrokerProperties brokerProperties(Environment env,
		@Qualifier(ID_GENERATOR_BEAN_NAME) Supplier<BigInteger> idGenerator) {
	BrokerProperties properties = new BrokerProperties();
	// set default from env
	if (env.containsProperty("spring.application.name")) {
		properties.setId(env.getProperty("spring.application.name"));
	}
	properties.setRouteId(idGenerator.get());
	return properties;
}
 
Example 5
private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) {
    String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
    if (StringUtils.hasLength(springApplicationName)
            && !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) {
        defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName);
    }
}
 
Example 6
private Integer initPlatform(Environment environment, Platform platform) {
    String propetyKey = ROOT_VOLUME_SIZE_PROPERTY_PREFIX + platform.value();
    if (!environment.containsProperty(propetyKey)) {
        LOGGER.debug("{} property is not set. Defaulting its value to 50.", propetyKey);
    }
    return Integer.valueOf(environment.getProperty(propetyKey, DEFAULT_ROOT_VOLUME_SIZE.toString()));
}
 
Example 7
void configureTopology(Environment environment, ConnectionEndpointList connectionEndpoints,
		int connectionCount) {

	if (connectionCount < 1) {
		if (!environment.containsProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY)) {
			System.setProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY,
				LOCAL_CLIENT_REGION_SHORTCUT.name());
		}
	}
}
 
Example 8
private static boolean isSslConfigured(Environment environment) {

		return (environment.containsProperty(SECURITY_SSL_KEYSTORE_PROPERTY)
			&& environment.containsProperty(SECURITY_SSL_TRUSTSTORE_PROPERTY))
			|| (environment.containsProperty(GEMFIRE_SSL_KEYSTORE_PROPERTY)
			&& environment.containsProperty(GEMFIRE_SSL_TRUSTSTORE_PROPERTY));
	}
 
Example 9
private void configureAuthentication(Environment environment, VcapPropertySource vcapPropertySource,
		CloudCacheService cloudCacheService, Properties cloudCacheProperties) {

	if (isSecurityPropertiesNotSet(environment)) {
		if (environment.containsProperty(SECURITY_USERNAME_PROPERTY)) {

			String targetUsername = environment.getProperty(SECURITY_USERNAME_PROPERTY);

			vcapPropertySource.findUserByName(cloudCacheService, targetUsername)
				.flatMap(User::getPassword)
				.map(password -> {

					cloudCacheProperties.setProperty(SECURITY_USERNAME_PROPERTY, targetUsername);
					cloudCacheProperties.setProperty(SECURITY_PASSWORD_PROPERTY, password);

					return password;

				})
				.orElseThrow(() -> newIllegalStateException(
					"No User with name [%s] was configured for Cloud Cache service [%s]",
						targetUsername, cloudCacheService.getName()));
		}
		else {
			vcapPropertySource.findFirstUserByRoleClusterOperator(cloudCacheService)
				.ifPresent(user -> {

					cloudCacheProperties.setProperty(SECURITY_USERNAME_PROPERTY, user.getName());

					user.getPassword().ifPresent(password ->
						cloudCacheProperties.setProperty(SECURITY_PASSWORD_PROPERTY, password));
				});
		}
	}
}
 
Example 10
Source Project: genericdao   File: MybatisConfig.java    License: Artistic License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource , Environment environment) throws IOException{
	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
	sqlSessionFactoryBean.setDataSource(dataSource);
	//别名包
	sqlSessionFactoryBean.setTypeAliasesPackage(environment.getRequiredProperty(PROPERTY_MYBATIS_ALIAS_PACKAGE));
	
	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver() ;
	//获取mybatis映射文件路径,classpath:mybatis/mybatis-config.xml
	if(environment.containsProperty(PROPERTY_MYBATIS_CONFIG)){
		sqlSessionFactoryBean.setConfigLocation(resolver.getResource(environment.getRequiredProperty(PROPERTY_MYBATIS_CONFIG)));
	}
	//获取mybatis映射文件路径,例:classpath*:com/framework/sample/mapper/*Mapper.xml
	sqlSessionFactoryBean.setMapperLocations(resolver.getResources(environment.getRequiredProperty(PROPERTY_MYBATIS_MAPPER_LOCATION)));

	//开启后将在启动时检查设定的parameterMap,resultMap是否存在,是否合法
	sqlSessionFactoryBean.setFailFast(true) ;

	//存储mybatis的插件
	List<Interceptor> interceptorList = new ArrayList<Interceptor>() ;
	//初始化mybatis的插件
	initPlugins(interceptorList , environment) ;
	//设置mybatis插件
	sqlSessionFactoryBean.setPlugins(interceptorList.toArray(new Interceptor[]{}));

	//创建自定义的的Configuration
	Configuration configuration = new Configuration() ;
	//设置ObjectWrapperFactory,在其中映射mybatis查询结果和jpa实体
	configuration.setObjectWrapperFactory(new JPAObjectWrapperFactory());
	sqlSessionFactoryBean.setConfiguration(configuration);

	return sqlSessionFactoryBean ;
}
 
Example 11
@Override
public boolean containsProperty(String key) {
    Environment environment = getEnvironment();
    if (environment != null) {
        return environment.containsProperty(key);
    }
    return false;
}
 
Example 12
protected RegistryStrategiesProvider doCreate(ConfigurableListableBeanFactory beanFactory) {
    final Environment environment = beanFactory.getBean(Environment.class);

    if (environment.containsProperty(SERVICE_DISCOVERY_ZK_HOST)) {
        return new ZookeeperRegistryBeanProvider(beanFactory);
    } else if (environment.containsProperty(SERVICE_DISCOVERY_ADDRESS)) {
        return new InMemoryRegistryBeanProviderFactory(beanFactory);
    }

    throw new IllegalStateException(String.format("Provide one of props with registry either %s or %s",
            SERVICE_DISCOVERY_ZK_HOST, SERVICE_DISCOVERY_ADDRESS));
}
 
Example 13
private String initPlatform(Environment environment, Platform platform) {
    String propetyKey = DEFAULT_INSTANCE_TYPE_PROPERTY_PERFIX + platform.value();
    if (!environment.containsProperty(propetyKey)) {
        LOGGER.debug("{} property is not set. Defaulting its value to empty string.", propetyKey);
    }
    return environment.getProperty(propetyKey, "");
}
 
Example 14
Source Project: eventeum   File: NodeSettings.java    License: Apache License 2.0 4 votes vote down vote up
private boolean nodeExistsAtIndex(Environment environment, int index) {
    return environment.containsProperty(buildNodeAttribute(NODE_NAME_ATTRIBUTE, index));
}
 
Example 15
/**
 * @param registryAlias
 * @return
 * @throws SofaBootRpcRuntimeException
 */
public RegistryConfig getRegistryConfig(String registryAlias) throws SofaBootRpcRuntimeException {
    RegistryConfig registryConfig;
    String registryProtocol;
    String registryAddress;

    String currentDefaultAlias;

    if (StringUtils.isNotBlank(customDefaultRegistry)) {
        currentDefaultAlias = customDefaultRegistry;
    } else {
        currentDefaultAlias = DEFAULT_REGISTRY;
    }

    if (StringUtils.isEmpty(registryAlias)) {
        registryAlias = currentDefaultAlias;
    }

    //cloud be mesh,default,zk

    if (registryConfigs.get(registryAlias) != null) {
        return registryConfigs.get(registryAlias);
    }

    // just for new address
    if (DEFAULT_REGISTRY.equalsIgnoreCase(registryAlias)) {
        registryAddress = sofaBootRpcProperties.getRegistryAddress();
    } else if (registryAlias.equals(customDefaultRegistry)) {
        registryAddress = customDefaultRegistryAddress;
    } else {
        registryAddress = sofaBootRpcProperties.getRegistries().get(registryAlias);
    }

    //for worst condition.
    if (StringUtils.isBlank(registryAddress)) {
        registryProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL;
    } else {
        final int endIndex = registryAddress.indexOf("://");
        if (endIndex != -1) {
            registryProtocol = registryAddress.substring(0, endIndex);
        } else {
            registryProtocol = registryAlias;
        }
    }

    if (registryConfigMap.get(registryProtocol) != null) {
        RegistryConfigureProcessor registryConfigureProcessor = registryConfigMap.get(registryProtocol);
        registryConfig = registryConfigureProcessor.buildFromAddress(registryAddress);
        registryConfigs.put(registryAlias, registryConfig);
        //不再处理以.分隔的.
        final Environment environment = sofaBootRpcProperties.getEnvironment();
        if (environment.containsProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE)) {
            if (Boolean.TRUE.toString().equalsIgnoreCase(
                environment.getProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE))) {
                registryConfig.setRegister(false);
            }
        }
        return registryConfig;
    } else {
        throw new SofaBootRpcRuntimeException("registry config [" + registryAddress + "] is not supported");
    }
}
 
Example 16
@Override
public boolean isCloudPlatform(Environment environment) {
	return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
 
Example 17
private static String resolveTrustedKeystoreName(Environment environment) {

		return environment != null && environment.containsProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
			? environment.getProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
			: TRUSTED_KEYSTORE_FILENAME;
	}
 
Example 18
/**
 * 构建alibaba的数据库连接池
 * @param environment
 * @param propertyPrefix
 * @return
 */
@Override
public DataSource buildDataSource(Environment environment , String propertyPrefix){
	DruidDataSource dataSource = new DruidDataSource() ;
	
	dataSource.setDriverClassName(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_DRIVER));
	dataSource.setUrl(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_URL));
	dataSource.setUsername(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_USERNAME));
	dataSource.setPassword(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_PASSWORD));
	
	//分别设置最大和最小连接数
	if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE)){
		dataSource.setMaxActive(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE , Integer.class));
	}
	
	if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE)){
		dataSource.setMinIdle(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE , Integer.class));
	}
	
	dataSource.setDefaultAutoCommit(false);
	
	//是否需要进行验证
	dataSource.setValidationQuery(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_QUERY));
	//由连接池中获取连接时,需要进行验证
	dataSource.setTestOnBorrow(true) ;
	//归还连接时不需要验证
	dataSource.setTestOnReturn(false) ;
	//连接空闲时进行验证
	dataSource.setTestWhileIdle(true) ;

	//设置datasource监控,只对sql执行状态进行监控
	try {
		dataSource.setFilters("stat") ;
	}catch (Exception e){
		e.printStackTrace() ;
	}

	if(StringUtils.isNotBlank(environment.getProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL))){
		//连接有效的验证时间间隔
		dataSource.setValidationQueryTimeout(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Integer.class));
		//连接空闲验证的时间间隔
		dataSource.setTimeBetweenEvictionRunsMillis(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Long.class));
	}
	
	return dataSource ;
}
 
Example 19
@Override
public boolean isCloudPlatform(Environment environment) {
	return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
 
Example 20
private boolean isSecurityPropertiesSet(Environment environment) {

			boolean securityPropertiesSet = environment.containsProperty(SECURITY_USERNAME_PROPERTY)
				&& environment.containsProperty(SECURITY_PASSWORD_PROPERTY);

			logger.debug("Security Properties set? [{}]", securityPropertiesSet);

			return securityPropertiesSet;
		}