Java Code Examples for com.netflix.config.ConfigurationManager

The following examples show how to use com.netflix.config.ConfigurationManager. 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: twitch4j   Source File: TwitchMessagingInterfaceBuilder.java    License: 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 2
Source Project: twitch4j   Source File: TwitchKrakenBuilder.java    License: 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 3
Source Project: flair-registry   Source File: EurekaResource.java    License: 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 4
Source Project: ribbon   Source File: DiscoveryEnabledServerListTest.java    License: 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 Project: qconfig   Source File: EurekaStore.java    License: 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 Project: s2g-zuul   Source File: InitializeServletListener.java    License: 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 7
Source Project: s2g-zuul   Source File: InitializeServletListener.java    License: 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 8
Source Project: recipes-rss   Source File: EdgeServer.java    License: 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 9
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 10
@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 11
Source Project: karyon   Source File: AdminPageRegistry.java    License: 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 12
Source Project: ribbon   Source File: SecureGetTest.java    License: 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 13
Source Project: chassis   Source File: ChassisConfigTestConfiguration.java    License: 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 14
@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 15
Source Project: ribbon   Source File: RestClientTest.java    License: 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 16
Source Project: chassis   Source File: ChassisHystrixTestConfiguration.java    License: 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 17
@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 18
Source Project: staash   Source File: ArchaeusPassConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    @Ignore
    public void test() throws Exception {
        MyConfig config = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class);
        
        System.out.println("----- BEFORE -----");
        printContents(config);
        
        ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.string",  "NewA");
        ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.int",     "321");
        ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.boolean", "false");
        ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.long",    "654");
        ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.double",  "2.1");
        ConfigurationManager.getConfigInstance().setProperty("test.property.static.string",  "NewA");
        ConfigurationManager.getConfigInstance().setProperty("test.property.static.int",     "321");
        ConfigurationManager.getConfigInstance().setProperty("test.property.static.boolean", "false");
        ConfigurationManager.getConfigInstance().setProperty("test.property.static.long",    "654");
        ConfigurationManager.getConfigInstance().setProperty("test.property.static.double",  "2.1");
        
        System.out.println("----- AFTER -----");
        printContents(config);
        
//        Supplier<String> supplier = config.getDynamicStringSupplier();
//        System.out.println("Supplier value : " + supplier.get());
        
        int count = 1000000;
        
        MyConfig configDynamicProxy = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class);
        MyConfig configJavaAssixt   = new JavaAssistArchaeusConfigurationFactory().get(MyConfig.class);
        MyConfig configCglib        = new CglibArchaeusConfigurationFactory().get(MyConfig.class);
        
        for (int i = 0; i < 10; i++) {
            System.out.println("==== Run " + i + " ====");
            timeConfig(configDynamicProxy,  "Dynamic Proxy", count);
            timeConfig(configJavaAssixt,    "Java Assist  ", count);
            timeConfig(configCglib,         "CGLIB        ", count);
        }
    }
 
Example 19
Source Project: ribbon   Source File: ClientConfigTest.java    License: 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 20
Source Project: s2g-zuul   Source File: InitializeServletListener.java    License: MIT License 5 votes vote down vote up
private void registerEureka() {
	DynamicBooleanProperty eurekaEnabled = DynamicPropertyFactory.getInstance().getBooleanProperty("eureka.enabled",
			true);
	if (!eurekaEnabled.get())
		return;

	EurekaInstanceConfig eurekaInstanceConfig = new PropertiesInstanceConfig() {
	};
       ConfigurationManager.getConfigInstance().setProperty("eureka.statusPageUrl","http://"+ getTurbineInstance());

	DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, new DefaultEurekaClientConfig());

	final DynamicStringProperty serverStatus = DynamicPropertyFactory.getInstance()
			.getStringProperty("server." + IPUtil.getLocalIP() + ".status", "up");
	DiscoveryManager.getInstance().getDiscoveryClient().registerHealthCheckCallback(new HealthCheckCallback() {
		@Override
		public boolean isHealthy() {
			return serverStatus.get().toLowerCase().equals("up");
		}
	});

	String version = String.valueOf(System.currentTimeMillis());
	String group = ConfigurationManager.getConfigInstance().getString("server.group", "default");
	String dataCenter = ConfigurationManager.getConfigInstance().getString("server.data-center", "default");

	Map<String, String> metadata = new HashMap<String, String>();
	metadata.put("version", version);
	metadata.put("group", group);
	metadata.put("dataCenter", dataCenter);

	String turbineInstance = getTurbineInstance();
	if (turbineInstance != null) {
		metadata.put("turbine.instance", turbineInstance);
	}

	ApplicationInfoManager.getInstance().registerAppMetadata(metadata);
}
 
Example 21
Source Project: s2g-zuul   Source File: InitializeServletListener.java    License: MIT License 5 votes vote down vote up
public String getTurbineInstance() {
	String instance = null;
	String ip = IPUtil.getLocalIP();
	if (ip != null) {
		instance = ip + ":" + ConfigurationManager.getConfigInstance().getString("server.internals.port", "8077");
	} else {
		LOGGER.warn("Can't build turbine instance as can't fetch the ip.");
	}
	return instance;
}
 
Example 22
Source Project: s2g-zuul   Source File: RestClient.java    License: MIT License 5 votes vote down vote up
public static URL getResource(String resourceName)
{
    URL url = null;
    // attempt to load from the context classpath
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
        url = loader.getResource(resourceName);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ClassLoader.getSystemResource(resourceName);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ConfigurationManager.class.getResource(resourceName);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ConfigurationManager.class.getClassLoader().getResource(resourceName);
    }
    if (url == null) {
        try {
            resourceName = URLDecoder.decode(resourceName, "UTF-8");
            url = (new File(resourceName)).toURI().toURL();
        } catch (Exception e) {
        	logger.error("Problem loading resource", e);
        }
    }
    return url;
}
 
Example 23
Source Project: s2g-zuul   Source File: PropsServlet.java    License: MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Map<String, String> allPropsAsString = new TreeMap<String, String>();
    AbstractConfiguration config = ConfigurationManager.getConfigInstance();
    Iterator<String> keys = config.getKeys();

    while (keys.hasNext()) {
        final String key = keys.next();
        final Object value;
        value = config.getProperty(key);
        allPropsAsString.put(key, value.toString());
    }

    String jsonStr = JSON.toJSONString(allPropsAsString);
    		//mapper.writeValueAsString(allPropsAsString);

    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
    resp.setContentType("application/json; charset=UTF-8");

    PrintWriter writer = resp.getWriter();
    try{
        writer.write(jsonStr);
        resp.setStatus(Response.SC_OK);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
 
Example 24
Source Project: ribbon   Source File: ClientConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFallback_fallbackSet() {
    ConfigurationManager.getConfigInstance().setProperty(DEFAULT_INTEGER_PROPERTY.key(), "100");
    DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl();
    Property<Integer> prop = clientConfig.getGlobalProperty(INTEGER_PROPERTY.format(testName.getMethodName()))
            .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_INTEGER_PROPERTY));

    Assert.assertEquals(100, prop.getOrDefault().intValue());
}
 
Example 25
Source Project: zuul   Source File: ZuulSampleModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    try {
      ConfigurationManager.loadCascadedPropertiesFromResources("application");
    } catch (Exception ex) {
      throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex);
    }

    bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance());
    bind(DynamicCodeCompiler.class).to(GroovyCompiler.class);
    bind(FilenameFilter.class).to(GroovyFileFilter.class);

    install(new EurekaModule());

    // sample specific bindings
    bind(BaseServerStartup.class).to(SampleServerStartup.class);

    // use provided basic netty origin manager
    bind(OriginManager.class).to(BasicNettyOriginManager.class);

    // zuul filter loading
    install(new ZuulFiltersModule());
    bind(FilterLoader.class).to(DynamicFilterLoader.class);
    bind(FilterRegistry.class).to(MutableFilterRegistry.class);
    bind(FilterFileManager.class).asEagerSingleton();


    // general server bindings
    bind(ServerStatusManager.class); // health/discovery status
    bind(SessionContextDecorator.class).to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in
    bind(Registry.class).to(DefaultRegistry.class); // atlas metrics registry
    bind(RequestCompleteHandler.class).to(BasicRequestCompleteHandler.class); // metrics post-request completion
    bind(RequestMetricsPublisher.class).to(BasicRequestMetricsPublisher.class); // timings publisher

    // access logger, including request ID generator
    bind(AccessLogPublisher.class).toInstance(new AccessLogPublisher("ACCESS",
            (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel).getContext().getUUID()));
}
 
Example 26
Source Project: ribbon   Source File: NamedConnectionPoolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionPoolCounters() throws Exception {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    NFHttpClient client = NFHttpClientFactory.getNamedNFHttpClient("google-NamedConnectionPoolTest");
    assertTrue(client.getConnectionManager() instanceof MonitoredConnectionManager);
    MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) client.getConnectionManager();
    connectionPoolManager.setDefaultMaxPerRoute(100);
    connectionPoolManager.setMaxTotal(200);
    assertTrue(connectionPoolManager.getConnectionPool() instanceof NamedConnectionPool);
    NamedConnectionPool connectionPool = (NamedConnectionPool) connectionPoolManager.getConnectionPool();
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    for (int i = 0; i < 10; i++) {
        HttpUriRequest request = new HttpGet(server.getServerPath("/"));
        HttpResponse response = client.execute(request);
        EntityUtils.consume(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        assertTrue(statusCode == 200 || statusCode == 302);
        Thread.sleep(500);
    }
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    assertTrue(connectionPool.getCreatedEntryCount() >= 1);
    assertTrue(connectionPool.getRequestsCount() >= 10);
    assertTrue(connectionPool.getFreeEntryCount() >= 9);
    assertEquals(0, connectionPool.getDeleteCount());
    assertEquals(connectionPool.getReleaseCount(), connectionPool.getRequestsCount());
    assertEquals(connectionPool.getRequestsCount(), connectionPool.getCreatedEntryCount() + connectionPool.getFreeEntryCount());
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxTotalHttpConnections.key(), "50");
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), "10");
    assertEquals(50, connectionPoolManager.getMaxTotal());
    assertEquals(10, connectionPoolManager.getDefaultMaxPerRoute());
}
 
Example 27
Source Project: oneplatform   Source File: EurekaRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private void initEurekaClient(Properties properties) throws Exception{
	
	properties.setProperty("eureka.metadataMap.nodeId", NodeNameHolder.getNodeId());
	ConfigurationManager.loadProperties(properties);
	//ConfigurationManager.loadPropertiesFromResources("eureka.properties");
	
	//DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance();
	
	MyDataCenterInstanceConfig instanceConfig = new MyDataCenterInstanceConfig(){
		@Override
		public String getHostName(boolean refresh) {
			String hostName = super.getHostName(refresh);
			if(ResourceUtils.getBoolean("eureka.preferIpAddress")){
				hostName = IpUtils.getLocalIpAddr();
			}
			return hostName;
		}

		@Override
		public String getIpAddress() {
			return IpUtils.getLocalIpAddr();
		}
		
		
	};
	InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get();
       applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo);
       
       DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();

       eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig);
       
       instanceId = instanceInfo.getInstanceId();
}
 
Example 28
Source Project: eureka-consul-adapter   Source File: AgentController.java    License: MIT License 5 votes vote down vote up
@GetMapping(value = "/v1/agent/self", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Agent getNodes() {
    String dataCenter = ConfigurationManager.getConfigInstance().getString("archaius.deployment.datacenter");
    Config config = Config.builder().dataCenter(Optional.ofNullable(dataCenter).orElse("default")).build();
    return Agent.builder().config(config).build();
}
 
Example 29
Source Project: ribbon   Source File: ClientPropertiesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoExportToArchaius() {
    MyTransportFactory transportFactory = new MyTransportFactory(ClientConfigFactory.DEFAULT);
    RibbonResourceFactory resourceFactory = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, transportFactory);
    RibbonDynamicProxy.newInstance(MovieService.class, resourceFactory, ClientConfigFactory.DEFAULT, transportFactory);
    IClientConfig clientConfig = transportFactory.getClientConfig();
    assertEquals(1000, clientConfig.get(Keys.ConnectTimeout).longValue());
    assertEquals(3000, clientConfig.get(Keys.ReadTimeout).longValue());
    assertEquals(0, clientConfig.get(Keys.MaxAutoRetriesNextServer).longValue());

    Configuration config = ConfigurationManager.getConfigInstance();
    assertNull(config.getProperty("MovieService.ribbon.ReadTimeout"));
    config.setProperty("MovieService.ribbon.ReadTimeout", "5000");
    assertEquals(5000, clientConfig.get(Keys.ReadTimeout).longValue());
}
 
Example 30
Source Project: chassis   Source File: MetricsGraphiteConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatePublishIntervalUnit() {
    TimeUnit originalIntervalUnit = metricsGraphiteConfiguration.getReporterLoader().getPublishIntervalUnit();
    Assert.assertEquals(originalIntervalUnit, TimeUnit.MINUTES);

    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsGraphiteReporterLoader.METRICS_GRAPHITE_PUBLISH_INTERVAL_UNIT_PROPERTY_NAME), TimeUnit.SECONDS + "");

    Assert.assertEquals(TimeUnit.SECONDS, metricsGraphiteConfiguration.getReporterLoader().getPublishIntervalUnit());

    ConfigurationManager.getConfigInstance().setProperty(removePlaceholder(MetricsGraphiteReporterLoader.METRICS_GRAPHITE_PUBLISH_INTERVAL_UNIT_PROPERTY_NAME), TimeUnit.MINUTES + "");
}