com.netflix.config.ConfigurationManager Java Examples

The following examples show how to use com.netflix.config.ConfigurationManager. 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: TwitchKrakenBuilder.java    From twitch4j with MIT License 7 votes vote down vote up
/**
 * Twitch API Client (Kraken)
 *
 * @return TwitchKraken
 */
public TwitchKraken build() {
    log.debug("Kraken: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Build
    TwitchKraken client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder())
        .decoder(new JacksonDecoder())
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchKrakenErrorDecoder(new JacksonDecoder()))
        .requestInterceptor(new TwitchClientIdInterceptor(this.clientId, this.userAgent))
        .options(new Request.Options(timeout / 3, TimeUnit.MILLISECONDS, timeout, TimeUnit.MILLISECONDS, true))
        .retryer(new Retryer.Default(500, timeout, 2))
        .target(TwitchKraken.class, baseUrl);

    return client;
}
 
Example #2
Source File: TwitchMessagingInterfaceBuilder.java    From twitch4j with MIT License 7 votes vote down vote up
/**
 * Twitch API Client (Helix)
 *
 * @return TwitchHelix
 */
public TwitchMessagingInterface build() {
    log.debug("TMI: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Build
    TwitchMessagingInterface client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder())
        .decoder(new JacksonDecoder())
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchMessagingInterfaceErrorDecoder(new JacksonDecoder()))
        .logLevel(Logger.Level.BASIC)
        .requestInterceptor(new TwitchClientIdInterceptor(this.clientId, this.userAgent))
        .retryer(new Retryer.Default(1, 10000, 3))
        .options(new Request.Options(5000, TimeUnit.MILLISECONDS, 15000, TimeUnit.MILLISECONDS, true))
        .target(TwitchMessagingInterface.class, baseUrl);

    return client;
}
 
Example #3
Source File: DiscoveryEnabledLoadBalancerSupportsPortOverrideTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecureVipPortCanBeOverriden() throws Exception{

    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.DeploymentContextBasedVipAddresses", "secureDummy");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.IsSecure", "true");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.SecurePort", "6002");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.TargetRegion", "region");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName());
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.ForceClientPortConfiguration", "true");

    DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList();

    DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance();
    clientConfig.loadProperties("DiscoveryEnabled.testSecureVipPortCanBeOverriden");
    deList.initWithNiwsConfig(clientConfig);

    List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers();

    Assert.assertEquals(1, serverList.size());
    Assert.assertEquals(8002, serverList.get(0).getPort());                           // vip indicated
    Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort());         // vip indicated
    Assert.assertEquals(6002, serverList.get(0).getInstanceInfo().getSecurePort());   // client property indicated
}
 
Example #4
Source File: DiscoveryEnabledServerListTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testDynamicServers() {
    ConfigurationManager.getConfigInstance().setProperty("MyService.ribbon." + Keys.DeploymentContextBasedVipAddresses, getVipAddress());
    ConfigurationManager.getConfigInstance().setProperty("MyService.ribbon." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("MyService")
            .withClientOptions(ClientOptions.create()
                    .withMaxAutoRetriesNextServer(3)
                    .withReadTimeout(300000)).build();
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class)
            .withUriTemplate("/")
            .withMethod("GET").build();
    RibbonRequest<ByteBuf> request = template
            .requestBuilder().build();
    String result = request.execute().toString(Charset.defaultCharset());
    assertEquals("Hello world", result);
}
 
Example #5
Source File: EurekaStore.java    From qconfig with MIT License 6 votes vote down vote up
/**
 * Users can override to initialize the environment themselves.
 */
protected void initEurekaEnvironment() throws Exception {
    logger.info("Setting the eureka configuration..");

    String dataCenter = ConfigurationManager.getConfigInstance().getString(EUREKA_DATACENTER);
    if (dataCenter == null) {
        logger.info("Eureka data center value eureka.datacenter is not set, defaulting to default");
        ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, DEFAULT);
    } else {
        ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter);
    }
    String environment = ConfigurationManager.getConfigInstance().getString(EUREKA_ENVIRONMENT);
    if (environment == null) {
        ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST);
        logger.info("Eureka environment value eureka.environment is not set, defaulting to test");
    }
}
 
Example #6
Source File: InitializeServletListener.java    From s2g-zuul with MIT License 6 votes vote down vote up
private void loadConfiguration() {
	appName = ConfigurationManager.getDeploymentContext().getApplicationId();

	// Loading properties via archaius.
	if (null != appName) {
		try {
			LOGGER.info(String.format("Loading application properties with app id: %s and environment: %s", appName,
					ConfigurationManager.getDeploymentContext().getDeploymentEnvironment()));
			ConfigurationManager.loadCascadedPropertiesFromResources(appName);
		} catch (IOException e) {
			LOGGER.error(String.format(
					"Failed to load properties for application id: %s and environment: %s. This is ok, if you do not have application level properties.",
					appName, ConfigurationManager.getDeploymentContext().getDeploymentEnvironment()), e);
		}
	} else {
		LOGGER.warn(
				"Application identifier not defined, skipping application level properties loading. You must set a property 'archaius.deployment.applicationId' to be able to load application level properties.");
	}

}
 
Example #7
Source File: InitializeServletListener.java    From s2g-zuul with MIT License 6 votes vote down vote up
public InitializeServletListener() {
//		System.setProperty(Constants.DEPLOY_ENVIRONMENT, "test");
//		System.setProperty(Constants.DEPLOYMENT_APPLICATION_ID, "mobile_zuul");
//		System.setProperty(Constants.DEPLOY_CONFIG_URL, "http://localhost:8080/configfiles/mobile_zuul/default/application");			
		String applicationID = ConfigurationManager.getConfigInstance().getString(Constants.DEPLOYMENT_APPLICATION_ID);
		if (StringUtils.isEmpty(applicationID)) {
			LOGGER.warn("Using default config!");
			ConfigurationManager.getConfigInstance().setProperty(Constants.DEPLOYMENT_APPLICATION_ID, "mobile_zuul");
		}
		
		System.setProperty(DynamicPropertyFactory.ENABLE_JMX, "true");
		
        loadConfiguration();
        configLog();
        registerEureka();
	}
 
Example #8
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSunnyDayNoClientAuth() throws Exception{

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = "GetPostSecureTest" + ".testSunnyDayNoClientAuth";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS2.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

	RestClient rc = (RestClient) ClientFactory.getNamedClient(name);

	testServer2.accept();

	URI getUri = new URI(SERVICE_URI2 + "test/");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	HttpResponse response = rc.execute(request);
	assertEquals(200, response.getStatus());
}
 
Example #9
Source File: EdgeServer.java    From recipes-rss with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
	System.setProperty("archaius.deployment.applicationId", "edge");
	System.setProperty(PropertyNames.SERVER_BOOTSTRAP_BASE_PACKAGES_OVERRIDE, "com.netflix");

	String appId = ConfigurationManager.getDeploymentContext().getApplicationId();
	String env = ConfigurationManager.getDeploymentContext().getDeploymentEnvironment();
	
	// populate the eureka-specific properties
	System.setProperty("eureka.client.props", appId);
	if (env != null) {
		System.setProperty("eureka.environment", env);
	}

	EdgeServer edgeServer = new EdgeServer();
	edgeServer.start();
}
 
Example #10
Source File: EurekaResource.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getEurekaStatus() {

        Map<String, Object> stats = new HashMap<>();
        stats.put("time", new Date());
        stats.put("currentTime", StatusResource.getCurrentTimeAsString());
        stats.put("upTime", StatusInfo.getUpTime());
        stats.put("environment", ConfigurationManager.getDeploymentContext()
            .getDeploymentEnvironment());
        stats.put("datacenter", ConfigurationManager.getDeploymentContext()
            .getDeploymentDatacenter());

        PeerAwareInstanceRegistry registry = getRegistry();

        stats.put("isBelowRenewThreshold", registry.isBelowRenewThresold() == 1);

        populateInstanceInfo(stats);

        return stats;
    }
 
Example #11
Source File: DiscoveryEnabledLoadBalancerSupportsPortOverrideTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultHonorsVipSecurePortDefinition() throws Exception{

    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.DeploymentContextBasedVipAddresses", "secureDummy");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.IsSecure", "true");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.SecurePort", "6002");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.TargetRegion", "region");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName());



    DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList();

    DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance();
    clientConfig.loadProperties("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition");
    deList.initWithNiwsConfig(clientConfig);

    List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers();

    Assert.assertEquals(1, serverList.size());
    Assert.assertEquals(8002, serverList.get(0).getPort());                         // vip indicated
    Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort());       // vip indicated
    Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default
}
 
Example #12
Source File: AdminPageRegistry.java    From karyon with Apache License 2.0 6 votes vote down vote up
public List<Class<? extends Annotation>> getAdminPageAnnotations() {
    final String adminPageAnnotationClasses = ConfigurationManager.getConfigInstance().getString(PROP_ID_ADMIN_PAGE_ANNOTATION, DEFAULT_ADMIN_PAGE_ANNOTATION);
    String[] clsNameList = adminPageAnnotationClasses.split(";");
    List<Class<? extends Annotation>> clsList = new ArrayList<>(clsNameList.length);
    for (String clsName : clsNameList) {
        try {
            final Class<?> aClass = Class.forName(clsName);
            if (aClass.isAnnotation()) {
                clsList.add(aClass.asSubclass(Annotation.class));
            }
        } catch (ClassNotFoundException e) {
            LOG.warn("Invalid AdminPage Annotation class - " + clsName);
        }
    }
    return clsList;
}
 
Example #13
Source File: EurekaResource.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getEurekaStatus() {

        Map<String, Object> stats = new HashMap<>();
        stats.put("time", new Date());
        stats.put("currentTime", StatusResource.getCurrentTimeAsString());
        stats.put("upTime", StatusInfo.getUpTime());
        stats.put("environment", ConfigurationManager.getDeploymentContext()
            .getDeploymentEnvironment());
        stats.put("datacenter", ConfigurationManager.getDeploymentContext()
            .getDeploymentDatacenter());

        PeerAwareInstanceRegistry registry = getRegistry();

        stats.put("isBelowRenewThreshold", registry.isBelowRenewThresold() == 1);

        populateInstanceInfo(stats);

        return stats;
    }
 
Example #14
Source File: ChassisConfigTestConfiguration.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Bean
static public PropertyPlaceholderConfigurer archaiusPropertyPlaceholderConfigurer() throws IOException, ConfigurationException {
	
    ConfigurationManager.loadPropertiesFromResources("chassis-test.properties");
    ConfigurationManager.loadPropertiesFromResources("chassis-default.properties");
    
    // force disable eureka
    ConfigurationManager.getConfigInstance().setProperty("chassis.eureka.disable", true);
    
    return new PropertyPlaceholderConfigurer() {
        @Override
        protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
            return DynamicPropertyFactory.getInstance().getStringProperty(placeholder, "null").get();
        }
    };
}
 
Example #15
Source File: InMemoryPlaintextSecretDerivedTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecretIsDecryptedBeforeBeingPassedToDecoder() {
    String secretValue = "test_secret_value";
    long version = 1;
    RawSecretEntry rawSecret = new RawSecretEntry(secretIdentifier,
            version,
            State.ENABLED,
            Optional.empty(),
            Optional.empty(),
            new SecretValue(secretValue, SecretType.OPAQUE).asByteArray());
    SecretEntry secretEntry = new SecretEntryMock.Builder().secretValue(secretValue).build();
    when(mockSecretsGroup.decrypt(rawSecret, secretIdentifier, version)).thenReturn(secretEntry);

    InMemoryPlaintextSecretDerived<Integer> p = new InMemoryPlaintextSecretDerived<>(mockSecretsGroup,
            secretIdentifier,
            String::length);
    ConfigurationManager.getConfigInstance().setProperty(secretIdentifier.name, rawSecret.toJsonBlob());
    assertEquals(p.getValue().intValue(), secretValue.length());
}
 
Example #16
Source File: RestClientTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecureClient2()  throws Exception {
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.IsSecure, "true");
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStore, secureServer.getTrustStore().getAbsolutePath());
    ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD);
    
    RestClient client = (RestClient) ClientFactory.getNamedClient("test3");
    BaseLoadBalancer lb = new BaseLoadBalancer();
    Server[] servers = new Server[]{new Server("localhost", secureServer.getServerPort())}; 
    lb.addServers(Arrays.asList(servers));
    client.setLoadBalancer(lb);
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
    assertEquals(secureServer.getServerPath("/"), response.getRequestedURI().toString());
    
}
 
Example #17
Source File: ChassisHystrixTestConfiguration.java    From chassis with Apache License 2.0 6 votes vote down vote up
@Bean
static public PropertyPlaceholderConfigurer archaiusPropertyPlaceholderConfigurer() throws IOException, ConfigurationException {

    ConfigurationManager.loadPropertiesFromResources("chassis-test.properties");
    ConfigurationManager.loadPropertiesFromResources("chassis-default.properties");

    // force disable eureka
    ConfigurationManager.getConfigInstance().setProperty("chassis.eureka.disable", true);

    return new PropertyPlaceholderConfigurer() {
        @Override
        protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
            return DynamicPropertyFactory.getInstance().getStringProperty(placeholder, "null").get();
        }
    };
}
 
Example #18
Source File: HealthCheckResourceTest.java    From karyon with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    final AbstractConfiguration configInst = ConfigurationManager.getConfigInstance();
    configInst.clearProperty(AdminConfigImpl.CONTAINER_LISTEN_PORT);
    if (container != null) {
        container.shutdown();
    }
}
 
Example #19
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testVipAsURI()  throws Exception {
	ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.DeploymentContextBasedVipAddresses", server.getServerPath("/"));
	ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.InitializeNFLoadBalancer", "false");
    RestClient client = (RestClient) ClientFactory.getNamedClient("test1");
    assertNull(client.getLoadBalancer());
    HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
    assertEquals(server.getServerPath("/"), response.getRequestedURI().toString());
}
 
Example #20
Source File: MetricsCloudWatchConfigurationTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.APP_NAME_PROPERTY_NAME), "test");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.APP_VERSION_PROPERTY_NAME), "test");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.APP_ENVIRONMENT_PROPERTY_NAME), "test");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.METRICS_AWS_FILTER_PROPERTY_NAME), "foo=bar");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.METRICS_AWS_PUBLISH_INTERVAL_PROPERTY_NAME), "1");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.METRICS_AWS_PUBLISH_INTERVAL_UNIT_PROPERTY_NAME), "MINUTES");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.METRICS_AWS_REGION_PROPERTY_NAME), "default");
    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchConfiguration.METRICS_AWS_ENABLED_PROPERTY_NAME), "true");
}
 
Example #21
Source File: MetricsCloudWatchConfigurationTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatePublishInterval() {
    int originalInterval = metricsCloudWatchConfiguration.getReporter().getPublishInterval();
    int newInterval = originalInterval + 1;

    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsCloudWatchReporter.METRICS_AWS_PUBLISH_INTERVAL_PROPERTY_NAME), newInterval + "");

    Assert.assertEquals(newInterval, metricsCloudWatchConfiguration.getReporter().getPublishInterval());
}
 
Example #22
Source File: PaasModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    LOG.info("Loading PaasModule");
    
    bind(EventBus.class).toInstance(eventBus);
    bindListener(Matchers.any(), new TypeListener() {
        public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
            typeEncounter.register(new InjectionListener<I>() {
                public void afterInjection(I i) {
                    eventBus.register(i);
                }
            });
        }
    });

    bind(TaskManager.class).to(InlineTaskManager.class);

    // Constants
    bind(String.class).annotatedWith(Names.named("namespace")).toInstance("com.netflix.pass.");
    bind(String.class).annotatedWith(Names.named("appname"  )).toInstance("paas");
    
    bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance());

    // Configuration
    bind(PaasConfiguration.class).to(ArchaeusPaasConfiguration.class).in(Scopes.SINGLETON);
    
    // Stuff
    bind(ScheduledExecutorService.class).annotatedWith(Names.named("tasks")).toInstance(Executors.newScheduledThreadPool(10));
    
    bind(DaoProvider.class).in(Scopes.SINGLETON);
    
    // Rest resources
    bind(DataResource.class).in(Scopes.SINGLETON);
    bind(SchemaAdminResource.class).to(JerseySchemaAdminResourceImpl.class).in(Scopes.SINGLETON);
    bind(SchemaService.class).to(DaoSchemaService.class).in(Scopes.SINGLETON);
    
}
 
Example #23
Source File: DefaultClientConfigImplTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypedValue() {
    ConfigurationManager.getConfigInstance().setProperty("myclient.ribbon." + CommonClientConfigKey.ConnectTimeout, "1500");
    DefaultClientConfigImpl config = new DefaultClientConfigImpl();
    config.loadProperties("myclient");
    assertEquals(1500, config.get(CommonClientConfigKey.ConnectTimeout).intValue());
    config.set(CommonClientConfigKey.ConnectTimeout, 2000);
    // The archaius property should override code override
    assertEquals(1500, config.get(CommonClientConfigKey.ConnectTimeout).intValue());
}
 
Example #24
Source File: DiscoveryEnabledLoadBalancerSupportsUseIpAddrTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
/**
 * Generic method to help with various tests
 * @param globalspecified if false, will clear property DiscoveryEnabledNIWSServerList.useIpAddr
 * @param global value of DiscoveryEnabledNIWSServerList.useIpAddr
 * @param clientspecified if false, will not set property on client config
 * @param client value of client.namespace.ribbon.UseIPAddrForServer
 */
private List<Server> testUsesIpAddr(boolean globalSpecified, boolean global, boolean clientSpecified, boolean client) throws Exception{
	if (globalSpecified) {
        ConfigurationManager.getConfigInstance().setProperty("ribbon.UseIPAddrForServer", global);
	}
	else {
		ConfigurationManager.getConfigInstance().clearProperty("ribbon.UseIPAddrForServer");
	}
	if (clientSpecified) {
		ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer", client);
	}
	else {
		ConfigurationManager.getConfigInstance().clearProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer");
	}
	System.out.println("r = " + ConfigurationManager.getConfigInstance().getProperty("ribbon.UseIPAddrForServer"));
	System.out.println("d = " + ConfigurationManager.getConfigInstance().getProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.UseIPAddrForServer"));
	
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName());
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.DeploymentContextBasedVipAddresses", "dummy");
    ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testUsesIpAddr.ribbon.TargetRegion", "region");
    
    DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList("TESTVIP:8080");

    DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance();
    clientConfig.loadProperties("DiscoveryEnabled.testUsesIpAddr");
    deList.initWithNiwsConfig(clientConfig);

    List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers();

    Assert.assertEquals(2, serverList.size());
    List<Server> servers = new ArrayList<Server>();
    for (DiscoveryEnabledServer server : serverList) {
    	servers.add((Server)server);
    }
    return servers;
}
 
Example #25
Source File: PrimeConnectionsTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimeConnectionsLargePool() throws Exception {
	Configuration config = ConfigurationManager.getConfigInstance();
	config.setProperty("PrimeConnectionsTest2.ribbon.NFLoadBalancerClassName", 
			com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
	config.setProperty("PrimeConnectionsTest2.ribbon.NIWSServerListClassName", LargeFixedServerList.class.getName());
	config.setProperty("PrimeConnectionsTest2.ribbon.EnablePrimeConnections", "true");
	DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest2");
	PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats();
	assertEquals(stats.success, LARGE_FIXED_SERVER_LIST_SIZE);
}
 
Example #26
Source File: RestClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecureClient()  throws Exception {
	ConfigurationManager.getConfigInstance().setProperty("test2.ribbon.IsSecure", "true");
	RestClient client = (RestClient) ClientFactory.getNamedClient("test2");
    HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
    HttpResponse response = client.executeWithLoadBalancer(request);
    assertStatusIsOk(response.getStatus());
}
 
Example #27
Source File: SwaggerDocDiscovery.java    From sc-generator with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getServices() {
    List<String> services = new ArrayList<>();
    for (Document document : documentDao.findAll()) {
        services.add("" + document.getId());
        String host = getHost(document);
        ConfigurationManager.getConfigInstance()
                .addProperty(document.getId() + ".ribbon.listOfServers", host);
    }

    return services;
}
 
Example #28
Source File: ClientConfigTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testNiwsConfigViaProperties() throws Exception {
	DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl();
	DefaultClientConfigImpl override = new DefaultClientConfigImpl();
	clientConfig.loadDefaultValues();
    Properties props = new Properties();
    
    final String restClientName = "testRestClient";
    
    props.setProperty("netflix.appinfo.stack","xbox");
    props.setProperty("netflix.environment","test");
    props.setProperty("appname", "movieservice");
    props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.AppName.key(), "movieservice");
    props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.DeploymentContextBasedVipAddresses.key(), "${appname}-${netflix.appinfo.stack}-${netflix.environment},movieservice--${netflix.environment}");
    props.setProperty(restClientName + ".ribbon." + CommonClientConfigKey.EnableZoneAffinity.key(), "false");

    ConfigurationManager.loadProperties(props);
    ConfigurationManager.getConfigInstance().setProperty("testRestClient.ribbon.customProperty", "abc");
    
    clientConfig.loadProperties(restClientName);
    clientConfig.set(CommonClientConfigKey.ConnectTimeout, 1000);
    override.set(CommonClientConfigKey.Port, 8000);
    override.set(CommonClientConfigKey.ConnectTimeout, 5000);
    clientConfig.applyOverride(override);
    
    Assert.assertEquals("movieservice", clientConfig.get(CommonClientConfigKey.AppName));
    Assert.assertEquals(false, clientConfig.get(CommonClientConfigKey.EnableZoneAffinity));
    Assert.assertEquals("movieservice-xbox-test,movieservice--test", clientConfig.resolveDeploymentContextbasedVipAddresses());
    Assert.assertEquals(5000, clientConfig.get(CommonClientConfigKey.ConnectTimeout).longValue());

    Assert.assertEquals(8000, clientConfig.get(CommonClientConfigKey.Port).longValue());
    System.out.println("AutoVipAddress:" + clientConfig.resolveDeploymentContextbasedVipAddresses());
    
    ConfigurationManager.getConfigInstance().setProperty("testRestClient.ribbon.EnableZoneAffinity", "true");
    assertEquals(true, clientConfig.get(CommonClientConfigKey.EnableZoneAffinity));
}
 
Example #29
Source File: ConsulController.java    From james with Apache License 2.0 5 votes vote down vote up
private void setupConsulWatcher(ConsulControllerConfiguration configuration,
                                InformationPointService informationPointService) {
    ConsulClient client = new ConsulClient(configuration.getHost(), configuration.getPort());
    ConsulWatchedConfigurationSource configurationSource =
            new ConsulWatchedConfigurationSource(configuration.getFolderPath(), client);
    DynamicWatchedConfiguration dynamicConfig = new DynamicWatchedConfiguration(configurationSource);

    dynamicConfig.addConfigurationListener(event -> {
        if (!event.isBeforeUpdate()) {
            switch (event.getType()) {
                case AbstractConfiguration.EVENT_ADD_PROPERTY:
                    onInformationPointAdded(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_SET_PROPERTY:
                    onInformationPointModified(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_CLEAR_PROPERTY:
                    onInformationPointRemoved(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_CLEAR:
                    onInformationPointsCleared(informationPointService);
                    break;
                default:
                    LOG.debug(() -> "Unsupported event type: " + event.getType());
            }
        }
    });
    configurationSource.startAsync();

    ConcurrentCompositeConfiguration compositeConfig = new ConcurrentCompositeConfiguration();
    compositeConfig.addConfiguration(dynamicConfig, "consul-dynamic");
    ConfigurationManager.install(compositeConfig);
}
 
Example #30
Source File: EtcdRibbonClientConfiguration.java    From spring-cloud-etcd with Apache License 2.0 5 votes vote down vote up
protected void setProp(String serviceId, String suffix, String value) {
	// how to set the namespace properly?
	String key = getKey(serviceId, suffix);
	DynamicStringProperty property = getProperty(key);
	if (property.get().equals(VALUE_NOT_SET)) {
		ConfigurationManager.getConfigInstance().setProperty(key, value);
	}
}