Java Code Examples for com.netflix.config.ConfigurationManager#getConfigInstance()

The following examples show how to use com.netflix.config.ConfigurationManager#getConfigInstance() . 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: InitializeServletListener.java    From s2g-zuul with MIT License 6 votes vote down vote up
private void initZuul() throws Exception {
    LOGGER.info("Starting Groovy Filter file manager");
    final AbstractConfiguration config = ConfigurationManager.getConfigInstance();
    final String preFiltersPath = config.getString(Constants.ZUUL_FILTER_PRE_PATH);
    final String postFiltersPath = config.getString(Constants.ZUUL_FILTER_POST_PATH);
    final String routeFiltersPath = config.getString(Constants.ZUUL_FILTER_ROUTE_PATH);
    final String errorFiltersPath = config.getString(Constants.ZUUL_FILTER_ERROR_PATH);
    final String customPath = config.getString(Constants.Zuul_FILTER_CUSTOM_PATH);

    //load local filter files
    FilterLoader.getInstance().setCompiler(new GroovyCompiler());
    FilterFileManager.setFilenameFilter(new GroovyFileFilter());
    if (customPath == null) {
        FilterFileManager.init(5, preFiltersPath, postFiltersPath, routeFiltersPath, errorFiltersPath);
    } else {
        FilterFileManager.init(5, preFiltersPath, postFiltersPath, routeFiltersPath, errorFiltersPath, customPath);
    }
    //load filters in DB
    startZuulFilterPoller();
    LOGGER.info("Groovy Filter file manager started");
}
 
Example 2
Source File: TestConfigurationSpringInitializer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAll() {
  ConfigurationSpringInitializer configurationSpringInitializer = new ConfigurationSpringInitializer();
  ConfigUtil.installDynamicConfig();

  Object o = ConfigUtil.getProperty("zq");
  @SuppressWarnings("unchecked")
  List<Map<String, Object>> listO = (List<Map<String, Object>>) o;
  Assert.assertEquals(3, listO.size());
  Assert.assertNull(ConfigUtil.getProperty("notExist"));

  MicroserviceConfigLoader loader = ConfigUtil.getMicroserviceConfigLoader();
  Assert.assertNotNull(loader);

  Configuration instance = ConfigurationManager.getConfigInstance();
  ConfigUtil.installDynamicConfig();
  // must not reinstall
  Assert.assertEquals(instance, ConfigurationManager.getConfigInstance());
}
 
Example 3
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 4
Source File: ClientPropertiesTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotation() {
    MyTransportFactory transportFactory = new MyTransportFactory(ClientConfigFactory.DEFAULT);
    RibbonResourceFactory resourceFactory = new DefaultResourceFactory(ClientConfigFactory.DEFAULT, transportFactory);
    RibbonDynamicProxy.newInstance(SampleMovieService.class, resourceFactory, ClientConfigFactory.DEFAULT, transportFactory);
    IClientConfig clientConfig = transportFactory.getClientConfig();
    assertEquals(1000, clientConfig.get(Keys.ConnectTimeout).longValue());
    assertEquals(2000, clientConfig.get(Keys.ReadTimeout).longValue());

    Configuration config = ConfigurationManager.getConfigInstance();
    assertEquals("2000", config.getProperty("SampleMovieService.ribbon.ReadTimeout"));
    assertEquals("1000", config.getProperty("SampleMovieService.ribbon.ConnectTimeout"));

    config.setProperty("SampleMovieService.ribbon.ReadTimeout", "5000");
    assertEquals(5000, clientConfig.get(Keys.ReadTimeout).longValue());
}
 
Example 5
Source File: LBBuilderTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildWithArchaiusProperties() {
    Configuration config = ConfigurationManager.getConfigInstance();
    config.setProperty("client1.niws.client." + Keys.DeploymentContextBasedVipAddresses, "dummy:7001");
    config.setProperty("client1.niws.client." + Keys.InitializeNFLoadBalancer, "true");
    config.setProperty("client1.niws.client." + Keys.NFLoadBalancerClassName, DynamicServerListLoadBalancer.class.getName());
    config.setProperty("client1.niws.client." + Keys.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName());
    config.setProperty("client1.niws.client." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    config.setProperty("client1.niws.client." + Keys.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName());
    config.setProperty("client1.niws.client." + Keys.ServerListUpdaterClassName, PollingServerListUpdater.class.getName());
    IClientConfig clientConfig = IClientConfig.Builder.newBuilder(NiwsClientConfig.class, "client1").build();
    ILoadBalancer lb = LoadBalancerBuilder.newBuilder().withClientConfig(clientConfig).buildLoadBalancerFromConfigWithReflection();
    assertNotNull(lb);
    assertEquals(DynamicServerListLoadBalancer.class.getName(), lb.getClass().getName());
    DynamicServerListLoadBalancer<Server> dynamicLB = (DynamicServerListLoadBalancer<Server>) lb;
    assertTrue(dynamicLB.getServerListUpdater() instanceof PollingServerListUpdater);
    assertTrue(dynamicLB.getFilter() instanceof ZoneAffinityServerListFilter);
    assertTrue(dynamicLB.getRule() instanceof RoundRobinRule);
    assertTrue(dynamicLB.getPing() instanceof DummyPing);
    assertEquals(Lists.newArrayList(expected), lb.getAllServers());
}
 
Example 6
Source File: PropsServlet.java    From s2g-zuul with 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 7
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsWithHostNameValidationOn() throws Exception {

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

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

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

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "true"); // <--
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

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

	testServer1.accept();

	URI getUri = new URI(SERVICE_URI1 + "test/");
	MultivaluedMapImpl params = new MultivaluedMapImpl();
	params.add("name", "test");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();

	try{
		rc.execute(request);

		fail("expecting ssl hostname validation error");
	}catch(ClientHandlerException che){
		assertTrue(che.getMessage().indexOf("hostname in certificate didn't match") > -1);
	}
}
 
Example 8
Source File: SecureGetTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testSunnyDay() throws Exception {

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

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

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

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer1.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

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

	testServer1.accept();

	URI getUri = new URI(SERVICE_URI1 + "test/");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
	HttpResponse response = rc.execute(request);
	assertEquals(200, response.getStatus());
}
 
Example 9
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 10
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 11
Source File: ArchaiusPropertyResolver.java    From ribbon with Apache License 2.0 5 votes vote down vote up
private ArchaiusPropertyResolver() {
    this.config = ConfigurationManager.getConfigInstance();

    ConfigurationManager.getConfigInstance().addConfigurationListener(new ConfigurationListener() {
        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if (!event.isBeforeUpdate()) {
                actions.forEach(ArchaiusPropertyResolver::invokeAction);
            }
        }
    });
}
 
Example 12
Source File: SubsetFilterTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() {
    Configuration config = ConfigurationManager.getConfigInstance();
    config.setProperty("SubsetFilerTest.ribbon.NFLoadBalancerClassName", com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
    config.setProperty("SubsetFilerTest.ribbon.NIWSServerListClassName", MockServerList.class.getName());
    config.setProperty("SubsetFilerTest.ribbon.NIWSServerListFilterClassName", ServerListSubsetFilter.class.getName());
    // turn off auto refresh
    config.setProperty("SubsetFilerTest.ribbon.ServerListRefreshInterval", String.valueOf(Integer.MAX_VALUE));
    config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.forceEliminatePercent", "0.6");
    config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.eliminationFailureThresold", 2);
    config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.eliminationConnectionThresold", 2);
    config.setProperty("SubsetFilerTest.ribbon.ServerListSubsetFilter.size", "5");
}
 
Example 13
Source File: ArchaiusServer.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the Archaius system and configures the Netty leak detection level (if necessary).
 * DO NOT CALL THIS DIRECTLY. Use {@link #launchServer(String[])} when you're ready to start the server.
 */
protected void infrastructureInit() {
    MainClassUtils.setupJbossLoggingToUseSlf4j();

    try {
        Pair<String, String> appIdAndEnvironmentPair = MainClassUtils.getAppIdAndEnvironmentFromSystemProperties();
        ConfigurationManager.loadCascadedPropertiesFromResources(appIdAndEnvironmentPair.getLeft());
    }
    catch (IOException e) {
        throw new RuntimeException("Error loading Archaius properties", e);
    }

    AbstractConfiguration appConfig = ConfigurationManager.getConfigInstance();
    Function<String, Boolean> hasPropertyFunction = (propKey) -> appConfig.getProperty(propKey) != null;
    Function<String, String> propertyExtractionFunction = (propKey) -> {
        // Properties in Archaius might be a Collection or an Object.
        Object propValObj = appConfig.getProperty(propKey);
        return (propValObj instanceof Collection)
               ? ((Collection<?>) propValObj).stream().map(String::valueOf).collect(Collectors.joining(","))
               : String.valueOf(propValObj);
    };
    Set<String> propKeys = new LinkedHashSet<>();
    appConfig.getKeys().forEachRemaining(propKeys::add);

    MainClassUtils.logApplicationPropertiesIfDebugActionsEnabled(
        hasPropertyFunction, propertyExtractionFunction, propKeys, false
    );

    MainClassUtils.setupNettyLeakDetectionLevel(hasPropertyFunction, propertyExtractionFunction);
}
 
Example 14
Source File: PropertiesServlet.java    From galaxy with Apache License 2.0 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);
    resp.setCharacterEncoding("utf-8");
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
    resp.setContentType("application/json");

    PrintWriter writer = resp.getWriter();
    try{
        writer.write(jsonStr);
        resp.setStatus(Response.SC_OK);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
 
Example 15
Source File: PropertiesServlet.java    From tcc-transaction with Apache License 2.0 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);
    resp.setCharacterEncoding("utf-8");
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
    resp.setContentType("application/json");

    PrintWriter writer = resp.getWriter();
    try{
        writer.write(jsonStr);
        resp.setStatus(Response.SC_OK);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
 
Example 16
Source File: ConfigurationSpringInitializer.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected Properties mergeProperties() throws IOException {
  Properties properties = super.mergeProperties();

  AbstractConfiguration config = ConfigurationManager.getConfigInstance();
  Iterator<String> iter = config.getKeys();
  while (iter.hasNext()) {
    String key = iter.next();
    Object value = config.getProperty(key);
    properties.put(key, value);
  }
  return properties;
}
 
Example 17
Source File: TenacityTestRule.java    From tenacity with Apache License 2.0 4 votes vote down vote up
private void setup() {
    resetStreams();
    Hystrix.reset();
    final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance();
    configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100");
}
 
Example 18
Source File: TenacityPropertyRegister.java    From tenacity with Apache License 2.0 4 votes vote down vote up
public static void registerCircuitForceReset(TenacityPropertyKey key) {
    final AbstractConfiguration configInstance = ConfigurationManager.getConfigInstance();
    configInstance.setProperty(circuitBreakerForceOpen(key), false);
    configInstance.setProperty(circuitBreakerForceClosed(key), false);
}
 
Example 19
Source File: SecureAcceptAllGetTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testPositiveAcceptAllSSLSocketFactory() throws Exception{

    // test connection succeeds connecting to a random SSL endpoint with allow all SSL factory

    AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

    String name = "GetPostSecureTest." + testName.getMethodName();

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

    cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory");

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

    TEST_SERVER.accept();

    URI getUri = new URI(TEST_SERVICE_URI + "test/");
    HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
    HttpResponse response = rc.execute(request);
    assertEquals(200, response.getStatus());
}
 
Example 20
Source File: ZuulFiltersModuleIntegTest.java    From zuul with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void before() {
    AbstractConfiguration configuration = ConfigurationManager.getConfigInstance();
    configuration.setProperty("zuul.filters.locations", "inbound,outbound,endpoint");
    configuration.setProperty("zuul.filters.packages", "com.netflix.zuul.init,com.netflix.zuul.init2");
}