Java Code Examples for org.springframework.core.env.Environment

The following examples show how to use org.springframework.core.env.Environment. 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
Source Project: spring-cloud-zookeeper   Author: spring-cloud   File: ZookeeperLoadBalancerConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnBean(DiscoveryClient.class)
@ConditionalOnMissingBean
public ServiceInstanceListSupplier zookeeperDiscoveryClientServiceInstanceListSupplier(
		DiscoveryClient discoveryClient, Environment env,
		ApplicationContext context,
		ZookeeperDependencies zookeeperDependencies) {
	DiscoveryClientServiceInstanceListSupplier firstDelegate = new DiscoveryClientServiceInstanceListSupplier(
			discoveryClient, env);
	ZookeeperServiceInstanceListSupplier secondDelegate = new ZookeeperServiceInstanceListSupplier(firstDelegate,
			zookeeperDependencies);
	ObjectProvider<LoadBalancerCacheManager> cacheManagerProvider = context
			.getBeanProvider(LoadBalancerCacheManager.class);
	if (cacheManagerProvider.getIfAvailable() != null) {
		return new CachingServiceInstanceListSupplier(secondDelegate,
				cacheManagerProvider.getIfAvailable());
	}
	return secondDelegate;
}
 
Example #2
Source Project: blackduck-alert   Author: blackducksoftware   File: AlertStartupInitializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInitializeConfigs() throws Exception {
    Environment environment = Mockito.mock(Environment.class);
    DescriptorAccessor baseDescriptorAccessor = Mockito.mock(DescriptorAccessor.class);
    ConfigurationAccessor baseConfigurationAccessor = Mockito.mock(ConfigurationAccessor.class);
    EncryptionUtility encryptionUtility = Mockito.mock(EncryptionUtility.class);
    Mockito.when(encryptionUtility.isInitialized()).thenReturn(Boolean.TRUE);
    EncryptionSettingsValidator encryptionValidator = new EncryptionSettingsValidator(encryptionUtility);
    ChannelDescriptor channelDescriptor = new EmailDescriptor(EMAIL_CHANNEL_KEY, new EmailGlobalUIConfig(encryptionValidator), null);
    List<DescriptorKey> descriptorKeys = List.of(channelDescriptor.getDescriptorKey());
    List<ChannelDescriptor> channelDescriptors = List.of(channelDescriptor);
    List<ProviderDescriptor> providerDescriptors = List.of();
    List<ComponentDescriptor> componentDescriptors = List.of();
    EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment);
    DescriptorMap descriptorMap = new DescriptorMap(descriptorKeys, channelDescriptors, providerDescriptors, componentDescriptors);
    ConfigurationFieldModelConverter modelConverter = new ConfigurationFieldModelConverter(encryptionUtility, baseDescriptorAccessor, descriptorMap);
    Mockito.when(baseDescriptorAccessor.getFieldsForDescriptor(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class))).thenReturn(List.copyOf(channelDescriptor.getAllDefinedFields(ConfigContextEnum.GLOBAL)));

    FieldModelProcessor fieldModelProcessor = new FieldModelProcessor(modelConverter, new FieldValidationAction(), new DescriptorProcessor(descriptorMap, baseConfigurationAccessor, List.of(), List.of()));
    SettingsUtility settingsUtility = Mockito.mock(SettingsUtility.class);
    Mockito.when(settingsUtility.getKey()).thenReturn(new SettingsDescriptorKey());
    AlertStartupInitializer initializer = new AlertStartupInitializer(descriptorMap, environmentVariableUtility, baseDescriptorAccessor, baseConfigurationAccessor, modelConverter, fieldModelProcessor, settingsUtility);
    initializer.initializeComponent();
    Mockito.verify(baseDescriptorAccessor, Mockito.times(3)).getFieldsForDescriptor(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class));
    Mockito.verify(baseConfigurationAccessor, Mockito.times(2)).getConfigurationsByDescriptorKeyAndContext(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class));
}
 
Example #3
Source Project: spring-cloud-gcp   Author: spring-cloud   File: GoogleConfigPropertySourceLocator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (!this.enabled) {
		return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap());
	}
	Map<String, Object> config;
	try {
		GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment();
		Assert.notNull(googleConfigEnvironment, "Configuration not in expected format.");
		config = googleConfigEnvironment.getConfig();
	}
	catch (Exception ex) {
		String message = String.format("Error loading configuration for %s/%s_%s", this.projectId,
				this.name, this.profile);
		throw new RuntimeException(message, ex);
	}
	return new MapPropertySource(PROPERTY_SOURCE_NAME, config);
}
 
Example #4
Source Project: alf.io   Author: alfio-event   File: WebSecurityConfig.java    License: GNU General Public License v3.0 6 votes vote down vote up
public OpenIdFormBasedWebSecurity(Environment environment,
                                  UserManager userManager,
                                  RecaptchaService recaptchaService,
                                  ConfigurationManager configurationManager,
                                  CsrfTokenRepository csrfTokenRepository,
                                  DataSource dataSource,
                                  PasswordEncoder passwordEncoder,
                                  OpenIdAuthenticationManager openIdAuthenticationManager,
                                  UserRepository userRepository,
                                  AuthorityRepository authorityRepository,
                                  UserOrganizationRepository userOrganizationRepository,
                                  OrganizationRepository organizationRepository) {
    super(environment, userManager, recaptchaService, configurationManager, csrfTokenRepository,
        dataSource, passwordEncoder, openIdAuthenticationManager, userRepository, authorityRepository,
        userOrganizationRepository, organizationRepository);
}
 
Example #5
Source Project: spring-cloud-commons   Author: spring-cloud   File: BootstrapConfigurationTests.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (this.name != null) {
		then(this.name)
				.isEqualTo(environment.getProperty("spring.application.name"));
	}
	if (this.fail) {
		throw new RuntimeException("Planned");
	}
	CompositePropertySource compositePropertySource = new CompositePropertySource(
			"listTestBootstrap");
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap1", MAP1));
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap2", MAP2));
	return compositePropertySource;
}
 
Example #6
Source Project: tutorials   Author: eugenp   File: BaeldungApp.java    License: MIT License 6 votes vote down vote up
/**
 * Main method, used to run the application.
 *
 * @param args the command line arguments
 * @throws UnknownHostException if the local host name could not be resolved into an address
 */
public static void main(String[] args) throws UnknownHostException {
    SpringApplication app = new SpringApplication(BaeldungApp.class);
    DefaultProfileUtil.addDefaultProfile(app);
    Environment env = app.run(args).getEnvironment();
    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
        protocol = "https";
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\t{}://localhost:{}\n\t" +
            "External: \t{}://{}:{}\n\t" +
            "Profile(s): \t{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        protocol,
        env.getProperty("server.port"),
        protocol,
        InetAddress.getLocalHost().getHostAddress(),
        env.getProperty("server.port"),
        env.getActiveProfiles());
}
 
Example #7
Source Project: sofa-common-tools   Author: sofastack   File: LogbackIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * test logging.config.{space id} config
 * @throws IOException
 */
@Test
public void testLogConfig() throws IOException {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(Constants.LOG_CONFIG_PREFIX + TEST_SPACE, "logback-test-conf.xml");
    SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
    springApplication.setDefaultProperties(properties);
    ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {});
    Environment environment = applicationContext.getEnvironment();
    File logFile = getLogbackDefaultFile(environment);
    FileUtils.write(logFile, StringUtil.EMPTY_STRING,
        environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
    logger.info("info level");
    List<String> contents = FileUtils.readLines(logFile,
        environment.getProperty(Constants.LOG_ENCODING_PROP_KEY));
    Assert.assertEquals(1, contents.size());
    Assert.assertTrue(contents.get(0).contains("logback-test-conf"));
    LogEnvUtils.processGlobalSystemLogProperties().remove(
        Constants.LOG_CONFIG_PREFIX + TEST_SPACE);
}
 
Example #8
Source Project: spring-boot-starter-motan   Author: chenxing2   File: BasicServiceConfigCondition.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * match [motan.basicservice.exportPort, motan.basicservice.export] config property
 * 
 * @see org.springframework.context.annotation.Condition#matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata)
 */
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
	Environment env = context.getEnvironment();
	return (!StringUtils.isEmpty(env.getProperty("motan.basicservice.exportPort"))
			|| !StringUtils.isEmpty(env.getProperty("motan.basicservice.export")));
}
 
Example #9
Source Project: cloudbreak   Author: hortonworks   File: DefaultRootVolumeSizeProvider.java    License: 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 #10
Source Project: iot-dc   Author: Theembers   File: TheEmbersBanner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
    for (String line : BANNER) {
        out.println(AnsiOutput.toString(BRIGHT_BLUE, line));
    }

    String version = Banner.class.getPackage().getImplementationVersion();
    version = (version == null ? "" : " (v" + version + ")...");
    out.println(AnsiOutput.toString(BRIGHT_YELLOW, SPRING_BOOT, version));
    out.println();
}
 
Example #11
Source Project: airsonic-advanced   Author: airsonic-advanced   File: SettingsService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void setDefaultConstants(Environment env, Map<String, Object> defaultConstants) {
    // if jndi is set, everything datasource-related is ignored
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_URL))) {
        defaultConstants.put(KEY_DATABASE_URL, getDefaultJDBCUrl());
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_USERNAME))) {
        defaultConstants.put(KEY_DATABASE_USERNAME, getDefaultJDBCUsername());
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_PASSWORD))) {
        defaultConstants.put(KEY_DATABASE_PASSWORD, getDefaultJDBCPassword());
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_MIGRATION_ROLLBACK_FILE))) {
        defaultConstants.put(
                KEY_DATABASE_MIGRATION_ROLLBACK_FILE,
                getAirsonicHome().toAbsolutePath().resolve("rollback.sql").toFile());
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_MIGRATION_PARAMETER_MYSQL_VARCHAR_MAXLENGTH))) {
        defaultConstants.put(
                KEY_DATABASE_MIGRATION_PARAMETER_MYSQL_VARCHAR_MAXLENGTH,
                DEFAULT_DATABASE_MIGRATION_PARAMETER_MYSQL_VARCHAR_MAXLENGTH.toString());
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_MIGRATION_PARAMETER_USERTABLE_QUOTE))) {
        defaultConstants.put(
                KEY_DATABASE_MIGRATION_PARAMETER_USERTABLE_QUOTE,
                DEFAULT_DATABASE_MIGRATION_PARAMETER_USERTABLE_QUOTE);
    }
    if (StringUtils.isBlank(env.getProperty(KEY_DATABASE_MIGRATION_PARAMETER_DEFAULT_MUSIC_FOLDER))) {
        defaultConstants.put(KEY_DATABASE_MIGRATION_PARAMETER_DEFAULT_MUSIC_FOLDER, Util.getDefaultMusicFolder());
    }
}
 
Example #12
Source Project: ByteTCC   Author: liuyangming   File: CompensableLoadBalance.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private synchronized void initializeIfNecessary() {
	if (this.loadBalancer == null) {
		Environment environment = CompensableBeanRegistry.getInstance().getEnvironment();
		String loadBalanceKey = environment.getProperty(CONSTANT_LOADBALANCE_KEY, "default");
		ExtensionLoader<ILoadBalancer> extensionLoader = ExtensionLoader.getExtensionLoader(ILoadBalancer.class);
		this.loadBalancer = extensionLoader.getExtension(loadBalanceKey);
	}
}
 
Example #13
public static void main(String[] args) {
    new SpringApplicationBuilder(DubboRegistryZooKeeperProviderBootstrap.class)
        .listeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> {
            Environment environment = event.getEnvironment();
            int port = environment.getProperty("embedded.zookeeper.port", int.class);
            new EmbeddedZooKeeper(port, false).start();
        })
        .run(args);
}
 
Example #14
Source Project: spring4-understanding   Author: langtianya   File: AbstractApplicationContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>The parent {@linkplain ApplicationContext#getEnvironment() environment} is
 * {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with
 * this (child) application context environment if the parent is non-{@code null} and
 * its environment is an instance of {@link ConfigurableEnvironment}.
 * @see ConfigurableEnvironment#merge(ConfigurableEnvironment)
 */
@Override
public void setParent(ApplicationContext parent) {
	this.parent = parent;
	if (parent != null) {
		Environment parentEnvironment = parent.getEnvironment();
		if (parentEnvironment instanceof ConfigurableEnvironment) {
			getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
		}
	}
}
 
Example #15
Source Project: jasypt-spring-boot   Author: ulisesbocchio   File: DefaultLazyPropertyResolver.java    License: MIT License 5 votes vote down vote up
public DefaultLazyPropertyResolver(EncryptablePropertyDetector propertyDetector, StringEncryptor encryptor, String customResolverBeanName, boolean isCustom, BeanFactory bf, Environment environment) {
    singleton = new Singleton<>(() ->
            Optional.of(customResolverBeanName)
                    .filter(bf::containsBean)
                    .map(name -> (EncryptablePropertyResolver) bf.getBean(name))
                    .map(tap(bean -> log.info("Found Custom Resolver Bean {} with name: {}", bean, customResolverBeanName)))
                    .orElseGet(() -> {
                        if (isCustom) {
                            throw new IllegalStateException(String.format("Property Resolver custom Bean not found with name '%s'", customResolverBeanName));
                        }
                        log.info("Property Resolver custom Bean not found with name '{}'. Initializing Default Property Resolver", customResolverBeanName);
                        return createDefault(propertyDetector, encryptor, environment);
                    }));
}
 
Example #16
Source Project: sakai   Author: sakaiproject   File: MessageBundleTestConfiguration.java    License: Educational Community License v2.0 5 votes vote down vote up
@Bean
public Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty(org.hibernate.cfg.Environment.DIALECT, environment.getProperty(org.hibernate.cfg.Environment.DIALECT, HSQLDialect.class.getName()));
            setProperty(org.hibernate.cfg.Environment.HBM2DDL_AUTO, environment.getProperty(org.hibernate.cfg.Environment.HBM2DDL_AUTO));
            setProperty(org.hibernate.cfg.Environment.ENABLE_LAZY_LOAD_NO_TRANS, environment.getProperty(org.hibernate.cfg.Environment.ENABLE_LAZY_LOAD_NO_TRANS, "true"));
        }
    };
}
 
Example #17
Source Project: spring-cloud-config   Author: spring-cloud   File: ConfigClientProperties.java    License: Apache License 2.0 5 votes vote down vote up
public ConfigClientProperties(Environment environment) {
	String[] profiles = environment.getActiveProfiles();
	if (profiles.length == 0) {
		profiles = environment.getDefaultProfiles();
	}
	this.setProfile(StringUtils.arrayToCommaDelimitedString(profiles));
}
 
Example #18
Source Project: spring-cloud-consul   Author: spring-cloud   File: ConsulAutoRegistration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param properties consul discovery properties
 * @param env Spring environment
 * @return the app name, currently the spring.application.name property
 */
public static String getAppName(ConsulDiscoveryProperties properties,
		Environment env) {
	final String appName = properties.getServiceName();
	if (StringUtils.hasText(appName)) {
		return appName;
	}
	return env.getProperty("spring.application.name", "application");
}
 
Example #19
Source Project: blade-tool   Author: chillzhuang   File: StartEventListener.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Async
@Order
@EventListener(WebServerInitializedEvent.class)
public void afterStart(WebServerInitializedEvent event) {
	Environment environment = event.getApplicationContext().getEnvironment();
	String appName = environment.getProperty("spring.application.name").toUpperCase();
	int localPort = event.getWebServer().getPort();
	String profile = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
	log.info("---[{}]---启动完成,当前使用的端口:[{}],环境变量:[{}]---", appName, localPort, profile);
}
 
Example #20
Source Project: spring-cloud-commons   Author: spring-cloud   File: EnableDiscoveryClientImportSelector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	String[] imports = super.selectImports(metadata);

	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));

	boolean autoRegister = attributes.getBoolean("autoRegister");

	if (autoRegister) {
		List<String> importsList = new ArrayList<>(Arrays.asList(imports));
		importsList.add(
				"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");
		imports = importsList.toArray(new String[0]);
	}
	else {
		Environment env = getEnvironment();
		if (ConfigurableEnvironment.class.isInstance(env)) {
			ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
			LinkedHashMap<String, Object> map = new LinkedHashMap<>();
			map.put("spring.cloud.service-registry.auto-registration.enabled", false);
			MapPropertySource propertySource = new MapPropertySource(
					"springCloudDiscoveryClient", map);
			configEnv.getPropertySources().addLast(propertySource);
		}

	}

	return imports;
}
 
Example #21
Source Project: genie   Author: Netflix   File: AwsAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Provide a lazy {@link S3ClientFactory} instance if one is needed by the system.
 *
 * @param awsCredentialsProvider The {@link AWSCredentialsProvider} to use
 * @param awsRegionProvider      The {@link AwsRegionProvider} to use
 * @param environment            The Spring application {@link Environment} to bind properties from
 * @return A {@link S3ClientFactory} instance
 */
@Bean
@ConditionalOnMissingBean(S3ClientFactory.class)
public S3ClientFactory s3ClientFactory(
    final AWSCredentialsProvider awsCredentialsProvider,
    final AwsRegionProvider awsRegionProvider,
    final Environment environment
) {
    return new S3ClientFactory(awsCredentialsProvider, awsRegionProvider, environment);
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: AnnotatedBeanDefinitionReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the Environment from the given registry if possible, otherwise return a new
 * StandardEnvironment.
 */
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry instanceof EnvironmentCapable) {
		return ((EnvironmentCapable) registry).getEnvironment();
	}
	return new StandardEnvironment();
}
 
Example #23
Source Project: java-cfenv   Author: pivotal-cf   File: CredHubCfEnvProcessorTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void simpleService() {
	mockVcapServices(readTestDataFile("test-credhub-service.json"));

	Environment environment = getEnvironment();

	assertThat(environment.getProperty("some.external.service.password")).isEqualTo("p4ssw0rd");
}
 
Example #24
Source Project: cloudbreak   Author: hortonworks   File: DefaultRootVolumeSizeProvider.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultRootVolumeSizeProvider(CloudPlatformConnectors cloudPlatformConnectors, Environment environment) {
    PlatformVariants platformVariants = cloudPlatformConnectors.getPlatformVariants();
    platformVolumeSizeMap = Collections.unmodifiableMap(
            platformVariants.getDefaultVariants().keySet()
            .stream()
            .collect(Collectors.toMap(StringType::value, p -> initPlatform(environment, p)))
    );
}
 
Example #25
Source Project: spring-analysis-note   Author: Vip-Augus   File: ConfigurationClassParser.java    License: MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
Example #26
Source Project: spring-cloud-function   Author: spring-cloud   File: FunctionExporterAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RequestBuilder simpleRequestBuilder(Environment environment) {
	SimpleRequestBuilder builder = new SimpleRequestBuilder(environment);
	if (this.props.getSink().getUrl() != null) {
		builder.setTemplateUrl(this.props.getSink().getUrl());
	}
	builder.setHeaders(this.props.getSink().getHeaders());
	return builder;
}
 
Example #27
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 #28
Source Project: apollo   Author: ctripcorp   File: AutoUpdateConfigChangeListener.java    License: Apache License 2.0 5 votes vote down vote up
public AutoUpdateConfigChangeListener(Environment environment, ConfigurableListableBeanFactory beanFactory){
  this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter();
  this.beanFactory = beanFactory;
  this.typeConverter = this.beanFactory.getTypeConverter();
  this.environment = environment;
  this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
  this.springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
  this.gson = new Gson();
}
 
Example #29
Source Project: spring-boot-data-geode   Author: spring-projects   File: AbstractCacheDataImporterExporterUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
private Environment configureExport(Environment mockEnvironment, boolean enabled) {

		doReturn(enabled).when(mockEnvironment)
			.getProperty(eq(AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME),
				eq(Boolean.class), eq(AbstractCacheDataImporterExporter.DEFAULT_CACHE_DATA_EXPORT_ENABLED));

		return mockEnvironment;
	}
 
Example #30
Source Project: alchemy   Author: binglind   File: AlchemyApp.java    License: Apache License 2.0 5 votes vote down vote up
private static void logApplicationStartup(Environment env) {
    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
        protocol = "https";
    }
    String serverPort = env.getProperty("server.port");
    String contextPath = env.getProperty("server.servlet.context-path");
    if (StringUtils.isBlank(contextPath)) {
        contextPath = "/";
    }
    String hostAddress = "localhost";
    try {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.warn("The host name could not be determined, using `localhost` as fallback");
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\t{}://localhost:{}{}\n\t" +
            "External: \t{}://{}:{}{}\n\t" +
            "Profile(s): \t{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        protocol,
        serverPort,
        contextPath,
        protocol,
        hostAddress,
        serverPort,
        contextPath,
        env.getActiveProfiles());
}