http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_osgi.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_osgi.adoc b/content/documentation-new/extensions/mod_osgi.adoc new file mode 100644 index 0000000..d075ac1 --- /dev/null +++ b/content/documentation-new/extensions/mod_osgi.adoc @@ -0,0 +1,814 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extensions: OSGI Integration + +toc::[] + + +[[OSGI]] +== Tamaya OSGI Support + +Tamaya _OSGI_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _OSGI_ provides support for integration with OSGI. Hereby Tamaya does actively override or extend the OSGI ++ConfigAdmin+ based configuration with entries stored and managed by Tamaya. Tamaya provides also shell extensions +to enable/perform configuration loading and restoring actions. +Optionally Tamaya also provides extension for automatically trigger configuration updates, when configuration has +been changed and configuration injection using Tamaya's injection API. + + +=== Compatibility + +All module described are based on Java 8, so it will run on Java 8 and beyond. +The modules are built against *OSGI Compendium version 5.0*. Tamaya OSGI support +is tested against the following OSGI runtimes: + +* Apache Karaf, version 4.0.7 +* Apache Felix, version 5.6.1 +* Eclipse Equinox, version x.x.x. + + +=== Installation + +To benefit from Tamaya in an OSGI context you must deploy at least the following modules to +your OSGI runtime environment: + +[source, listing] +----------------------------------------------- +# Runtime with OSGI ConfigAdmin support, e.g. +org.apache.felix:org.apache.felix.configadmin:{felix_version} +# API and core +org.apache.geronimo.specs:geronimo-annotation_1.2_spec:1.0 +org.apache.tamaya:tamaya-api:{tamaya_version} +org.apache.tamaya:tamaya-spisupport:{tamaya_version} +org.apache.tamaya:tamaya-core:{tamaya_version} +# Required extensions +org.apache.tamaya.ext:tamaya-functions:{tamaya_version} +org.apache.tamaya.ext:tamaya-osgi:{tamaya_version} +----------------------------------------------- + + +=== Tamaya Service Loading in OSGI + +Important to know is that within OSGI class- and resource loading is not compatible with standard Java SE. Also +in OSGI, bundles can be loaded or unloaded at any time, so Tamaya's logic must cope with this as well. +These constraints are handled by Tamaya (implemented in +tamaya-core+ and +tamaya-osgi+) as follows: + +* Tamaya registers a +OSGIServiceContext+ which reads all +java.util.ServiceLoader+ configurations and + registers them as OSGI services. Hereby integration is two-way: The core module contains an + OSGI +Activator+ that replaces Tamaya's default +ServiceContext+ with an OSGI based implementation that + will consume all services from the OSGI service API. Consequently you can also register Tamaya extensions + as OSGI services using standard OSGI tooling (e.g. your own +PropertySource+ instances). Tamaya hereby + also does not store any service references, so the dynamic nature of OSGI is fully honored. +* Tamaya's +ServiceContext+ SPI does additionally provide functionality for loading of (classpath) + resources using the bundle's +getEntry(String)+ method. +* Tamaya similarly checks the classpath of all bundles for Tamaya SPI services to be registered thus + implementing the +ServiceLoader+ logic in OSGI. Hereby Tamaya will only register services with the + +org.apache.tamaya+ as root package. + +NOTE: Tamaya actually does not replace any existing +ConfigAdmin+ component, Tamaya modifies any existing OSGI + configuration on changes detected and stores backups of any OSGI configuration before applying any + changes. + +=== Configuring Bundles +==== Mapping of pids and factoryPids + +When accessing configuration from the OSGI +ConfigAdmin+ a pid and an optional location can be provided. +Tamaya requires all configuration for a PID to be located in keys starting [PID]: + +[source, listing] +.OSGI pid mapping +----------------------------------------------- +# OSGI settings +pid=myBundle +key=common.net.port + +# Corresponding key in Tamaya configuration +[myBundle]key=common.net.port +----------------------------------------------- + +==== Enabling/Disabling Tamaya + +By default, Tamaya doesn't do anything, unless it is told to so so. So having installed the Tamaya OSGI plugin, +you will see the bundles are loaded, but your OSGI environment still works the same. This is not accidentally, since +configuration is a crucial part. This means Tamaya, by default, is disabled for all bundles. You have now several +options to enabled Tamaya: + +* you can enable Tamaya for *all* bundles by default by + ** setting the +-Dtamaya-enabled=true+ system property. + ** by setting +tamaya-enabled=true+ in the OSGI Configuration for the PID +TamayaConfigPlugin+. +* you can enable Tamaya for a single bundle by + ** by setting +tamaya-enabled=true+ in the OSGI Configuration for the given bundle. + ** by adding +Tamaya-Enabled: true+ to the bundle's MANIFEST. + +Similarly you can also combine these options the other way round: + +* You can enable Tamaya by default as shown above. +* You can disable Tamaya for bundles by + ** by setting +tamaya-enabled=false+ in the OSGI Configuration for the given bundle. + ** by adding +Tamaya-Enabled: false+ to the bundle's MANIFEST. + + +==== Controlling How Tamaya changes your OSGI Configuration + +Tamaya supports different policies that define how Tamaya is changing the OSGI configuration: + +* *EXTEND*: Only add properties not existing in the OSGI configuration, but never override + or remove existing properties. +* *OVERRIDE*: Override existing properties and also add new properties. +* *UPDATE_ONLY*: Only override existing properties but do not add any properties. + +By default, Tamaya uses the _OVERRIDE_ policy. Also this policy can be configured in several +ways and with different scopes: + +* You can define the _default_ policy applied, by + ** setting the +-Dtamaya-policy=POLICY+ system property. + ** by setting +tamaya-policy=POLICY+ in the OSGI Configuration for the PID +TamayaConfigPlugin+. + +Hereby, _POLICY_ must be one of +OVERRIDE, EXTEND, UPDATE_ONLY+. + +* You can also configure the policy individually for a bundle by + ** by setting +tamaya-policy=POLICY+ in the OSGI Configuration for the given bundle. + ** by adding +Tamaya-Policy: POLICY+ to the bundle's MANIFEST. + +==== Mapping OSGI PIDs to Tamaya Configuration + +Tamaya configuration is a single +Map<String,String> with String keys and String values. Whereas OSGI configuration are +multiple +Dictionary<String,?>+ (for several PIDs). The Tamaya OSGI extension implements the following mapping: + +As an example refer to the followinf Tamaya configuration entries: + +[source, listing] +.Tamaya configuration for PID 'MyPlugin' +----------------------------------------------- +[MyPlugin]ch.base.pack.Main.customer=Native Inc +[MyPlugin]ch.base.pack.Main.use=234 +[MyPlugin]ch.base.pack.Main.encoding=UTF-8 +----------------------------------------------- + +The OSGI Configuration Plugin now provides the following configuration for PID: + +[source, listing] +.OSGI configuration for PID 'MyPlugin' +----------------------------------------------- +ch.base.pack.Main.use=100 (Integer) +ch.base.pack.Main.switch=on (Boolean) +ch.base.pack.Main.customer=NONE (String) +----------------------------------------------- + +Now using +Policy.OVERRIDE+ (as desribed in the previous section), Tamaya will change the OSGI configuration +as follows: + +[source, listing] +.OSGI configuration after Tamaya update for PID 'MyPlugin' +----------------------------------------------- +ch.base.pack.Main.use=234 (Integer) +ch.base.pack.Main.switch=on (Boolean) +ch.base.pack.Main.customer=Native Inc (String) +[MyPlugin]ch.base.pack.Main.encoding=UTF-8 (String) +----------------------------------------------- + +So Tamaya configuration mapping can be summarized as follows: + +* The OSGI PID is mapped to a Tamaya prefix +[PID]+. +* The OSGI keys are the exact same keys as from Tamaya with the _[PID]_ prefix removed. +* New entries are added (depending on the +Policy+) as +String+ values. +* Types of existing entries are preserved on update (this requires the Tamaya entries to be convertable into + the required target types. Refer to Tamaya's core documentation for supported types and how + to add custom converters). + +Finally, the mapping of the OSGI _PID_ to the Tamaya _[PID]_ prefix also can be customized by + +* adding +tamaya-config-root+ as an OSGI configuration property to the OSGI configuration. +* adding +Tamaya-Config-Root+ as a MANIFEST entry to the bundle. + +The root will replace the default _[PID]_ prefix with the value configured. + +==== OSGI Configuration Backup + +Before Tamaya changes any OSGI configuration it creates a _Backup_ of the existing OSGI +configuration dictionary and stores it in serialized form in the plugin's OSGI configuration. +This allows you to restore the original OSGI configuration in case of problems. Hereby Tamaya +automatically sets the +tamaya-enabled=false+ property to disable Tamaya for the given +configuration (bundle). + +The history can be accessed from the Tamaya Configuration Plugin Service +(shown later). + +==== OSGI Configuration Change Log + +All changes applied by Tamaya are logged as well using ++ConfigHistory+ entry items. The history can be accessed from the Tamaya Configuration Plugin Service +(shown later): + +[source, Java] +.OSGI ConfigHistory Entry +----------------------------------------------- +public final class ConfigHistory implements Serializable{ + + [...] + + public enum TaskType{ + PROPERTY, + BEGIN, + END, + } + + // *** + // Entry = attributes + // *** + + public TaskType getArea(){...} + + public String getPid() {... } + + public Object getPreviousValue() {... } + + public ConfigHistory setPreviousValue(Object previousValue) {... } + + public Object getValue() {...} + + public ConfigHistory setValue(Object value) {...} + + public String getKey() {...} + + public ConfigHistory setKey(String key) {...} + +} +----------------------------------------------- + +==== The Tamaya OSGI Configuration Service + +As mentioned Tamaya exposes it's OSGI functionality, allowing programmatic access to Tamaya configuration +logic with the +TamayaConfigService+ OSGI service: + +[source, Java] +.The exposed +TamayaConfigService+ +----------------------------------------------- +public interface TamayaConfigService{ + /** The system/config property to set Tamaya's {@link Policy}. */ + String TAMAYA_POLICY_PROP = "tamaya-policy"; + /** The MANIFEST property to set Tamaya's {@link Policy}. */ + String TAMAYA_POLICY_MANIFEST = "Tamaya-Policy"; + /** The system/config property to define a customized Tamaya's configuration root, replacing the {@code [PID]} default + * prefix used. */ + String TAMAYA_CUSTOM_ROOT_PROP = "tamaya-config-root"; + /** The MANIFEST property to define a customized Tamaya's configuration root, replacing the {@code [PID]} default + * prefix used. */ + String TAMAYA_CUSTOM_ROOT_MANIFEST = "Tamaya-Config-Root"; + /** The system/config property to enable Tamaya. */ + String TAMAYA_ENABLED_PROP = "tamaya-enabled"; + /** The MANIFEST property to enable Tamaya. */ + String TAMAYA_ENABLED_MANIFEST = "Tamaya-Enabled"; + /** The system/config property to enable Tamaya automatic updates (requires Tamaya's Updater plugin to be loaded as well). */ + String TAMAYA_AUTO_UPDATE_ENABLED_PROP = "tamaya-update-enabled"; + /** The MANIFEST property to enable Tamaya automatic updates (requires Tamaya's Updater plugin to be loaded as well). */ + String TAMAYA_AUTO_UPDATE_ENABLED_MANIFEST = "Tamaya-Update-Enabled"; + + /** + * Enables/disables automatic updates (requires Tamaya's Updater plugin to be loaded as well). + * @param enabled set to true to enable updates. + */ + void setAutoUpdateEnabled(boolean enabled); + + /** + * Enables/disables Tamaya config by default. + * @param enabled set to true to enable Tamaya for all bundles by default. + */ + void setTamayaEnabledByDefault(boolean enabled); + + /** + * Get the flag, if Tamaya is enabled by default for all bundles. + * @return true if Tamaya is enabled. + */ + boolean isTamayaEnabledByDefault(); + + /** + * Get the default policy Tamaya is using for adapting OSGI configuration. + * @return the default policy, never null. + */ + Policy getDefaultPolicy(); + + /** + * Set the default policy Tamaya is using for adapting OSGI configuration. + * @param policy the policy, not null. + */ + void setDefaultPolicy(Policy policy); + + /** + * Updates the given OSGI configuration with Tamaya configuration. + * @param pid the target PID, not null. + * @return the new configuration. + */ + Dictionary<String,Object> updateConfig(String pid); + + /** + * Updates the given OSGI configuration with Tamaya configuration. + * @param pid the target PID, not null. + * @param dryRun if true, the changes will not be applied to the OSGI configuration. + * @return the configuration that would be applied, has been applied. + */ + Dictionary<String,Object> updateConfig(String pid, boolean dryRun); + + /** + * Updates the given OSGI configuration with Tamaya configuration. + * @param pid the target PID, not null. + * @param policy the updating policy to be used, by default. + * @param forcePolicy if set to true, the given policy will be used, even if an alternate policy is configured + * for the given PID. + * @param dryRun if true, the changes will not be applied to the OSGI configuration. + * @return the configuration that would be applied, has been applied. + */ + Dictionary<String,Object> updateConfig(String pid, Policy policy, boolean forcePolicy, boolean dryRun); + + /** + * Checks if a bundle is enabled for Tamaya configuration. + * @param bundle the bundle, not null. + * @return true, if the bundle is enabled. + */ + boolean isBundleEnabled(Bundle bundle); + + /** + * Get the flag if automatic updates for config changes are enabled. + * @return true, if automatic updates for config changes are enabled. + */ + boolean isAutoUpdateEnabled(); + + /** + * Get the backup written for a PID. + * @param pid the pid, not null. + * @return the backup, or null, if no backup is present. + */ + Dictionary<String,?> getBackup(String pid); + + /** + * Get all current known PIDs for which backups are registered. + * @return all known PIDs for which backups are registered. + */ + Set<String> getBackupPids(); + + /** + * Restores a backup, replacing the current OSGI configuration with the backup and + * disabling Tamaya for this PID. + * @param pid the PID, not null. + * @return true, if a backup has been restored successfully. + */ + boolean restoreBackup(String pid); + + /** + * Stores the current OSGI configuration as a backup (only if no backup is existing). + * @param pid the target PID, not null. + * @return true, if a backup has been stored successfully. + */ + boolean createBackup(String pid); + + /** + * Deletes a backup, if existing. + * @param pid the target PID, not null. + * @return true, if a backup has been restored successfully. + */ + boolean deleteBackup(String pid); + + /** + * Sets the maximum getHistory size. + * @param maxHistory the max getHistory size. {@code 0} disables the getHistory function. + */ + void setMaxHistorySize(int maxHistory); + + /** + * Get the max getHistory size. + * @return the max getHistory size. {@code 0} means the getHistory function is disabled. + */ + int getMaxHistorySize(); + + /** + * Access the current (full) change getHistory. + * @return the current getHistory, never null. + */ + List<ConfigHistory> getHistory(); + + /** + * Clears the getHistory. + */ + void clearHistory(); + + /** + * Clears the getHistory for a PID. + * @param pid the target PID, not null. + */ + void clearHistory(String pid); + + /** + * Get the getHistory for a PID. + * @param pid the target PID, not null. + * @return the PID's getHistory, never null. + */ + List<ConfigHistory> getHistory(String pid); + + /** + * Access the current OSGI configuration for a PID. + * @param pid the target PID, not null. + * @param section a subsection to be filter (using startsWith). + * @return the (optionally filtered) OSGI configuration. + */ + Dictionary<String,Object> getOSGIConfiguration(String pid, String section); + + /** + * Checks if a backup exists. + * @param pid the target PID, not null. + * @return true, if a backup exists. + */ + boolean containsBackup(String pid); +} +----------------------------------------------- + + +==== The Tamaya OSGI Configuration Service + +Finally Tamaya also provides support for using Tamaya's injection API with your OSGI project. To enable injection +you must install a few additional bundles: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-osgi-injection</artifactId> + <version>${tamaya.version}</version> +</dependency> +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-injection</artifactId> + <version>${tamaya.version}</version> +</dependency> +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>injection-api</artifactId> + <version>${tamaya.version}</version> +</dependency> +----------------------------------------------- + +Given that you can inject configuration entries + +* on your services by + ** setting +tamaya-config-inject=true+ in your service properties. + ** setting +Tamaya-Config-Inject: true+ in your bundle's manifest. +* or by using the registered +ConfigInjectionService+: + +[source, java] +----------------------------------------------- +public interface ConfigInjectionService { + /** The manifest entry to enable Tamaya injection. */ + String TAMAYA_INJECTION_ENABLED_MANIFEST = "Tamaya-Config-Inject"; + /** The OSGI config entry to enable Tamaya injection. */ + String TAMAYA_INJECTION_ENABLED_PROP = "tamaya-config-inject"; + + /** + * Checks if injection is enabled on the given service. + * @param reference the service reference, not null. + * @return true, if enjection is enabled. + */ + boolean isInjectionEnabled(ServiceReference reference); + + /** + * Checks if injection is enabled on the given service. + * @param bundle the bundle, not null. + * @return true, if enjection is enabled. + */ + boolean isInjectionEnabled(Bundle bundle); + + /** + * Configures the passed instance. + * @param instance the instance, not null. + * @param <T> the input and return type. + * @param pid the target PID, not null. + * @param location the optional location + * @return the configured instance. + */ + <T> T configure(String pid, String location, T instance); + + /** + * Creates a suzpplier, which supplies events as created by the basic supplier, which are + * automatically configured, when supplying. + * @param supplier the base supplier, not null. + * @param pid the target PID, not null. + * @param location the optional location + * @param <T> the type + * @return a configuring supplier. + */ + <T> Supplier<T> getConfiguredSupplier(String pid, String location, java.util.function.Supplier<T> supplier); + + /** + * Creates a template implementing the annotated methods based on current configuration data. + * + * @param <T> the type of the template. + * @param templateType the type of the template to be created. + * @param pid the target PID, not null. + * @param location the optional location + * @return the configured template. + */ + <T> T createTemplate(String pid, String location, Class<T> templateType); + + /** + * Configures the passed instance. + * @param instance the instance, not null. + * @param <T> the input and return type. + * @param bundle the target bundle, not null. + * @return the configured instance. + */ + <T> T configure(Bundle bundle, T instance); + + /** + * Creates a suzpplier, which supplies events as created by the basic supplier, which are + * automatically configured, when supplying. + * @param supplier the base supplier, not null. + * @param bundle the target bundle, not null. + * @param <T> the type + * @return a configuring supplier. + */ + <T> Supplier<T> getConfiguredSupplier(Bundle bundle, java.util.function.Supplier<T> supplier); + + /** + * Creates a template implementing the annotated methods based on current configuration data. + * + * @param <T> the type of the template. + * @param templateType the type of the template to be created. + * @param bundle the target bundle, not null. + * @return the configured template. + */ + <T> T createTemplate(Bundle bundle, Class<T> templateType); +} +----------------------------------------------- + +NOTE: Injection hereby is based on the OSGI ConfigAdmin values only. To use Tamaya configuration you have to additionally +install the Tamaya common OSGI support as described in the previous sections. + +More details on Tamaya's injection API can be found in the corresponding link:mod_injection.html[API documentation]. + +=== Special OSGI Platform support + +==== Apache Karaf Shell + +Apache Tamaya provides a Karaf Shell Extension providing commands for performing several actions related +to Tamaya configuration. To use them, simply add the +org.apache.tamaya.ext:tamaya-osgi-karaf-shell+ bundle +to your OSGI runtime. The extension will add the following commands to your Karaf conaole (with prefix +tamaya+): + +[width="100%",frame="1",options="header",grid="all"] +|======= +|_Artifact_ |_Description_ |_Options_ + +| +tm_apply_config+ +| Show the current Tamaya configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_apply_config [options] pid +<b>ARGUMENTS</b> +<i>pid</i> The target OSGI component PID. +<b>OPTIONS</b> +<i>operationMode, -m, --opmode</i> Explicitly set (override) the operation mode to use. +<i>dryRun, -d, --dryrun</i> If set to true no OSGI configuration gets changed. +</pre> ++++ + +| +tm_backup_create+ +| Creates a backup of a current OSGI configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_backup_create [options] pid +<b>ARGUMENTS</b> +<i>pid</i> The target pid to backup. +<b>OPTIONS</b> +<i>--force, -f</i> Forces to (over)write a backup, even if one already exists. +</pre> ++++ + +| +tm_backup_delete+ +| Deletes the OSGI configuration backup of Tamya. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_backup_delete pid +<b>ARGUMENTS</b> +<i>pid</i> Allows to filter on the given PID. '*' removes all backups. +</pre> ++++ + +| +tm_backup_list+ +| List the backed-up OSGI configuration before Tamya applied changes. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_backup_list [pid] +<b>ARGUMENTS</b> +<i>pid</i> Allows to filter on the given PID. +</pre> ++++ + +| +tm_backup_restore+ +| Restores the OSGI configuration backup of Tamya and disabled the PID for Tamaya configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_backup_restore pid +<b>ARGUMENTS</b> +<i>pid</i> The target PID. '*' restores all backups. +</pre> ++++ + +| +tm_config+ +| Show the current Tamaya configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_config [options] +<b>OPTIONS</b> +<i>pi, -p, --pid</i> Apply filtering for the given OSGI component PID. +<i>section, -s, --section</i> A starting expression selecting the section to be filtered. +</pre> ++++ + +| +tm_enable+ +| Enables or disable Tamaya by default for all bundles/services (default: enabled=false). Disabling still allows to explicitly enable + bundles using 'tamaya-enable' manifest or OSGI config entries. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_enable enabled +<b>ARGUMENTS</b> +<i>enabled</i> The boolean value to enabled/disable Tamaya by default. +</pre> ++++ + +| +tm_enabled+ +| Check if Tamaya is currently by default enabled for all bundles/services (default: enabled=false). If disabled still Tamaya allows to + explicitly enable bundles using 'tamaya-enable' manifest or OSGI config entries. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_enabled +</pre> ++++ + +| +tm_history+ +| Gets the getHistory of changes Tamaya applied to the OSGI configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_history [options] [pid] +<b>ARGUMENTS</b> +<i>pid</i> Allows to filter on the given PID. +<i>--type, -t</i> Allows to filter the events types shown. +</pre> ++++ + +| +tm_history_delete+ +| Deletes the getHistory of changes Tamaya applied to the OSGI configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_history_delete pid +<b>ARGUMENTS</b> +<i>pid</i> Allows to filter on the given PID. +</pre> ++++ + +| +tm_history_delete_all+ +| Deletes the full getHistory of changes Tamaya applied to the OSGI configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_history_delete_all +</pre> ++++ + + +| +tm_history_maxsize+ +| Gets the maximal size of stored getHistory entries. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_history_maxsize +</pre> ++++ + +| +tm_history_maxsize_set+ +| Sets the maximal size of Tamaya getHistory entries. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_history_maxsize_set size +<b>ARGUMENTS</b> +<i>size</i>: The maximum number of entries in the getHistory. ++++ + +| +tm_info+ +| Show he current Tamaya status. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_info +</pre> ++++ + +| +tm_osgi_config+ +| Show the current OSGI configuration. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_osgi_config [options] pid +<b>ARGUMENTS</b> +<i>pid</i> The target OSGI component PID. +<b>OPTIONS</b> +<i>section, -s, --section</i>: A starting expression selecting the keys to be filtered. +</pre> ++++ + +| +tm_policy+ +| Get the current Tamaya overriding policy. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_policy +</pre> ++++ + +| +tm_policy_set+ +| Sets the current Tamaya operation policy. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_policy_set tm_policy_set +<b>ARGUMENTS</b> +<i>tm_policy_set</i>: The operation policy how Tamaya intercepts OSGI configuration. ++++ + +| +tm_propagate_updates+ +| Flag if Tamaya is automatically triggering OSGI config updates, when according Tamaya configuration changes. +| +++ +<pre> +<b>SYNTAX</b> +tm_propagate_updates ++++ + +| +tm_propagate_updates_set+ +| Configure if Tamaya is automatically triggering OSGI config updates, when according Tamaya configuration changes. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_propagate_updates_set enabled +<b>ARGUMENTS</b> +<i>enabled</i>: Set to true to enable Tamaya's updating trigger. +</pre> ++++ + +| +tm_property+ +| Get a Tamaya property. +| +++ +<pre><b>SYNTAX</b> +tamaya:tm_property [options] [key] +<b>ARGUMENTS</b> +<i>key</i>: The target property source id. +<b>OPTIONS</b> +<i>extended,e</i>: Also print extended property value attributes. +<i>propertysource, ps</i>: The target property source id. +</pre> ++++ + +| +tm_propertysource+ +| Show the current Tamaya entries of a propertysource. +| +++ +<pre><b>SYNTAX</b> +tamaya:tm_propertysource [propertysource] +<b>ARGUMENTS</b> +<i>propertysource</i>: The target property source id. ++++ + +| +tm_propertysources+ +| Get a list of currently registered propertysources. +| +++ +<pre> +<b>SYNTAX</b> +tamaya:tm_propertysources +</pre> ++++ + +|======= + +==== Apache Karaf Ferature + +Apache Tamaya provides a Karaf feature with all required dependencies +as +org.apache.tamaya.ext:tamaya-karaf-features:{tamaya-version}:features:xml+. + + + +==== Apache Felix Gogo Console + +Apache Tamaya also provides the same commands as described for _Karaf_, but executable in +plaing Gogo console as used by Apache Felix and Equinox as ++org.apache.tamaya.ext:tamaya-gogo-shell:{tamaya-version}+. Refer to the previous sections for +a detailed command description. \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_remote.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_remote.adoc b/content/documentation-new/extensions/mod_remote.adoc new file mode 100644 index 0000000..9c234f1 --- /dev/null +++ b/content/documentation-new/extensions/mod_remote.adoc @@ -0,0 +1,111 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Remote Configuration + +toc::[] + + +[[Remote]] +== Tamaya Remote Configuration (Extension Module) + +Tamaya _Remote_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _Remote_ provides support for reading configuration from remote resources. It provides +out-of-the-box support for reading scoped configuration from a Tamaya configuration server as +provided with the Tamaya _server_ module . + + +=== Compatibility + +The module is based on Java 7, so it will not run on Java 7 and beyond. + + +=== Installation + +To use remote support you only must add the corresponding dependency to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-remote</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== Reading Remote configuration from a Tamaya Configuration Server + +The remote module allows reading JSON formatted configuration as provided by the Tamaya _server_ extension . The JSON +format used looks as follows: + +[source, json] +----------------------------------------------- +{ + "java.vendor.url": "http://java.oracle.com/", + "java.vendor.url.bug": "http://bugreport.sun.com/bugreport/", + "java.vm.info": "mixed mode", + "java.vm.name": "Java HotSpot(TM) 64-Bit Server VM", + "java.vm.specification.name": "Java Virtual Machine Specification", + "java.vm.specification.vendor": "Oracle Corporation", + "java.vm.specification.version": "1.8", + "java.vm.vendor": "Oracle Corporation", + "java.vm.version": "25.45-b02", + "sun.arch.data.model": "64", + "sun.boot.class.path": "C:\apps\jdk18\jre\lib\resources.jar;C:\apps\jdk18\jre\lib\rt.jar;C:\apps\jdk18\jre\lib\sunrsasign.jar;C:\apps\jdk18\jre\lib\jsse.jar;C:\apps\jdk18\jre\lib\jce.jar;C:\apps\jdk18\jre\lib\charsets.jar;C:\apps\jdk18\jre\lib\jfr.jar;C:\apps\jdk18\jre\classes", + "sun.boot.library.path": "C:\apps\jdk18\jre\bin", + "sun.cpu.endian": "little", + "sun.cpu.isalist": "amd64", + "sun.desktop": "windows", + "sun.io.unicode.encoding": "UnicodeLittle", + "sun.java.command": "com.intellij.rt.execution.application.AppMain org.apache.tamaya.examples.remote.server.Start", + "sun.java.launcher": "SUN_STANDARD", + "sun.jnu.encoding": "Cp1252", + "sun.management.compiler": "HotSpot 64-Bit Tiered Compilers", + "sun.os.patch.level": "", + "_class": "org.apache.tamaya.functions.FilteredConfiguration", + "_info.filter": "java.v,sun", + "_info.format": "application/json", + "_info.timestamp": "1441463200571", + "_timestamp": "1441463200571", + "_type": "Configuration" +} +----------------------------------------------- + +Basically there are no constraints about they keys provided. By default Tamaya uses keys prefixed with ++'_'+ to identify meta-data entries, but this is not a required precondition. + +Finally such a remote configuration can be easily integrated by inheriting from the provided base +class. Hereby a default ordinal must be defined and the +protected Collection<URL> getAccessURLs()+ +method must be implemented to define the URL from where the configuration should be accessible. Hereby +multiple URLs can be provided, which are accesed in order as provided by the collection's iterator. The +first accessible URL determines the configuration read. + +[source, java] +----------------------------------------------- +public class RemotePropertySource extends BaseRemotePropertySource{ + + @Override + protected Collection<URL> getAccessURLs() { + try { + String configServerUrl = System.getenv("CONFIG_SERVER"); + if(configServerUrl==null){ + configServerUrl = System.getProperty("configServer"); + } + if(configServerUrl==null){ + configServerUrl = "http://localhost:8888/config?scope=CLIENT&scopeId={clientId}&format=application/json"; + } + System.out.println("Reading config from " + configServerUrl.replace("{clientId}", Client.getClientId())); + return Arrays.asList(new URL[]{new URL(configServerUrl.replace("{clientId}", Client.getClientId()))}); + } catch (MalformedURLException e) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, "Failed to configure remote config location,", e); + return Collections.emptySet(); + } + } + +} +----------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_resolver.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_resolver.adoc b/content/documentation-new/extensions/mod_resolver.adoc new file mode 100644 index 0000000..ad95d14 --- /dev/null +++ b/content/documentation-new/extensions/mod_resolver.adoc @@ -0,0 +1,131 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Resolver + +[[Resolver]] +== Tamaya Resolver (Extension Module) + +Tamaya _Resolver_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _Resolver_ is an extension module. Refer to the link:../extensions.html[extensions documentation] +for further details about modules. + +Tamaya Resolver provides a dynamic resolution mechanism, which allows to use UNIX-styled (+${...}+ placeholder +expressions in your configuration values. The resolver hereby supports transitive resolution and also prevents +cycles to loop endlessly. + + +=== Compatibility + +The module is based on Java 7, so it can be used with Java 7 and beyond. + + +=== Installation + +To benefit from dynamic value resolution you only must add the corresponding dependency to your module: + +[source, xml, subs="verbatim,attributes"] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-resolver</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + +The module automatically registers an according +PropertyFilter+ that is automatically called, whenever a value +is accessed. + + +=== Available Resolvers + +Currently the module defines the following resolvers: + +.Available Resolvers +[cols="<.1,<.2,<.1"] +|======= +| _Expression_ +| _Description_ +| _Example_ + +| +conf:<configKey>+ +| Reads another configKey and replaces the expression with the value found. +| conf-ref=${conf:anotherConf.entryKey} + +| +resource:<resourceRef>+ +| Reads a resource from the current classpath and replaces the expression with the given text content. +| cp-ref=${resource:Testresource.txt} + +| +file:<fileRef>+ +| Reads a resource from the current classpath and replaces the expression with the given text content. +| file-ref=${file:c:\myFile.txt} + +|+url:<url>+ +|Reads an URL and replaces the expression with the given text content. +| url-ref=${url:http://www.google.com} + +|======= + + +=== SPI: Implementing your own Resolvers + +The module also provides a small but powerful SPI for adding your own resolver implementations. Basically the +first and most important thing to do is implementing the +ExpressionResolver+ interface: + +.Implementing a Custom Resolver +[source, java] +----------------------------------------------- +public class PwdDecrypter implements ExpressionResolver { + + @Override + public String getResolverPrefix() { + return "decrypt:"; + } + + @Override + public String evaluate(String expression) { + return decrypt(expression); + } + + private String decrypt(String s) { + ... + } +} +----------------------------------------------- + +Basically that is all you must do, after having registered the class with the +ServiceLoader+ it will be found +and loaded by the implementation. With that all expressions that start with the given prefix are passed to the +resolver, so all the following expressions will be sent to the implementation: + +[source,listing] +----------------------------------------------- +blabla ${decrypt:myname} +blabla ${decrypt:myname} foo blabla ${decrypt:myname} +----------------------------------------------- + +Hereby evaluation is repeated until no further change of values could be detetced. In case of a endless loop +the evaluation is broken after a (configurable) number of cycles. + + +Under the hood instances of +ExpressionResolver+ are managed by an implementation of the +ExpressionEvaluator+ +interface: + +[source, java] +----------------------------------------------- +public interface ExpressionEvaluator { + /** + * Evaluates the current expression. + * @param key the key, not null. + * @param value the value to be filtered/evaluated. + * @return the filtered/evaluated value, including null. + */ + String evaluateExpression(String key, String value); +} +----------------------------------------------- + +Implementing and registering this interface gives you full control, but in most cases you should be fine with +the default implementation in place. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_resources.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_resources.adoc b/content/documentation-new/extensions/mod_resources.adoc new file mode 100644 index 0000000..2e06053 --- /dev/null +++ b/content/documentation-new/extensions/mod_resources.adoc @@ -0,0 +1,167 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Resources + +[[Resources]] +== Tamaya Resources (Extension Module) + +Tamaya _Resources_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _Resources_ defines some additional tools to locate resources in your classpath or file system based on +descriptive ant-styled resource patterns. + + +=== Compatibility + +The module is based on Java 7, so it can be used with Java 7 and beyond. + + +=== Installation + +To use this module add the following dependency: + +[source, listing, subs="verbatim,attributes"] +----------------------------------------------- +<dependency> + <grooupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-resources</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== Usage + +The module's main entry point is the singleton class +org.apache.tamaya.resource.ConfigResources+. This class +provides access to a +ResourceResolver+ instance: + +[source,java] +----------------------------------------------- +ResourceResolver resolver = ConfigResources.getResourceResolver(); +----------------------------------------------- + +[source,java] +----------------------------------------------- +public interface ResourceResolver { + Collection<URL> getResources(Collection<String> expressions) {...} + Collection<URL> getResources(String... expressions) {...} + Collection<URL> getResources(ClassLoader classLoader, String... expressions){...} + Collection<URL> getResources(ClassLoader classLoader, Collection<String> expressions); +} +----------------------------------------------- + +Hereby the methods allow to resolve expressions to a collection of URLs. In case the expression is also targeting the +current classpath the target +ClassLoader+ to be used can be passed additionally. + +The default implementation provides resource resolution mechanism similar to the functionality offered by Spring. +So by default resources can be looked up + +* from files +* from the classpath +* optionally ant-styled expressions can be used. + + +=== Examples + +There are numerous ways how a resource pattern can be defined. Following the most important variants +are listed: + +[source,listing] +----------------------------------------------- +// explicitly searching the file system +file:myroot/aa?a/*.file +file:myroot/b*/b?/*.file +file:myroot/**/*.file + +// explicitly searching the classpath +classpath:myroot/**/*.file +classpath:javax/annotation/*.class +classpath:javax/**/sql/*.class +classpath:javax/annotation/**/R*.class +classpath:javax/annotation/R?so*.class +classpath:META-INF/maven/org.apache.geronimo.specs/**/* + +// search both classpath and files +javax/annotation/*.class +javax/**/sql/*.class +javax/annotation/**/R*.class +javax/annotation/R?so*.class +META-INF/maven/org.apache.geronimo.specs/**/* +myroot/**/*.file +myroot/aa?a/*.file +myroot/b*/b?/*.file +----------------------------------------------- + +Summarizing the resources module provides useful functionality that helps to locate resources on the file system and +in the classpath. This can be used to implement +PropertySourceProvider+ implementations that are based on +corresponding resource path patterns instead of concrete files. + + +=== Overall Usage Example + +Given the functionality we can easily implement a +PropertySourceProvider+ that reads all files from a classpath +location, hereby traversing down all folders: + + +[source, java] +------------------------------------------------------------- +public class PathBasedPropertySourceProvider implements PropertySourceProvider { + + @Override + public Collection<PropertySource> getPropertySources() { + List<PropertySource> propertySources = new ArrayList<>(); + Collection<URL> resources = ConfigResources.getResourceResolver().getResources("META-INF/cfg/**/*.properties"); + for(URL url:resources){ + Properties props = new Properties(); + try(InputStream is = url.openStream()){ + props.load(is); + propertySources.add(new PropertiesBasedPropertySource(url.toString(), props)); + } + catch(Exception e){ + e.printStackTrace(); + } + } + + return propertySources; + } + + private final static class PropertiesBasedPropertySource implements PropertySource { + private String name; + private Map<String,String> properties = new HashMap<>(); + + public PropertiesBasedPropertySource(String name, Properties props) { + this.name = name; + props.forEach((k,v) -> this.properties.put(k.toString(), v.toString())); + } + + @Override + public String getName() { + return name; + } + + @Override + public String get(String key) { + return properties.get(key); + } + + @Override + public Map<String, String> getProperties() { + return properties; + } + } +} +------------------------------------------------------------- + + +=== SPI + +The +ResourceResolver+ that is returned by the +ConfigResources+ singleton is determined by the +current +ServiceContext+, by default you can replace the default implementation by registering an +alternate implementation with an overriding +@Priority+ annotation added using the +ServiceLoader+. + +Additionally a +BaseResourceResolver+ class can be used to reduce the amount of code to be written +on your own. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_server.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_server.adoc b/content/documentation-new/extensions/mod_server.adoc new file mode 100644 index 0000000..52081b6 --- /dev/null +++ b/content/documentation-new/extensions/mod_server.adoc @@ -0,0 +1,239 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Configuration Server + +toc::[] + + +[[Server]] +== Tamaya Configuration Server (Extension Module) + +Tamaya _Server_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +The Tamaya _Server_ module provides support for providing scoped configuration using a http server serving JSON formatted +configuration properties. + + +=== Compatibility + +The module is based on Java 7, so it will not run on Java 7 and beyond. + + +=== Installation + +To benefit from configuration server support you only must add the corresponding dependency to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-server</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== Providing configuration using the Tamaya Built-in Configuration Server + +The most simple way for providing configuration is to start the internal server: + +[source, java] +----------------------------------------------- +// using context path: '/', port 8085 +org.apache.tamaya.server.Server.start(); + +// optionally pass the root context path and/or port: +// org.apache.tamaya.server.Server.start(8088); +// org.apache.tamaya.server.Server.start("/appconf", 7787); +----------------------------------------------- + +This will start a simple server instance that serves the following URL patterns: + +* +GET ${CONTEXT}/config+ provides access to the full configuration tree. +* +GET ${CONTEXT}/config/filtered/${path}+ let you filter the configuration returned using regular expression (comma separated). + E.g. +${CONTEXT}/config/filtered/java,sun+ will return all configuration entries starting with _java_ and _sun_. + +Additionally the server module has the following options implemented, which can be passed as additional, optional +parameters: + +* +format+ allows to define the target format. By default the +ACCEPT+ header of the http request is checked, but this + setting can be explicitly controlled by passing this parameter explicitly. The value is the expected MIME type to be + returned. By default the service supports the following types: + ** text/html + ** text/plain + ** application/xml + ** application/json + + +=== Using the Configuration Servlets + +You can also register a servlet, e.g. as follows; + +---------------------------------------------------------- +<servlet> + <servlet-name>config-servlet</servlet-name> + <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class> + <init-params> + <init-param key="javax.ws.rs.Application">org.apache.tamaya.server.Server$ResourceLoader</init-param> + </init-params> +</servlet> +---------------------------------------------------------- + + +==== Formatting used by Default + +The server module formats the configuration returned by default in the following variants: + +.Formatting for +text/json+ + +[source, json] +----------------------------------------------- +{ + "java.vendor.url": "http://java.oracle.com/", + "java.vendor.url.bug": "http://bugreport.sun.com/bugreport/", + "java.vm.info": "mixed mode", + "java.vm.name": "Java HotSpot(TM) 64-Bit Server VM", + "java.vm.specification.name": "Java Virtual Machine Specification", + "java.vm.specification.vendor": "Oracle Corporation", + "java.vm.specification.version": "1.8", + "java.vm.vendor": "Oracle Corporation", + "java.vm.version": "25.45-b02", + "sun.arch.data.model": "64", + "sun.boot.class.path": "C:\apps\jdk18\jre\lib\resources.jar;C:\apps\jdk18\jre\lib\rt.jar;C:\apps\jdk18\jre\lib\sunrsasign.jar;C:\apps\jdk18\jre\lib\jsse.jar;C:\apps\jdk18\jre\lib\jce.jar;C:\apps\jdk18\jre\lib\charsets.jar;C:\apps\jdk18\jre\lib\jfr.jar;C:\apps\jdk18\jre\classes", + "sun.boot.library.path": "C:\apps\jdk18\jre\bin", + "sun.cpu.endian": "little", + "sun.cpu.isalist": "amd64", + "sun.desktop": "windows", + "sun.io.unicode.encoding": "UnicodeLittle", + "sun.java.command": "com.intellij.rt.execution.application.AppMain org.apache.tamaya.examples.remote.server.Start", + "sun.java.launcher": "SUN_STANDARD", + "sun.jnu.encoding": "Cp1252", + "sun.management.compiler": "HotSpot 64-Bit Tiered Compilers", + "sun.os.patch.level": "", + "_class": "org.apache.tamaya.functions.FilteredConfiguration", + "_info.filter": "java.v,sun", + "_info.format": "application/json", + "_info.timestamp": "1441463200571", + "_timestamp": "1441463200571", + "_type": "Configuration" +} +----------------------------------------------- + + +.Formatting for +application/xml+ + +[source, xml] +----------------------------------------------- +<configuration> + <entry key="java.vendor.url">http://java.oracle.com/</entry> + <entry key="java.vendor.url.bug">http://bugreport.sun.com/bugreport/</entry> + <entry key="java.vm.info">mixed mode</entry> + <entry key="java.vm.name">Java HotSpot(TM) 64-Bit Server VM</entry> + <entry key="java.vm.specification.name">Java Virtual Machine Specification</entry> + <entry key="java.vm.specification.vendor">Oracle Corporation</entry> + <entry key="java.vm.specification.version">1.8</entry> + <entry key="java.vm.vendor">Oracle Corporation</entry> + <entry key="java.vm.version">25.45-b02</entry> + <entry key="sun.arch.data.model">64</entry> + <entry key="sun.boot.class.path">C:\apps\jdk18\jre\lib\resources.jar;C:\apps\jdk18\jre\lib\rt.jar;C:\apps\jdk18\jre\lib\sunrsasign.jar;C:\apps\jdk18\jre\lib\jsse.jar;C:\apps\jdk18\jre\lib\jce.jar;C:\apps\jdk18\jre\lib\charsets.jar;C:\apps\jdk18\jre\lib\jfr.jar;C:\apps\jdk18\jre\classes</entry> + <entry key="sun.boot.library.path">C:\apps\jdk18\jre\bin</entry> + <entry key="sun.cpu.endian">little</entry> + <entry key="sun.cpu.isalist">amd64</entry> + <entry key="sun.desktop">windows</entry> + <entry key="sun.io.unicode.encoding">UnicodeLittle</entry> + <entry key="sun.java.command">com.intellij.rt.execution.application.AppMain org.apache.tamaya.examples.remote.server.Start</entry> + <entry key="sun.java.launcher">SUN_STANDARD</entry> + <entry key="sun.jnu.encoding">Cp1252</entry> + <entry key="sun.management.compiler">HotSpot 64-Bit Tiered Compilers</entry> + <entry key="sun.os.patch.level"></entry> + <entry key="_class">org.apache.tamaya.functions.FilteredConfiguration</entry> + <entry key="_info.filter">java.v,sun</entry> + <entry key="_info.format">application/xml</entry> + <entry key="_info.timestamp">1441463383687</entry> + <entry key="_timestamp">1441463383687</entry> + <entry key="_type">Configuration</entry> +</configuration> +----------------------------------------------- + + +.Formatting for +text/plain+ + +[source, text] +----------------------------------------------- + +Configuration: + java.vendor.url: http://java.oracle.com/, + java.vendor.url.bug: http://bugreport.sun.com/bugreport/, + java.vm.info: mixed mode, + java.vm.name: Java HotSpot(TM) 64-Bit Server VM, + java.vm.specification.name: Java Virtual Machine Specification, + java.vm.specification.vendor: Oracle Corporation, + java.vm.specification.version: 1.8, + java.vm.vendor: Oracle Corporation, + java.vm.version: 25.45-b02, + sun.arch.data.model: 64, + sun.boot.class.path: C:\apps\jdk18\jre\lib\resources.jar;C:\apps\jdk18\jre\lib\rt.jar;C:\apps\jdk18\jre\lib\sunrsasign.jar;C:\apps\jdk18\jre\lib\jsse.jar;C:\apps\jdk18\jre\lib\jce.jar;C:\apps\jdk18\jre\lib\charsets.jar;C:\apps\jdk18\jre\lib\jfr.jar;C:\apps\jdk18\jre\classes, + sun.boot.library.path: C:\apps\jdk18\jre\bin, + sun.cpu.endian: little, + sun.cpu.isalist: amd64, + sun.desktop: windows, + sun.io.unicode.encoding: UnicodeLittle, + sun.java.command: com.intellij.rt.execution.application.AppMain org.apache.tamaya.examples.remote.server.Start, + sun.java.launcher: SUN_STANDARD, + sun.jnu.encoding: Cp1252, + sun.management.compiler: HotSpot 64-Bit Tiered Compilers, + sun.os.patch.level: , + _class: org.apache.tamaya.functions.FilteredConfiguration, + _info.filter: java.v,sun, + _info.format: text/plain, + _info.timestamp: 1441463082020, + _timestamp: 1441463082021, + _type: Configuration +----------------------------------------------- + + +.Formatting for +application/html+ + +[source, html] +----------------------------------------------- +<html> +<head><title>System Configuration</title></head> +<body> +<h1>Sysem Configuration</h1> +<p>This view shows the system configuration of devbox-win at Sat Sep 05 16:30:59 CEST 2015.</p><pre> +Configuration: + java.vendor.url: http://java.oracle.com/, + java.vendor.url.bug: http://bugreport.sun.com/bugreport/, + java.vm.info: mixed mode, + java.vm.name: Java HotSpot(TM) 64-Bit Server VM, + java.vm.specification.name: Java Virtual Machine Specification, + java.vm.specification.vendor: Oracle Corporation, + java.vm.specification.version: 1.8, + java.vm.vendor: Oracle Corporation, + java.vm.version: 25.45-b02, + sun.arch.data.model: 64, + sun.boot.class.path: C:\apps\jdk18\jre\lib\resources.jar;C:\apps\jdk18\jre\lib\rt.jar;C:\apps\jdk18\jre\lib\sunrsasign.jar;C:\apps\jdk18\jre\lib\jsse.jar;C:\apps\jdk18\jre\lib\jce.jar;C:\apps\jdk18\jre\lib\charsets.jar;C:\apps\jdk18\jre\lib\jfr.jar;C:\apps\jdk18\jre\classes, + sun.boot.library.path: C:\apps\jdk18\jre\bin, + sun.cpu.endian: little, + sun.cpu.isalist: amd64, + sun.desktop: windows, + sun.io.unicode.encoding: UnicodeLittle, + sun.java.command: com.intellij.rt.execution.application.AppMain org.apache.tamaya.examples.remote.server.Start, + sun.java.launcher: SUN_STANDARD, + sun.jnu.encoding: Cp1252, + sun.management.compiler: HotSpot 64-Bit Tiered Compilers, + sun.os.patch.level: , + _class: org.apache.tamaya.functions.FilteredConfiguration, + _info.filter: java.v,sun, + _info.format: text/html, + _info.timestamp: 1441463459653, + _timestamp: 1441463459654, + _type: Configuration +</pre> +</body> +</html> +----------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_spring.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_spring.adoc b/content/documentation-new/extensions/mod_spring.adoc new file mode 100644 index 0000000..798431b --- /dev/null +++ b/content/documentation-new/extensions/mod_spring.adoc @@ -0,0 +1,176 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Spring Integration + +toc::[] + + +[[Spring]] +== Tamaya Spring Integration (Extension Module) + +Tamaya _Spring_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _Spring_ currently provides full integration with Spring and Spring Boot: + +* A Spring +@Configuration+ implementation that also provides a Tamaya based version of + +org.springframework.context.support.PropertySourcesPlaceholderConfigurer+. +* +org.apache.tamaya.integration.spring.TamayaEnvironment+ is the Tamaya based implementation of the Spring + +Environment+ interface. +* +TamayaSpringPropertySource+ implements an additional Spring +PropertySource+. +* Finally +org.apache.tamaya.integration.spring.SpringConfigInjectionPostProcessor+ implements a Bean +PostProcessor+, + which adds all the fully fledged Tamaya configuration capabilities to Spring. + + +=== Compatibility + +Both modules are based on Java 8, so they will run on Java 8 and beyond. The extension shown here works in +Spring Framework as well as Spring Boot. + + +=== Installation + +To benefit from Tamaya Spring integration add the following dependencies to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-spring</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== Registering Tamaya Spring Configuration + +Basically to activate the Tamaya Spring support the most simple thing is to a enable the Tamaya package for being +scanned for Spring components, e.g. using by annotation: + +[source, java] +-------------------------------------------------------- +@SpringBootApplication +@ComponentScan({"org.apache.tamaya.integration.spring"}) +public class SampleWebFreeMarkerApplication { + + public static void main(String[] args) throws Exception { + SpringApplication.run(SampleWebFreeMarkerApplication.class, args); + } + +} +-------------------------------------------------------- + +Of course, you can still use Spring's XML configuration in a similar way: + +[source, xml] +-------------------------------------------------------- +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <context:annotation-config /> + <context:component-scan base-package="org.apache.tamaya.integration.spring"/> + + ... + +</beans> +-------------------------------------------------------- + + +Though not recommended you can explicitly register the Tamaya related beans in your context configuration by hand: +files: + +[source, xml] +-------------------------------------------------------- +<bean id="tamayaInjectionProcessor" name="tamayaInjectionProcessor" class="org.apache.tamaya.integration.spring.SpringConfigInjectionPostProcessor"/> +<bean id="tamayaConfigProvider" name="tamayaConfigProvider" class="org.apache.tamaya.integration.spring.TamayaSpringConfig"/> +-------------------------------------------------------- + + +=== Configuring your Context + +After activation you can use Tamaya as a backend for property resolution, e.g. +propertyValue+ +is resolved from the current Tamaya configuration. See example below: + +[source, xml] +-------------------------------------------------------- +<bean id="configuredBean" name="configuredBean" class="org.apache.tamaya.integration.spring.ConfiguredSpringBean"> + <property name="message" value="${propertyValue}"/> +</bean> +-------------------------------------------------------- + + +=== Configuring your Beans + +Similarly you can inject any kind of configuration as supported by Tamaya into your Spring managed beans: + +[source, java] +-------------------------------------------------------- +@ConfigDefaultSections("app.root") // optional <1> +@Component +public class ConfiguredSpringBean { + + @Value("${application.message:Hello World}") <2> + private String message; + + @Autowired + private Environment env; + + @Config(value = "alternateMessage", required = false) <3> + private String anotherMessage = "N/A"; + + @Config("java.version") + private String javaVersion; + + @Config(value={"number", "testNum", "[notavailable]"}, defaultValue="23") <4><5> + private int testNumber; + + ... +} +-------------------------------------------------------- + +<1> You can configure default section prefixes. This is an optional feature. +<2> Tamaya does not require you to change your code. You can still work with + Spring injection for your configuration, but Tamaya will override Spring + configuration by default. +<3> You can also define entries as optional, which allows you to perform + default inialization using Java idoms. +<4> Tamaya allows you to define an ordered list of key candidates, which are + combined with the section prefix, if present, to the full keys. Keys added + in brackets ([]) are interpreted as absolute keys, so the example above + the key candidate list evaluates to +app.root.number", "app.root.testNum", + "notavailable"+. +<5> You can configure default values used, if no other value can be evaluated + for the given keyset. + +Summarizing you get all the nice features of Tamaya out of the box running +with your Spring code. + +=== Working with Dynamic Values + +Integration into Spring also includes for support for _dynamic values_: + +[source, java] +-------------------------------------------------------- +@Config(value = "foreground.color", required = false, defaultValue = "#DDDDDD") +private DynamicValue<Color> foregroundColor; +-------------------------------------------------------- + +Dynamic values are a very flexible mechanism for managing configuration changes. +You can even use an update policy to define how you want to handle configuration +changes for your configuration parameter: + +[source, java] +-------------------------------------------------------- +foregroundColor.setUpdatePolicy(UpdatePolicy.IMMEDEATE); +foregroundColor.addPropertyChangeListener(() -> { + System.out.println("New forground color: " + foregroundColor.get(); +}); +-------------------------------------------------------- + +IMPORTANT: For a full description of Tamaya's injection API please + refer to the link:extensions/mod_injection.html[corresponding documentation]. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_usagetracker.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_usagetracker.adoc b/content/documentation-new/extensions/mod_usagetracker.adoc new file mode 100644 index 0000000..e0bd8c7 --- /dev/null +++ b/content/documentation-new/extensions/mod_usagetracker.adoc @@ -0,0 +1,161 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Usage Tracking + +toc::[] + + +[[UsageTracker]] +== Tamaya Usage Tracking (Extension Module) + +Tamaya _UsageTracker_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== What functionality this module provides ? + +Tamaya _UsageTracker_ allows to record and count the configuration access and consumer locations in your local +VM. + + +=== Compatibility + +The module is based on Java 7, so it can be used with Java 7 and beyond. + + +=== Installation + +To use Tamaya _usagetracker_ you only must add the corresponding dependency to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-usagetracker</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== Tracking Configuration Access + +The model module also allows tracking which code accesses configuration properties or configuration parameters. +It checks the stacktrace to evaluate the calling code location, hereby any unwanted packages can be implicitly +ommitted from the stacktrace. Also the maximal length of the stacktrace retained can be constraint in length. +The usages are recorded as +Usage+ instances. Hereby for each parameter accessed a corresponding +Usage+ +instance is created. It can be accessed by calling +Usage ConfigUsageStats.getUsage(String key)+. Usage +statistics for calling +Configuration.getProperties()+ can be obtained calling +Usage getUsageAllProps();+. + +Usage tracking is disabled by default. It can be enabled by calling +ConfigUsageStats.enableUsageTracking(true);+. ++ConfigUsageStats.isUsageTrackingEnabled()+ returns the current tracking status. + +The +Usage+ class itself provides access to further fainer grained usage data (+AccessDetail+) containing: + +* the access point (+fqn.ClassName#method(line: xxx)+). +* the number of accesses +* the first an last access +* the values read +* the access stacktrace (filtered by ignored packages). + +[source,java] +----------------------------------------------------------- +public final class Usage { + [...] + public String getKey(); + public void clearMetrics(); + public int getReferenceCount(); + public int getUsageCount(); + public Collection<AccessDetail> getAccessDetails(Class type); + public Collection<AccessDetail> getAccessDetails(Package pack); + public Collection<AccessDetail> getAccessDetails(String lookupExpression); + public Collection<AccessDetail> getAccessDetails(); + public void trackUsage(String value); + public void trackUsage(String value, int maxTraceLength); + + + public static final class AccessDetail { + [...] + public void clearStats(); + public long trackAccess(String value); + public long getAccessCount(); + public String getAccessPoint(); + public long getFirstAccessTS(); + public long getLastAccessTS(); + public String[] getStackTrace(); + public Map<Long, String> getTrackedValues(); + } + +} +----------------------------------------------------------- + +With +ConfigUsageStats.clearUsageStats()+ the collected statistics can be reset at any time. Summarizing the main +singleton for configuration statistics is defined as follows: + +[source,java] +----------------------------------------------------------- +public final class ConfigUsageStats{ + public static Set<String> getIgnoredUsagePackages(); + public static void addIgnoredUsagePackages(String... packageName); + public static void enableUsageTracking(boolean enabled); + public static Usage getUsage(String key); + public static Collection<Usage> getUsages(); + public static void clearUsageStats(); + public static Usage getUsageAllProperties(); + public static boolean isUsageTrackingEnabled(); + public static String getUsageInfo(); +} +----------------------------------------------------------- + + +==== Customizing the Stacktrace for Usage Reporting + +The stacktrace tracked by the system can be customized in several ways: + +* +ConfigUsageStats.addIgnoredPackageNames(String...)+ allows to add additional ignored package names. +* With +Usage.setMaxTraceLength(int)+ the maximal size of the stacktraces logged can be set. Setting a + negative value will disable stacktrace logging completelely. + + +=== Accessing Usage Statistics + +Bascially usage statistics are available in two forms: + +* The +Usage/AccessDetail+ object tree can be accessed programmatically from the +ConfigUsageStats+ + singleton. +* With +ConfigUsageStats.getUsageInfo()+ also a textual representation of the usage statistics + can be obtained, as illustrated below (a snipped from the current test output): + +[source,listing] +----------------------------------------------------------- +Apache Tamaya Configuration Usage Metrics +========================================= +DATE: Sat Apr 30 21:51:09 CEST 2016 + +220 <<all>>: + - 220 <unknown/filtered/internal> , first=Sat Apr 30 21:51:09 CEST 2016, last=Sat Apr 30 21:51:09 CEST 2016 +3 java.version: + - 2 test.model.TestConfigAccessor#readProperty(line:43), first=Sat Apr 30 21:51:09 CEST 2016, last=Sat Apr 30 21:51:09 CEST 2016 + - 1 <unknown/filtered/internal> , first=Sat Apr 30 21:51:09 CEST 2016, last=Sat Apr 30 21:51:09 CEST 2016 + +----------------------------------------------------------- + + +=== Auto-Documentation of Classes with Configuration Injection + +A special feature of this module is that it observes +ConfigEvent+ published through Tamaya'as event channel +(+tamaya-events+ module). If no metaconfiguration model is found the model manager by default automatically creates +models for all injected instances on the fly. In the case of CDI integration this happens typically during deployment +time, since CDI initializes during deployment time. Other runtime platforms, such as OSGI, may have rather different +behaviour. Nevertheless this means that after your system has been started you should have access to a complete +set of +ConfigModel+ instances that automatically document all the classes in your system that consume configuration +(through injection). + + +== UsageTracker Module SPI + +=== The ConfigUsageStatsSpi + +The methods for managing and tracking of configuration changes are similarly delegated to an +implementation of the +org.apache.tamaya.model.spi.ConfigUsageStatsSpi+ SPI. +By implementing this SPI and registerting it with the +ServiceContext+ the usage tracking +logic can be adapted or replaced. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_validation.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_validation.adoc b/content/documentation-new/extensions/mod_validation.adoc new file mode 100644 index 0000000..5b239cb --- /dev/null +++ b/content/documentation-new/extensions/mod_validation.adoc @@ -0,0 +1,104 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Configuration Validation + +toc::[] + + +[[Validation]] +== Tamaya Validation: Validating Configuration (Extension Module) + +Tamaya _Validation_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== Overview + +Tamaya _Validation_ adds support to validate a configuration against a set of rules +defined in a Tamaya Metaconfiguration XML file. + + +=== Compatibility + +The module is based on Java 7, so it will run on Java 7 and beyond. + + +=== Installation + +To activate configuration _validation_ you only must add the corresponding dependency to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-validation</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + +The component will extend Tamaya's +tamaya-metamodel+ module and adds an additional meta provider ruleset +so validation rules can also be added to the default meta configuration XML file as separate sections. + + +=== Usage + +This module expects meta-configuration to be located at the following locations. Hereby multiple files +are supported: + +[source, text] +----------------------------------------------- +-Dtamaya-validation=<an URL> // any resolvable URL +./tamaya-validation-*.xml // file +META-INF/tamaya-validation-*.xml // classpath (multiple entries-possible) +----------------------------------------------- + + +=== The Validation XML Format + +The configuration validation is defined by simple configuration meta-data entries. + +[source, xml] +----------------------------------------------- +<configuration-validation> + ... + <provider>The Validation Provider</provider> <!-- optional --> + <section name="org.mycompany"> + <section name="security" required="true"> + <description>The description of ma area.</description> + </section> + </section> + <section name="minimal"/> + <section name="validated.sections" at-least="1"> + <section name="customValidated" validator="myFQValidatorClassName"/> + <section name="withParams" > + <param name="int" type="int"/> + <param name="aText" expression="[a|b|c]" required="true"/> + <param name="aValidatedText" validator="myValidatorClass"> + <description>This kind of params are more complex...</description> + </param> + </section> + </section> + <validator class="a,b,c,MyGlobalValidator"/> +</configuration-validation> +----------------------------------------------- + + +==== The Example Explained + +* The *provider* entry is used for generating validation message, when a validation fails. +* Section itself can be recursively defined, where each level can have it's own validations. +* Sections added, but without validation rules are _defined_ section. Configuration outside of + defined sections can be flagged out using WARNING messages. +* Sections can be _reuired_ and additionally also _validated_. +* There is also the possibility to register global validators, which are called by the validation + logic once a configuration has been completely loaded. + +Similar to sections also parameters can be validated: + +* they can be marked as _required_ +* they can have a certain type, meaning they must be convertible to the given type +* they can have an additional custom validator. +* they can have an optional description for error analysis and error output. + +Similar to section parameters that are not defined, but encountered may be flagged out with +a WARNING message. http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_vertx.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_vertx.adoc b/content/documentation-new/extensions/mod_vertx.adoc new file mode 100644 index 0000000..eef576b --- /dev/null +++ b/content/documentation-new/extensions/mod_vertx.adoc @@ -0,0 +1,188 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Integration for Vertx + +toc::[] + + +[[JNDI]] +== Integration with Vertx (Extension Module) +Tamaya _JNDI_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + +=== What functionality this module provides ? + +Tamaya _Vertx_ provides configuration services that can be used in a Vertx environment: + +* +AbstractConfiguredVerticle+ defines a subclass extending +AbstractVerticle+, which allows you to + use Tamaya Injection API. +* Additionally you deply a +ConfigVerticle+, which registers services to access configuration + using asynchronous event bus. + + +=== Compatibility + +The module requires Java 8, so it will not run on Java 7. + + +=== Installation + +To use Tamaya's _Vertx_ support you only must add the corresponding dependency to +your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-vertx-alpha</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + + +=== The Functionality Provided + +NOTE: This module is in alpha state. Please give feedback via our JIRA, so we can improve it. + + +==== Extending AbstractConfiguredVerticle + +Main artifact is the +AbstractConfiguredVerticle+ class, which implements a +base verticle class for Vertx: + +[source, java] +----------------------------------------------- +public abstract class AbstractConfiguredVerticle extends AbstractVerticle{ + + private Configuration configuration; + + public AbstractConfiguredVerticle() { + configure(); + } + + public Configuration getConfiguration(){ + if(this.configuration==null){ + this.configuration = ConfigurationProvider.getConfiguration(); + } + return this.configuration; + } + + public void setConfiguration(Configuration configuration){ + this.configuration = configuration; + configure(); + } + + protected void configure(){ + ConfigurationInjection.getConfigurationInjector().configure(this, getConfiguration()); + } + + protected final String getConfigProperty(String key); + protected final String getConfigPropertyOrDefault(String key, String defaultValue); + protected final <T> T getConfigProperty(String key, Class<T> type); + protected final <T> T getConfigPropertyOrDefault(String key, Class<T> type, T defaultValue); +} +----------------------------------------------- + +Using this verticle as a superclass, provides you + +* embedded convenience methods for programmatic configuration access (+getConfigProperty*+ methods). +* support for configuration injection based on link:../mod_injection.html[Tamaya's injection API]. + + +The following code snippet gives you an example, what you can do with this functionality: + +[source, java] +----------------------------------------------- +public cllass MyVerticle extends AbstractConfiguredVerticle{ + + @Override + public void start(){ + String configuredValue = getConfigPropertyOrDefault("myKey"); + [...] + BigDecimal bd = getConfigureddPropertyOrDefault("MyNum", BigDecimal.ZERO); + [...] + } +} +----------------------------------------------- + + +As menioned you can also use the injection API: + +[source, java] +----------------------------------------------- +public cllass MyVerticle extends AbstractConfiguredVerticle{ + + @Config("myKey") + private String configuredValue; + + @Config(value="MyNum", defaultValue="0.0") + private BigDecimal bd; + + + @Override + public void start(){ + [...] + } +} +----------------------------------------------- + + +==== Accessing Configuration using the Vertx event bus + +Additionally the extension allows to access configuration values from the event bus: + +[source, java] +----------------------------------------------- +@Override +public void start(){ + // the selector allows to apply a regex on the configuration key to select a + // a configuration sub set. + String selector = "user."; + vertx().eventBus().send( + "CONFIG-MAP", // event bus address + selector, + new Handler<AsyncResult<Message<String>>>() { + @Override + public void handle(AsyncResult<Message<String>> reply) { + testContext.assertNotNull(reply.result()); + testContext.assertNotNull(reply.result().body()); + Map<String,String> config = Json.decodeValue(reply.result().body(), + Map.class); + // do something with the config + // ... + } + }); +----------------------------------------------- + + +Similar only single values can be accessed: + +[source, java] +----------------------------------------------- +@Override +public void start(){ + vertx().eventBus().send( + "CONFIG-VAL", // event bus address + "user.home", // property key + new Handler<AsyncResult<Message<String>>>() { + @Override + public void handle(AsyncResult<Message<String>> reply) { + String value = reply.result().body(); + // do something with the config value + // ... + } + }); +----------------------------------------------- + + +Finally the event bus targets to be used can be configured using Tamaya configuration, +see the code snippet from the implementation: + +[source, java] +----------------------------------------------- +@Config(value = "tamaya.vertx.config.map", defaultValue = "CONFIG-MAP") +private String mapBusTarget; + +@Config(value = "tamaya.vertx.config.value", defaultValue = "CONFIG-VAL") +private String valBusTarget; +----------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-tamaya-site/blob/8951b7be/content/documentation-new/extensions/mod_yaml.adoc ---------------------------------------------------------------------- diff --git a/content/documentation-new/extensions/mod_yaml.adoc b/content/documentation-new/extensions/mod_yaml.adoc new file mode 100644 index 0000000..ceef59a --- /dev/null +++ b/content/documentation-new/extensions/mod_yaml.adoc @@ -0,0 +1,118 @@ +:jbake-type: page +:jbake-status: published + += Apache Tamaya - Extension: Builder + +toc::[] + + +[[YAML]] +== Tamaya YAML (Extension Module) + +Tamaya _YAML_ is an extension module. Refer to the link:../extensions.html[extensions documentation] for further details. + + +=== Overview + +Tamaya _YAML_ provides support for reading configuration using the YAML format (yaml.org). YAML hereby +use intendation for expressing hierarchy, which makes yaml configuration files very easily readable and compact. + + +=== Compatibility + +The YAML module is based on Java 7, so it will run on Java 7 and beyond. + + +=== Installation + +To use YAML as configuration format you must add the corresponding dependency to your module: + +[source, xml] +----------------------------------------------- +<dependency> + <groupId>org.apache.tamaya.ext</groupId> + <artifactId>tamaya-yaml</artifactId> + <version>{tamaya_version}</version> +</dependency> +----------------------------------------------- + +This extension also transitively requires the +tamaya.formats+ module. + + +=== Reading configuration in YAML + +For reading YAML based onfiguration most easily a +YAMLFormat+ can be provided: + +[source, java] +----------------------------------------------- +PropertySource ps = ConfigurationFormats.createPropertySource( + getClassLoader().getResource("myFileConfig.yaml"), new YAMLFormat())); +----------------------------------------------- + + +=== Examples + +The YAML module adds instances of +ConfigurationFormat+ so YAML configuration can be read and mapped to the +according property values. E.g. the following file is a simple and correct YAML configuration: + +[source,yaml] +---------------------------------------------------------------- +invoice: 34843 +date : 2001-01-23 +bill-to: &id001 + given : Chris + family : Dumars + address: + lines: | + 458 Walkman Dr. + Suite #292 + city : Royal Oak + state : MI + postal : 48046 +ship-to: *id001 +product: + - sku : BL394D + quantity : 4 + description : Basketball + price : 450.00 + - sku : BL4438H + quantity : 1 + description : Super Hoop + price : 2392.00 +tax : 251.42 +total: 4443.52 +comments: + Late afternoon is best. + Backup contact is Nancy + Billsmer @ 338-4338. +---------------------------------------------------------------- + +Hereby the above file, by default is mapped as follows into +Map<String,String>+ typed properties: + +[source,listing] +---------------------------------------------------------------- +invoice -> 34843 +date -> Tue Jan 23 01:00:00 CET 2001 +bill-to.family -> Dumars +bill-to.given -> Chris +bill-to.address.state -> MI +bill-to.address.postal -> 48046 +bill-to.address.city -> Royal Oak +bill-to.address.lines -> 458 Walkman Dr. +Suite #292 + +ship-to.given -> Chris +ship-to.address.state -> MI +ship-to.family -> Dumars +ship-to.address.postal -> 48046 +ship-to.address.city -> Royal Oak +ship-to.address.lines -> 458 Walkman Dr. +Suite #292 + +product -> {sku=BL394D, quantity=4, description=Basketball, price=450.0},{sku=BL4438H, quantity=1, description=Super Hoop, price=2392.0} +_product.collection-type -> List + +tax -> 251.42 +total -> 4443.52 +comments -> Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. +----------------------------------------------------------------
