org.apache.deltaspike.core.spi.config.ConfigSource Java Examples

The following examples show how to use org.apache.deltaspike.core.spi.config.ConfigSource. 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: ConfigImpl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private ConfigSource[] sortDescending(List<ConfigSource> configSources)
{
    Collections.sort(configSources, new Comparator<ConfigSource>()
    {
        /**
         * {@inheritDoc}
         */
        @Override
        public int compare(ConfigSource configSource1, ConfigSource configSource2)
        {
            int o1 = configSource1.getOrdinal();
            int o2 = configSource2.getOrdinal();
            if (o1 == o2)
            {
                return configSource1.getConfigName().compareTo(configSource2.getConfigName());
            }
            return (o1 > o2) ? -1 : 1;
        }
    });
    return configSources.toArray(new ConfigSource[configSources.size()]);
}
 
Example #2
Source File: DeltaSpikeConfigInfo.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private List<ConfigEntry> calculateConfigEntries()
{
    Map<String, String> allProperties = ConfigResolver.getAllProperties();
    List<ConfigEntry> configEntries = new ArrayList<ConfigEntry>(allProperties.size());
    ConfigSource[] configSources = ConfigResolver.getConfigSources();

    for (Map.Entry<String, String> configEntry : allProperties.entrySet())
    {
        String key = configEntry.getKey();
        String value = ConfigResolver.filterConfigValueForLog(key,
                                ConfigResolver.getProjectStageAwarePropertyValue(key));

        String fromConfigSource = getFromConfigSource(configSources, key);
        configEntries.add(new ConfigEntry(key, value, fromConfigSource));
    }

    return configEntries;
}
 
Example #3
Source File: DeltaSpikeConfigInfo.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getConfigSourcesAsString()
{
    ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
    try
    {
        Thread.currentThread().setContextClassLoader(appConfigClassLoader);

        ConfigSource[] configSources = ConfigResolver.getConfigSources();
        List<String> configSourceInfo = new ArrayList<String>();
        for (ConfigSource configSource : configSources)
        {
            configSourceInfo.add(Integer.toString(configSource.getOrdinal())
                + " - " + configSource.getConfigName());
        }

        return configSourceInfo.toArray(new String[configSourceInfo.size()]);
    }
    finally
    {
        // set back the original TCCL
        Thread.currentThread().setContextClassLoader(originalCl);
    }

}
 
Example #4
Source File: BaseConfigSource.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Init method e.g. for initializing the ordinal.
 * This method can be used from a subclass to determine
 * the ordinal value
 * @param defaultOrdinal the default value for the ordinal if not set via configuration
 */
protected void initOrdinal(int defaultOrdinal)
{
    ordinal = defaultOrdinal;

    String configuredOrdinalString = getPropertyValue(ConfigSource.DELTASPIKE_ORDINAL);

    try
    {
        if (configuredOrdinalString != null)
        {
            ordinal = Integer.parseInt(configuredOrdinalString.trim());
        }
    }
    catch (NumberFormatException e)
    {
        log.log(Level.WARNING,
                "The configured config-ordinal isn't a valid integer. Invalid value: " + configuredOrdinalString);
    }
}
 
Example #5
Source File: ConfigResolver.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Map of all properties from all scannable config sources. The values of the properties reflect the
 * values that would be obtained by a call to {@link #getPropertyValue(java.lang.String)}, that is, the value of the
 * property from the ConfigSource with the highest ordinal.
 *
 * @see ConfigSource#isScannable()
 */
public static Map<String, String> getAllProperties()
{
    ConfigSource[] configSources = getConfigProvider().getConfig().getConfigSources();
    Map<String, String> result = new HashMap<String, String>();

    for (int i = configSources.length; i > 0; i--)
    {
        ConfigSource configSource = configSources[i - 1];

        if (configSource.isScannable())
        {
            result.putAll(configSource.getProperties());
        }
    }

    return Collections.unmodifiableMap(result);
}
 
Example #6
Source File: ConfigResolver.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve all values for the given key.
 *
 * @param key
 *
 * @return a List of all found property values, sorted by their ordinal in ascending order
 *
 * @see org.apache.deltaspike.core.spi.config.ConfigSource#getOrdinal()
 */
public static List<String> getAllPropertyValues(String key)
{
    ConfigSource[] configSources = getConfigProvider().getConfig().getConfigSources();
    List<String> result = new ArrayList<String>();
    for (int i = configSources.length; i > 0; i--)
    {
        String value = configSources[i - 1].getPropertyValue(key);

        if (value != null)
        {
            value = filterConfigValue(key, value);
            if (!result.contains(value))
            {
                result.add(value);
            }
        }
    }

    return result;

}
 
Example #7
Source File: ConfigImpl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void addConfigSources(List<ConfigSource> configSourcesToAdd)
{
    if (configSourcesToAdd == null || configSourcesToAdd.isEmpty())
    {
        return;
    }

    List<ConfigSource> allConfigSources = new ArrayList<>();
    // start with all existing ConfigSources
    if (this.configSources != null)
    {
        for (ConfigSource configSource : this.configSources)
        {
            allConfigSources.add(configSource);
        }
    }

    for (ConfigSource configSourceToAdd : configSourcesToAdd)
    {
        configSourceToAdd.setOnAttributeChange(this::onAttributeChange);
        allConfigSources.add(configSourceToAdd);
    }

    this.configSources = sortDescending(allConfigSources);
}
 
Example #8
Source File: PropertyLoader.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Merge the given Properties in order of appearance.
 * @param sortedProperties
 * @return the merged Properties
 */
private static Properties mergeProperties(List<Properties> sortedProperties)
{
    Properties mergedProperties = new Properties();
    for (Properties p : sortedProperties)
    {
        for (Map.Entry<?, ?> entry : p.entrySet())
        {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            if (!ConfigSource.DELTASPIKE_ORDINAL.equals(key))
            {
                // simply overwrite the old properties with the new ones.
                mergedProperties.setProperty(key, value);
            }
        }
    }

    return mergedProperties;
}
 
Example #9
Source File: PropertyLoader.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the 'deltaspike_ordinal' of the given properties.
 * {@link #CONFIGURATION_ORDINAL_DEFAULT_VALUE} if
 * {@link ConfigSource#DELTASPIKE_ORDINAL} is not set in the
 * Properties file.
 *
 * @param p the Properties from the file.
 * @return the ordinal number of the given Properties file.
 */
private static int getConfigurationOrdinal(Properties p)
{
    int configOrder = CONFIGURATION_ORDINAL_DEFAULT_VALUE;

    String configOrderString = p.getProperty(ConfigSource.DELTASPIKE_ORDINAL);
    if (configOrderString != null && configOrderString.length() > 0)
    {
        try
        {
            configOrder = Integer.parseInt(configOrderString);
        }
        catch (NumberFormatException nfe)
        {
            LOG.severe(ConfigSource.DELTASPIKE_ORDINAL + " must be an integer value!");
            throw nfe;
        }
    }

    return configOrder;
}
 
Example #10
Source File: ScopeNotStartedTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Deployment
public static WebArchive deploy()
{
    String simpleName = ScopeNotStartedTest.class.getSimpleName();
    String archiveName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

    JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "scopeNotStartedTest.jar")
            .addPackage(CustomSchedulerWarFileTest.class.getPackage().getName())
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsResource(new StringAsset(MockedScheduler.class.getName()),
                    "META-INF/services/" + Scheduler.class.getName())
            .addAsResource(new StringAsset(CustomDeactivatedConfigSource.class.getName()),
                    "META-INF/services/" + ConfigSource.class.getName());

    return ShrinkWrap.create(WebArchive.class, archiveName + ".war")
            .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndSchedulerArchive())
            .addAsLibraries(ArchiveUtils.getContextControlForDeployment())
            .addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml").resolve(
                    "org.quartz-scheduler:quartz")
                    .withTransitivity()
                    .asFile())
            .addAsLibraries(testJar)
            .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example #11
Source File: CustomSchedulerWarFileTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Deployment
public static WebArchive deploy()
{
    String simpleName = CustomSchedulerWarFileTest.class.getSimpleName();
    String archiveName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

    JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "customSchedulerTest.jar")
            .addPackage(CustomSchedulerWarFileTest.class.getPackage().getName())
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsResource(new StringAsset(MockedScheduler.class.getName()),
                    "META-INF/services/" + Scheduler.class.getName())
            .addAsResource(new StringAsset(CustomConfigSource.class.getName()),
                    "META-INF/services/" + ConfigSource.class.getName());

    return ShrinkWrap.create(WebArchive.class, archiveName + ".war")
            .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndSchedulerArchive())
            .addAsLibraries(ArchiveUtils.getContextControlForDeployment())
            .addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml").resolve(
                    "org.quartz-scheduler:quartz")
                    .withTransitivity()
                    .asFile())
            .addAsLibraries(testJar)
            .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example #12
Source File: ConfigResolverTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private void setTestConfigSourceValue(String key, String value)
{
    ConfigSource[] configSources = ConfigResolver.getConfigSources();
    for (ConfigSource configSource : configSources)
    {
        if (configSource instanceof TestConfigSource)
        {
            if (value == null)
            {
                configSource.getProperties().remove(key);
            }
            else
            {
                configSource.getProperties().put(key, value);
            }

            break;
        }
    }
}
 
Example #13
Source File: ThreadPoolManagerTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test // this test validates we read the config properly but also it is lazy
public void configuredPool() throws ExecutionException, InterruptedException
{
    ConfigResolver.addConfigSources(Collections.<ConfigSource>singletonList(new PropertiesConfigSource(new Properties()
    {{
        setProperty("futureable.pool.custom.coreSize", "5");
    }})
    {
        @Override
        public String getConfigName()
        {
            return "configuredPool";
        }
    }));
    final ExecutorService custom = manager.find("custom");
    assertEquals(custom, custom);
    assertSame(custom, custom);
    assertEquals(5, ThreadPoolExecutor.class.cast(custom).getCorePoolSize());
    assertUsable(custom);
}
 
Example #14
Source File: ProjectStageProducer.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public List<ConfigSource> getConfigSources() {
    return new ArrayList<ConfigSource>() {{
        add(new ConfigSource() {
            @Override
            public int getOrdinal() {
                return 0;
            }

            @Override
            public String getPropertyValue(final String key) {
                return value(key);
            }

            @Override
            public String getConfigName() {
                return "test-project-stage";
            }

            @Override
            public Map<String, String> getProperties() {
                return Collections.emptyMap();
            }

            @Override
            public boolean isScannable() {
                return false;
            }
        });
    }};
}
 
Example #15
Source File: ConfigImpl.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Shuts down the Config.
 * This will also close all ConfigSources and ConfigFilters which
 * implment the {@link java.lang.AutoCloseable} interface.
 */
void release()
{
    for (ConfigSource configSource : configSources)
    {
        close(configSource);
    }

    for (ConfigFilter configFilter : configFilters)
    {
        close(configFilter);
    }
}
 
Example #16
Source File: ConfigurationExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public void findSources(@Observes ProcessBean<? extends ConfigSource> source)
{
    if (!source.getAnnotated().isAnnotationPresent(Source.class))
    {
        return;
    }
    cdiSources.add(source.getBean());
}
 
Example #17
Source File: ConfigurationExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public void registerUserConfigSources(@Observes AfterBeanDiscovery abd)
{
    if (!isActivated)
    {
        return;
    }

    // create a local copy with all the collected PropertyFileConfig
    Set<Class<? extends PropertyFileConfig>> allPropertyFileConfigClasses
        = new HashSet<Class<? extends PropertyFileConfig>>(this.propertyFileConfigClasses);

    // now add any PropertyFileConfigs from a 'parent BeanManager'
    // we start with the current TCCL
    ClassLoader currentClassLoader = ClassUtils.getClassLoader(null);
    addParentPropertyFileConfigs(currentClassLoader, allPropertyFileConfigClasses);

    // now let's add our own PropertyFileConfigs to the detected ones.
    // because maybe WE are a parent BeanManager ourselves!
    if (!this.propertyFileConfigClasses.isEmpty())
    {
        detectedParentPropertyFileConfigs.put(currentClassLoader, this.propertyFileConfigClasses);
    }

    // collect all the ConfigSources from our PropertyFileConfigs
    List<ConfigSource> configSources = new ArrayList<ConfigSource>();
    for (Class<? extends PropertyFileConfig> propertyFileConfigClass : allPropertyFileConfigClasses)
    {
        configSources.addAll(createPropertyConfigSource(propertyFileConfigClass));
    }
    ConfigResolver.addConfigSources(configSources);

    registerConfigMBean();

    logConfiguration();
}
 
Example #18
Source File: ConfigImpl.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Performs all the initialisation of the default
 * ConfigSources, ConfigFilters, etc
 */
void init()
{
    List<ConfigSource> appConfigSources
        = ServiceUtils.loadServiceImplementations(ConfigSource.class, false, classLoader);

    List<ConfigSourceProvider> configSourceProviderServiceLoader
        = ServiceUtils.loadServiceImplementations(ConfigSourceProvider.class, false, classLoader);

    for (ConfigSourceProvider configSourceProvider : configSourceProviderServiceLoader)
    {
        appConfigSources.addAll(configSourceProvider.getConfigSources());
    }
    addConfigSources(appConfigSources);

    if (LOG.isLoggable(Level.FINE))
    {
        for (ConfigSource cs : appConfigSources)
        {
            LOG.log(Level.FINE, "Adding ordinal {0} ConfigSource {1}",
                    new Object[]{cs.getOrdinal(), cs.getConfigName()});
        }
    }

    List<ConfigFilter> configFilters
        = ServiceUtils.loadServiceImplementations(ConfigFilter.class, false, classLoader);
    this.configFilters = new CopyOnWriteArrayList<>(configFilters);
}
 
Example #19
Source File: ConfigurationExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private void logConfiguration()
{
    Boolean logConfig = ConfigResolver.resolve(ConfigResolver.DELTASPIKE_LOG_CONFIG).as(Boolean.class).getValue();
    if (logConfig != null && logConfig && LOG.isLoggable(Level.INFO))
    {
        StringBuilder sb = new StringBuilder(1 << 16);

        // first log out the config sources in descendent ordinal order
        sb.append("ConfigSources: ");
        ConfigSource[] configSources = ConfigResolver.getConfigSources();
        for (ConfigSource configSource : configSources)
        {
            sb.append("\n\t").append(configSource.getOrdinal()).append(" - ").append(configSource.getConfigName());
        }

        // and all the entries in no guaranteed order
        Map<String, String> allProperties = ConfigResolver.getAllProperties();
        sb.append("\n\nConfigured Values:");
        for (Map.Entry<String, String> entry : allProperties.entrySet())
        {
            sb.append("\n\t")
                .append(entry.getKey())
                .append(" = ")
                .append(ConfigResolver.filterConfigValueForLog(entry.getKey(), entry.getValue()));
        }

        LOG.info(sb.toString());
    }
}
 
Example #20
Source File: TypedResolverImpl.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private String getPropertyValue(String key)
{
    String value;
    for (ConfigSource configSource : config.getConfigSources())
    {
        value = configSource.getPropertyValue(key);

        if (value != null)
        {
            if (LOG.isLoggable(Level.FINE))
            {
                LOG.log(Level.FINE, "found value {0} for key {1} in ConfigSource {2}.",
                        new Object[]{config.filterConfigValue(key, value, true),
                            key, configSource.getConfigName()});
            }

            if (this.evaluateVariables)
            {
                value = resolveVariables(value);
            }

            return config.filterConfigValue(key, value, false);
        }

        if (LOG.isLoggable(Level.FINE))
        {
            LOG.log(Level.FINER, "NO value found for key {0} in ConfigSource {1}.",
                    new Object[]{key, configSource.getConfigName()});
        }
    }

    return null;
}
 
Example #21
Source File: DeltaSpikeConfigInfo.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private String getFromConfigSource(ConfigSource[] configSources, String key)
{
    for (ConfigSource configSource : configSources)
    {
        if (configSource.getPropertyValue(key) != null)
        {
            return configSource.getConfigName();
        }
    }

    return null;
}
 
Example #22
Source File: DeltaSpikeConfigInfo.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public TabularData getConfigSources()
{
    ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
    try
    {
        Thread.currentThread().setContextClassLoader(appConfigClassLoader);

        String typeName = "ConfigSources";
        OpenType<?>[] types = new OpenType<?>[]{SimpleType.INTEGER, SimpleType.STRING};
        String[] keys = new String[]{"Ordinal", "ConfigSource"};

        CompositeType ct = new CompositeType(typeName, typeName, keys, keys, types);
        TabularType type = new TabularType(typeName, typeName, ct, keys);
        TabularDataSupport configSourceInfo = new TabularDataSupport(type);

        ConfigSource[] configSources = ConfigResolver.getConfigSources();
        for (ConfigSource configSource : configSources)
        {
            configSourceInfo.put(
                new CompositeDataSupport(ct, keys,
                        new Object[]{configSource.getOrdinal(), configSource.getConfigName()}));
        }

        return configSourceInfo;
    }
    catch (OpenDataException e)
    {
        throw new RuntimeException(e);
    }
    finally
    {
        // set back the original TCCL
        Thread.currentThread().setContextClassLoader(originalCl);
    }
}
 
Example #23
Source File: DefaultConfigSourceProvider.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Add a ConfigSource for files in the user home folder IF it exists!
 * The location is ~/.deltaspike/apache-deltaspike.properties
 */
private void addUserHomeConfigSource()
{
    String userHome = System.getProperty("user.home");
    if (userHome != null && !userHome.isEmpty())
    {
        File dsHome = new File(userHome, PROPERTY_FILE_HOME_NAME);
        try
        {
            if (dsHome.exists())
            {
                try
                {
                    ConfigSource dsHomeConfigSource = new PropertyFileConfigSource(dsHome.toURI().toURL());
                    configSources.add(dsHomeConfigSource);
                    LOG.log(Level.INFO, "Reading configuration from {}", dsHome.getAbsolutePath());
                }
                catch (MalformedURLException e)
                {
                    LOG.log(Level.WARNING, "Could not read configuration from " + dsHome.getAbsolutePath(), e);
                }

            }
        }
        catch (SecurityException se)
        {
            LOG.log(Level.INFO, "Not allowed to check if directory {} exists", dsHome.getPath());
        }
    }
}
 
Example #24
Source File: ServletConfigListener.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce)
{
    ConfigSource[] configSources = ConfigResolver.getConfigSources();
    for (ConfigSource configSource : configSources)
    {
        if (configSource instanceof ServletConfigSource)
        {
            setServletConfig((ServletConfigSource) configSource, sce);
            return;
        }
    }
}
 
Example #25
Source File: DefaultConfigSourceProvider.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<ConfigSource> getConfigSources()
{
    return configSources;
}
 
Example #26
Source File: ConfigResolver.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
public static ConfigSource[] getConfigSources()
{
    return getConfigProvider().getConfig().getConfigSources();
}
 
Example #27
Source File: ConfigImpl.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Override
public ConfigSource[] getConfigSources()
{
    return configSources;
}
 
Example #28
Source File: EnvironmentPropertyConfigSourceProvider.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Override
public List<ConfigSource> getConfigSources()
{
    return configSources;
}
 
Example #29
Source File: ViewConfigTest.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void init()
{
    active = true;

    ConfigResolver.addConfigSources(new ArrayList<ConfigSource>() {
        {
            add(new ConfigSource()
            {
                @Override
                public int getOrdinal()
                {
                    return Integer.MAX_VALUE;
                }

                @Override
                public Map<String, String> getProperties()
                {
                    return Collections.emptyMap();
                }

                @Override
                public String getPropertyValue(String key)
                {
                    if (active && View.ViewConfigPreProcessor.class.getName().equals(key))
                    {
                        return TestConfigPreProcessor.class.getName();
                    }
                    return null;
                }

                @Override
                public String getConfigName()
                {
                    return "test-view-config";
                }

                @Override
                public boolean isScannable()
                {
                    return false;
                }
            });
        }

        private static final long serialVersionUID = 3247551986947387154L;
    });
}
 
Example #30
Source File: ViewConfigPathTest.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void init()
{
    active = true;

    ConfigResolver.addConfigSources(new ArrayList<ConfigSource>() {
        {
            add(new ConfigSource() {
                @Override
                public int getOrdinal() {
                    return Integer.MAX_VALUE;
                }

                @Override
                public Map<String, String> getProperties() {
                    return Collections.emptyMap();
                }

                @Override
                public String getPropertyValue(String key) {
                    if (active && View.ViewConfigPreProcessor.class.getName().equals(key)) {
                        return ViewConfigPreProcessorWithoutValidation.class.getName();
                    }
                    return null;
                }

                @Override
                public String getConfigName() {
                    return "test-view-config";
                }

                @Override
                public boolean isScannable() {
                    return false;
                }
            });
        }

        private static final long serialVersionUID = 3247551986947387154L;
    });
}