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

The following examples show how to use org.springframework.core.env.Environment#containsProperty() . 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
Source File: KafDrop.java    From Kafdrop with 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 2
Source File: JuiserSpringSecurityCondition.java    From juiser with Apache License 2.0 6 votes vote down vote up
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 3
Source File: GatewayRSocketAutoConfiguration.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: DefaultInstanceTypeProvider.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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 5
Source File: RegistryBeanProviderFactory.java    From Ratel with Apache License 2.0 5 votes vote down vote up
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 6
Source File: SpringPropertySource.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean containsProperty(String key) {
    Environment environment = getEnvironment();
    if (environment != null) {
        return environment.containsProperty(key);
    }
    return false;
}
 
Example 7
Source File: MybatisConfig.java    From genericdao with 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 8
Source File: ClientSecurityAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
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 9
Source File: SslAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
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 10
Source File: ClusterAwareConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
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 11
Source File: DefaultRootVolumeSizeProvider.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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 12
Source File: DubboDefaultPropertiesEnvironmentPostProcessor.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
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 13
Source File: MagicExistsCondition.java    From Project with 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 14
Source File: SslAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
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 15
Source File: DruidDataSourceConfig.java    From genericdao with Artistic License 2.0 4 votes vote down vote up
/**
 * 构建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 16
Source File: CloudFoundryCloudProfileProvider.java    From spring-cloud-skipper with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isCloudPlatform(Environment environment) {
	return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
 
Example 17
Source File: RegistryConfigContainer.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
/**
 * @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 18
Source File: CloudFoundryCloudProfileProvider.java    From spring-cloud-dataflow with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isCloudPlatform(Environment environment) {
	return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
 
Example 19
Source File: NodeSettings.java    From eventeum with 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 20
Source File: ClientSecurityAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 3 votes vote down vote up
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;
		}