Search in sources :

Example 1 with GuiceConfig

use of com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig in project stdlib by petergeneric.

the class GuiceFactory method build.

/**
 * Build a guice environment; this is achieved in the following stages:
 * <ol>
 * <li>Load GuiceRole implementations using {@link ServiceLoader} Service Provider Interface</li>
 * <li>Allow all GuiceRole instances to add/remove/change base configuration</li>
 * <li>Load configuration file resources (e.g. environment.properties)</li>
 * <li>Load network configuration (if enabled)</li>
 * <li>Add special GuiceRole for network configuration auto-reload (if network configuration enabled)</li>
 * <li>Load the override configuration file (if present)</li>
 * <li>Set up the classpath scanner (using property {@link GuiceProperties#SCAN_PACKAGES})</li>
 * <li>Instantiate the {@link GuiceSetup} class specified in {@link GuiceProperties#SETUP_PROPERTY}</li>
 * <li>Hand over the GuiceSetup, Roles, Configuration and Classpath Scanner to {@link #createInjector(GuiceRegistry, *
 * ClassScannerFactory, GuiceConfig, GuiceSetup, List)}</li>
 * </ol>
 *
 * @param registry
 * 		(optional) the GuiceRegistry to expose to the Guice environment
 * @param scannerFactory
 * 		(optional) classpath scanner to use
 * @param configs
 * 		base configurations to use
 * @param roles
 * 		base roles to use
 * @param staticSetup
 * 		(optional) a {@link GuiceSetup} implementation to use instead of loading the class name from a property
 * @param autoLoadProperties
 * 		if true, environment.properties etc. and network configuration will be loaded from disk
 * @param autoLoadRoles
 * 		if true, roles will be loaded using the Service Provider Interface
 * @param classloader
 * 		the classloader to use when loading environment.properties etc.
 *
 * @return
 */
static Injector build(final GuiceRegistry registry, ClassScannerFactory scannerFactory, final List<PropertyFile> configs, final List<GuiceRole> roles, final GuiceSetup staticSetup, final boolean autoLoadProperties, final boolean autoLoadRoles, final ClassLoader classloader) {
    final ServiceLoader<GuiceRole> loader = ServiceLoader.load(GuiceRole.class);
    // Find additional guice roles from jar files using the Service Provider Interface
    if (autoLoadRoles) {
        Iterator<GuiceRole> it = loader.iterator();
        while (it.hasNext()) {
            final GuiceRole role = it.next();
            log.debug("Discovered guice role: " + role);
            roles.add(role);
        }
    }
    // Make sure that the first most basic level of properties is the system environment variables
    configs.add(0, getAllEnvironmentVariables());
    // Allow all GuiceRole implementations to add/remove/reorder configuration sources
    for (GuiceRole role : roles) {
        log.debug("Adding requested guice role: " + role);
        role.adjustConfigurations(configs);
    }
    GuiceConfig properties = new GuiceConfig();
    // Generate a random instance ID for this instance of the guice environment
    final String instanceId = SimpleId.alphanumeric(32);
    // Make the randomly generated instance id available to others
    properties.set(GuiceProperties.INSTANCE_ID, instanceId);
    for (PropertyFile config : configs) properties.setAll(config);
    // Load all the core property files?
    if (autoLoadProperties) {
        applyConfigs(classloader, properties);
    }
    // This is a bit of a hack really, but let's insert the GuiceRole for network config if network config is enabled
    if (hasNetworkConfiguration(properties)) {
        final NetworkConfigGuiceRole role = new NetworkConfigGuiceRole();
        roles.add(role);
    }
    // Read the override configuration property to find the override config file
    // Load the override config file and pass that along too.
    PropertyFile overrideFile = load(properties.get(GuiceProperties.OVERRIDE_FILE_PROPERTY));
    // If there are overrides then rebuild the configuration to reflect it
    if (overrideFile != null) {
        log.debug("Applying overrides: " + overrideFile.getFile());
        properties.setOverrides(overrideFile.toMap());
    }
    // Set up the class scanner factory (if the scanner property is set and one has not been provided)
    if (scannerFactory == null) {
        List<String> packages = properties.getList(GuiceProperties.SCAN_PACKAGES, Collections.emptyList());
        if (packages != null && !packages.isEmpty())
            scannerFactory = new ClassScannerFactory(packages.toArray(new String[packages.size()]));
        else
            throw new IllegalArgumentException("Property " + GuiceProperties.SCAN_PACKAGES + " has not been set!");
    }
    final GuiceSetup setup;
    if (staticSetup == null) {
        // Load the Setup property and load the Setup class
        final Class<? extends GuiceSetup> setupClass = getClass(properties, GuiceSetup.class, GuiceProperties.SETUP_PROPERTY);
        try {
            if (setupClass == null)
                throw new IllegalArgumentException("Could not find a setup class!");
            setup = setupClass.newInstance();
            log.debug("Constructed GuiceSetup: " + setupClass);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException("Error constructing instance of " + setupClass, e);
        }
    } else {
        log.debug("Using static GuiceSetup: " + staticSetup);
        setup = staticSetup;
    }
    return createInjector(registry, scannerFactory, properties, setup, roles);
}
Also used : GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) GuiceSetup(com.peterphi.std.guice.apploader.GuiceSetup) GuiceRole(com.peterphi.std.guice.apploader.GuiceRole) NetworkConfigGuiceRole(com.peterphi.std.guice.common.serviceprops.net.NetworkConfigGuiceRole) PropertyFile(com.peterphi.std.io.PropertyFile) ClassScannerFactory(com.peterphi.std.guice.common.ClassScannerFactory) NetworkConfigGuiceRole(com.peterphi.std.guice.common.serviceprops.net.NetworkConfigGuiceRole)

Example 2 with GuiceConfig

use of com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig in project stdlib by petergeneric.

the class JAXBResourceFactoryTest method testChangingLiteralProperty.

@Test
public void testChangingLiteralProperty() throws Exception {
    MyType first = new MyType("test1", true);
    MyType second = new MyType("test2", true);
    GuiceConfig config = new GuiceConfig();
    config.set("some.xml", "<MyType name=\"test1\"/>");
    JAXBResourceFactory factory = new JAXBResourceFactory(config, SERIALISER_FACTORY);
    assertEquals(first, factory.get(MyType.class, "some.xml"));
    config.set("some.xml", "<MyType name=\"test2\"/>");
    assertEquals(second, factory.get(MyType.class, "some.xml"));
}
Also used : GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) Test(org.junit.Test)

Example 3 with GuiceConfig

use of com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig in project stdlib by petergeneric.

the class JAXBResourceFactoryTest method testLiteralPropertyCaching.

@Test
public void testLiteralPropertyCaching() throws Exception {
    MyType expected = new MyType("test", true);
    GuiceConfig config = new GuiceConfig();
    config.set("some.xml", "<MyType name=\"test\"/>");
    JAXBResourceFactory factory = new JAXBResourceFactory(config, SERIALISER_FACTORY);
    final MyType a = factory.get(MyType.class, "some.xml");
    final MyType b = factory.get(MyType.class, "some.xml");
    assertEquals(expected, a);
    assertSame("cache should return same JAXB object ref when XML has not changed", a, b);
}
Also used : GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) Test(org.junit.Test)

Example 4 with GuiceConfig

use of com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig in project stdlib by petergeneric.

the class ResourceGuiceModule method getTemplateNetworkConfig.

@Provides
@Named("template-config")
public NetworkConfig getTemplateNetworkConfig() {
    NetworkConfig config = new NetworkConfig();
    config.path = "/resource-templates";
    config.properties = new GuiceConfig();
    return config;
}
Also used : GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) NetworkConfig(com.peterphi.std.guice.common.serviceprops.net.NetworkConfig) Named(com.google.inject.name.Named) Provides(com.google.inject.Provides)

Example 5 with GuiceConfig

use of com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig in project stdlib by petergeneric.

the class HibernateModule method extractHibernateProperties.

private Properties extractHibernateProperties(final GuiceConfig guiceConfig, @Named(GuiceProperties.HIBERNATE_PROPERTIES) final String propertyFileName) {
    final Properties properties;
    if (PROPFILE_VAL_EMBEDDED.equals(propertyFileName)) {
        // Extract all properties starting with "hibernate." and "liquibase."
        properties = guiceConfig.toProperties(k -> k.startsWith("hibernate.") || k.startsWith("liquibase."));
    } else {
        if (StringUtils.contains(propertyFileName, '\n')) {
            log.debug("Assuming hibernate.properties contains literal hibernate.properties file, not a resource/file reference");
            properties = PropertyFile.fromString(propertyFileName).toProperties();
        } else {
            PropertyFile[] files = PropertyFile.findAll(propertyFileName);
            if (files == null || files.length == 0) {
                throw new IllegalArgumentException("Cannot find any property files called: " + propertyFileName);
            } else {
                // Merge all hibernate property files into a single file
                PropertyFile file = PropertyFile.readOnlyUnion(files);
                // Now Merge all the values and interpret them via the guice config to allow for interpolation of variables
                GuiceConfig temp = new GuiceConfig();
                temp.setAll(guiceConfig);
                temp.setAll(file);
                // Now extract the hibernate properties again with any variables
                properties = temp.toProperties(key -> file.containsKey(key));
            }
        }
    }
    return properties;
}
Also used : Matchers(com.google.inject.matcher.Matchers) StringUtils(org.apache.commons.lang.StringUtils) Session(org.hibernate.Session) PropertyFile(com.peterphi.std.io.PropertyFile) HibernateObservingInterceptor(com.peterphi.std.guice.hibernate.module.logging.HibernateObservingInterceptor) Transaction(org.hibernate.Transaction) GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) Logger(org.apache.log4j.Logger) SampleCountUserType(com.peterphi.std.guice.hibernate.usertype.SampleCountUserType) DateUserType(com.peterphi.std.guice.hibernate.usertype.DateUserType) Configuration(org.hibernate.cfg.Configuration) JodaLocalDateUserType(com.peterphi.std.guice.hibernate.usertype.JodaLocalDateUserType) HibernateConfigurationValidator(com.peterphi.std.guice.hibernate.module.ext.HibernateConfigurationValidator) MetricRegistry(com.codahale.metrics.MetricRegistry) Properties(java.util.Properties) Iterator(java.util.Iterator) SessionFactory(org.hibernate.SessionFactory) Transactional(com.peterphi.std.guice.database.annotation.Transactional) ServiceLoader(java.util.ServiceLoader) ServiceRegistry(org.hibernate.service.ServiceRegistry) JodaDateTimeUserType(com.peterphi.std.guice.hibernate.usertype.JodaDateTimeUserType) UserType(org.hibernate.usertype.UserType) Provides(com.google.inject.Provides) GuiceProperties(com.peterphi.std.guice.apploader.GuiceProperties) Named(com.google.inject.name.Named) TimecodeUserType(com.peterphi.std.guice.hibernate.usertype.TimecodeUserType) AbstractModule(com.google.inject.AbstractModule) Singleton(com.google.inject.Singleton) GuiceConfig(com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig) Properties(java.util.Properties) GuiceProperties(com.peterphi.std.guice.apploader.GuiceProperties) PropertyFile(com.peterphi.std.io.PropertyFile)

Aggregations

GuiceConfig (com.peterphi.std.guice.common.serviceprops.composite.GuiceConfig)11 Test (org.junit.Test)8 Provides (com.google.inject.Provides)2 Named (com.google.inject.name.Named)2 PropertyFile (com.peterphi.std.io.PropertyFile)2 MetricRegistry (com.codahale.metrics.MetricRegistry)1 AbstractModule (com.google.inject.AbstractModule)1 Injector (com.google.inject.Injector)1 Singleton (com.google.inject.Singleton)1 Matchers (com.google.inject.matcher.Matchers)1 GuiceProperties (com.peterphi.std.guice.apploader.GuiceProperties)1 GuiceRole (com.peterphi.std.guice.apploader.GuiceRole)1 GuiceSetup (com.peterphi.std.guice.apploader.GuiceSetup)1 ClassScannerFactory (com.peterphi.std.guice.common.ClassScannerFactory)1 NetworkConfig (com.peterphi.std.guice.common.serviceprops.net.NetworkConfig)1 NetworkConfigGuiceRole (com.peterphi.std.guice.common.serviceprops.net.NetworkConfigGuiceRole)1 Transactional (com.peterphi.std.guice.database.annotation.Transactional)1 HibernateConfigurationValidator (com.peterphi.std.guice.hibernate.module.ext.HibernateConfigurationValidator)1 HibernateObservingInterceptor (com.peterphi.std.guice.hibernate.module.logging.HibernateObservingInterceptor)1 DateUserType (com.peterphi.std.guice.hibernate.usertype.DateUserType)1