Interface DataSource
from...() methods.
The following example illustrates how to construct a DataSource.
import com.caplin.datasource.DataSource;
import java.util.logging.Logger;
public class ExampleDataSource {
@SuppressWarnings("unused")
public static void main(String[] args) {
// Construct a DataSource instance using a config file and a logger
Logger myLogger = Logger.getLogger(ExampleDataSource.class.getName());
// The constructed DataSource uses configuration in etc/datasource.conf
DataSource myDataSource = DataSource.fromConfigFile("etc/datasource.conf", myLogger);
}
}
-
Method Summary
Modifier and TypeMethodDescriptionvoidaddChannelListener(Namespace namespace, ChannelListener channelListener) Registers aChannelListenerfor a specified namespace.voidaddConnectionListener(ConnectionListener connectionListener) Adds a connection listener that receives status events about the state of the DataSource application's connection to other peers.voidaddGenericChannelListener(Namespace namespace, ChannelListener channelListener) Registers aChannelListenerfor a specified namespace.voidaddJsonChannelListener(Namespace namespace, JsonChannelListener jsonChannelListener) Registers aJsonChannelListenerfor a specified namespace.createActiveJsonSubscription(String subject, SubjectConsumer<T> listener, Class<T> jsonDeserializationType) Creates an active subscription to an individual subject that returns Java objects from their serialized JSON form.createActivePublisher(Namespace namespace, DataProvider dataProvider) Creates anActivePublisherfor the specified namespace.createActiveSubscription(String subject, SubscriptionListener subscriptionListener) Creates an active subscription to an individual subject.createBroadcastJsonSubscription(Namespace namespace, SubjectConsumer<T> listener, Class<T> jsonDeserializationType) Creates a subscription to many subjects that return Java objects from their serialized JSON form.createBroadcastPublisher(Namespace namespace) Creates aBroadcastPublisherfor the specified namespace.createBroadcastSubscription(Namespace namespace, SubscriptionListener subscriptionListener) Creates a subscription to many subjects.createCachingPublisher(Namespace namespace, CachingDataProvider dataProvider) Creates anCachingPublisherfor the specified namespace.createCachingPublisher(String metricNamePrefix, Namespace namespace, CachingDataProvider dataProvider) Creates anCachingPublisherfor the specified namespace.createCompatibilityPublisher(Namespace namespace, DataProvider dataProvider) Creates aCompatibilityPublisherfor the specified namespace.voidcreateService(@NotNull Service service) Creates a service with the provided name.static DataSourceCreates an instance ofDataSourceusing the supplied command options.static DataSourceCreates an instance ofDataSourceusing the supplied command options andLogger.static DataSourceCreates an instance ofDataSourceusing the supplied command options,Loggerand preprocessor.static DataSourcefromConfigFile(String configFileName) Creates an instance ofDataSourceusing the supplied configuration file.static DataSourcefromConfigFile(String configFileName, Logger logger) Creates an instance ofDataSourceusing the supplied configuration file andLogger.static DataSourcefromConfigString(String configString) Creates an instance ofDataSourceusing the supplied configuration string.static DataSourcefromConfigString(String configString, Logger logger) Creates an instance ofDataSourceusing the supplied configuration string and Logger.getCommandOption(String defaultValue, String... commandOptionNames) Retrieves the value of a DataSource command option.Retrieves configuration on datasource.conf fileGets an object where extra programmatic configuration can be appliedGets the datasource field managerGets the logger used by DataSource for Java.Retrieves theMBeanServerused for JMX monitoring by the DataSource.getPeers()Retrieves a set of all peers configured to connect to this DataSource.Retrieves a list of all peers configured to connect to this DataSource.static voidUsed to start the datasource and read the configuration file so the resultant configuration attribute values can be returned using the --get-config-value="attribute name" command line option.voidremoveConnectionListener(ConnectionListener connectionListener) Removes a previously registered connection listener.voidCauses the DataSource to disconnect and stop listening for connections.voidCauses the DataSource to reconnect and listen for connections.voidstart()Starts thisDataSource.voidstop()Stops thisDataSource.
-
Method Details
-
start
void start()Starts thisDataSource. Following a call to this method, DataSource for Java starts connecting to its peers. The method immediately returns with DataSource running in a background thread. You should take care to ensure that your application does not exit immediately after callingstart().Note that the datasource starts with status UP by default. To start the datasource with status DOWN, call
setStatusDown()before callingstart()- Throws:
UnsupportedOperationException- If this method is called afterstop()has been called. It is not possible to restart a DataSource for Java instance once it has been stopped.
-
stop
void stop()Stops thisDataSource. Following a call to this method, DataSource for Java disconnects from all of its peers. This method places the DataSource for Java instance in a terminal state from which it cannot be restarted. -
addConnectionListener
Adds a connection listener that receives status events about the state of the DataSource application's connection to other peers.Once registered, the
ConnectionListenerwill receive event updates whenever the connection status has changed (for details see the description ofConnectionListener).You can register more than one
ConnectionListenerwithDataSource. Each registeredConnectionListenerwill receive events for changes to all peers' connection statuses.- Parameters:
connectionListener- TheConnectionListenerto be registered.
-
removeConnectionListener
Removes a previously registered connection listener.Once removed, the
ConnectionListenerwill no longer receive event updates whenever the connection status has changed.- Parameters:
connectionListener- TheConnectionListenerto be removed.
-
createService
Creates a service with the provided name. This service definition will be provided to all connected peers to be considered in request routing.
Example usage:
Note: When multiple DataSource processes for the same service are started, subscriptions may be rebalanced according to thedataSource.createService( Service.named("my-service") .setRemoteLabelRegexPattern("my-datasource-application-[0-9]+") .addIncludePattern("/my-subject/.*") );Service.Typeselected. If no type is specified, subscriptions made by Liberator and Transformer will be rebalanced across all services.- Parameters:
service- The service to be created.- See Also:
-
createCompatibilityPublisher
Creates aCompatibilityPublisherfor the specified namespace.A
CompatibilityPublisheris similar to anActivePublisherexcept that it requires you to maintain a count of how many peers are subscribed to each subject. Because it does not maintain a cache, thisPublisherpasses all requests and discards for such subjects on to theDataProvider. For details, see the description ofCompatibilityPublisher.Note: The use of
CompatibilityPublisheris not recommended; useActivePublisherinstead.CompatibilityPublisheris provided for backwards compatibility with versions of DataSource for Java prior to 5.0, which require you to manage peers yourself. You may want to use this publisher if you are upgrading an existing DataSource application that contains such peer management logic.- Parameters:
namespace- TheNamespaceassociated with this publisher.dataProvider- TheDataProviderthat can publish data via this publisher.- Returns:
- A
CompatibilityPublisherfor the suppliedNamespace.
-
createActivePublisher
Creates anActivePublisherfor the specified namespace.An
ActivePublisherpublishes updates that are for subjects within the specifiedNamespace, to all peers that have subscribed to those subjects.- Parameters:
namespace- TheNamespaceassociated with this publisher.dataProvider- TheDataProviderthat can publish data via this publisher.- Returns:
- An
ActivePublisherfor the suppliedNamespace.
-
createCachingPublisher
Creates anCachingPublisherfor the specified namespace.An
CachingPublisherpublishes updates that are for subjects within the specifiedNamespace, to all peers that have subscribed to those subjects.- Parameters:
namespace- TheNamespaceassociated with this publisher.dataProvider- TheCachingDataProviderthat can publish data via this publisher.- Returns:
- An
CachingPublisherfor the suppliedNamespace.
-
createCachingPublisher
CachingPublisher createCachingPublisher(String metricNamePrefix, Namespace namespace, CachingDataProvider dataProvider) Creates anCachingPublisherfor the specified namespace.An
CachingPublisherpublishes updates that are for subjects within the specifiedNamespace, to all peers that have subscribed to those subjects.- Parameters:
metricNamePrefix- The prefix of the metric namenamespace- TheNamespaceassociated with this publisher.dataProvider- TheCachingDataProviderthat can publish data via this publisher.- Returns:
- An
CachingPublisherfor the suppliedNamespace.
-
createBroadcastPublisher
Creates aBroadcastPublisherfor the specified namespace.A
BroadcastPublisherpermits a DataSource to broadcast, to all connected peers, updates that are for subjects within the specifiedNamespace.- Parameters:
namespace- TheNamespaceassociated with this publisher.- Returns:
- A
BroadcastPublisherfor the suppliedNamespace.
-
addChannelListener
Registers aChannelListenerfor a specified namespace. -
addJsonChannelListener
Registers aJsonChannelListenerfor a specified namespace. -
addGenericChannelListener
Registers aChannelListenerfor a specified namespace. To be used only for Generic Messages. -
createActiveSubscription
ActiveSubscription createActiveSubscription(String subject, SubscriptionListener subscriptionListener) Creates an active subscription to an individual subject.The request will be made to all connected active peers
All events whose subjects match the method's subject parameter are passed to the given
SubscriptionListener.- Parameters:
subject- The subject to subscribe to.subscriptionListener- A listener to receive events raised for theActiveSubscription.- Returns:
- An
ActiveSubscription.
-
createActiveJsonSubscription
<T> ActiveSubscription createActiveJsonSubscription(String subject, SubjectConsumer<T> listener, Class<T> jsonDeserializationType) Creates an active subscription to an individual subject that returns Java objects from their serialized JSON form.To deserialize the JSON data a
JsonHandlermust have been installed (seegetExtraConfiguration()andConfiguration.setJsonHandler(JsonHandler)).- Type Parameters:
T- the Generic type of the object to deserialize the JSON to.- Parameters:
subject- The subject to subscribe to.listener- A listener to receive events raised for this subscription.jsonDeserializationType- the type of the object to deserialize the JSON to.- Returns:
- An
ActiveSubscription.
-
createBroadcastJsonSubscription
<T> BroadcastSubscription createBroadcastJsonSubscription(Namespace namespace, SubjectConsumer<T> listener, Class<T> jsonDeserializationType) Creates a subscription to many subjects that return Java objects from their serialized JSON form. The scope of the subscription is defined by aNamespace; all events whose subjects match the givenNamespaceare passed to the givenSubscriptionListener.To deserialize the JSON data a
JsonHandlermust have been installed (seegetExtraConfiguration()andConfiguration.setJsonHandler(JsonHandler)).- Type Parameters:
T- the Generic type of the object to deserialize the JSON to.- Parameters:
namespace- TheNamespacedefining the subjects to subscribe to.listener- A listener to receive events raised for this subscription.jsonDeserializationType- the type of the object to deserialize the JSON to.- Returns:
- An
BroadcastSubscription.
-
createBroadcastSubscription
BroadcastSubscription createBroadcastSubscription(Namespace namespace, SubscriptionListener subscriptionListener) Creates a subscription to many subjects. The scope of the subscription is defined by aNamespace; all events whose subjects match the givenNamespaceare passed to the givenSubscriptionListener.- Parameters:
namespace- TheNamespacedefining the subjects to subscribe to.subscriptionListener- A listener to receive events raised for theBroadcastSubscription.- Returns:
- A
BroadcastSubscription.
-
getCommandOption
Retrieves the value of a DataSource command option. Command options can be stored in DataSource for Java by creating them using one of the factory methods that take an array of arguments; eitherfromArgs(String[])orfromArgs(String[], Logger). Typically your application would obtain the command options from the command line used to launch the DataSource application, and pass them to the appropriatecreateDataSourcefactory method. DataSource for Java then parses the options from the argument array and makes them available by calling thegetCommandOptionmethod.For an example of how to construct a DataSource with an argument array containing options, and subsequently retrieve the options from the DataSource, see
fromArgs(String[], Logger).- Parameters:
defaultValue- The value to return if no value is stored for any of the option names provided.commandOptionNames- One or more command option names to retrieve a value for. This parameter takes any number of strings in order to help you retrieve a value when there are multiple aliases for the same option. For example, if a command option has a short name "f" and a long name "fields-file" you can pass both of these names into this parameter and if either of them exists, the corresponding value will be returned.- Returns:
- The value defined in the matching command option name, or the default value (see
defaultValueparameter) if there is no value for any of the command option names provided.
-
getPeers
Retrieves a set of all peers configured to connect to this DataSource. Peer connections are specified in the DataSource configuration file.- Returns:
- A set of
Peerobjects.
-
getPeersInOrder
Retrieves a list of all peers configured to connect to this DataSource. Peer connections are specified in the DataSource configuration file.- Returns:
- A list of
Peerobjects in the order they were added in the config file
-
setStatusUp
void setStatusUp()Causes the DataSource to reconnect and listen for connections. -
setStatusDown
void setStatusDown()Causes the DataSource to disconnect and stop listening for connections. -
getMBeanServer
MBeanServer getMBeanServer()Retrieves theMBeanServerused for JMX monitoring by the DataSource. The configuration properties for JMX monitoring are read from the DataSource configuration file.- Returns:
- The instance of
MBeanServerused by the DataSource.
-
getLogger
Logger getLogger()Gets the logger used by DataSource for Java.- Returns:
- The logger.
-
getConfiguration
DataSourceConfiguration getConfiguration()Retrieves configuration on datasource.conf file- Returns:
- DataSourceConfiguration object
-
getExtraConfiguration
Configuration getExtraConfiguration()Gets an object where extra programmatic configuration can be applied- Returns:
- The instance of
Configurationused by the DataSource.
-
getFieldManager
FieldManager getFieldManager()Gets the datasource field manager- Returns:
- FieldManager
-
main
Used to start the datasource and read the configuration file so the resultant configuration attribute values can be returned using the --get-config-value="attribute name" command line option.- Parameters:
args- An array of arguments containing command options. DataSource for Java understands both short command options of the form-key valueand long command options of the form--key=value.
-
fromConfigString
Creates an instance ofDataSourceusing the supplied configuration string and Logger.- Parameters:
configString- String containing the DataSource configuration.logger- TheLoggerto be used by DataSource for Java.- Returns:
- The
DataSource. - Throws:
IllegalArgumentException- TheconfigurationStringis null.
-
fromConfigString
Creates an instance ofDataSourceusing the supplied configuration string.When this method is called, DataSource for Java creates a
Loggerusing the logging configuration in the supplied DataSource configuration string.- Parameters:
configString- String containing the DataSource configuration.- Returns:
- The
DataSource. - Throws:
IllegalArgumentException- TheconfigurationStringis null.
-
fromArgs
Creates an instance ofDataSourceusing the supplied command options,Loggerand preprocessor.The preprocessor Function will be called with the text loaded from the configuration file to allow user defined replacements to be applied before the text is parsed. Note: when include files are used the preprocessor will also be called for each include file.
DataSource for Java parses the provided arguments into command options, which take the form of key/value pairs. DataSource for Java understands both short command options of the form
-key valueand long options of the form--key=valueYou can store arbitrary arguments in DataSource for Java and use them later in your own application code. However DataSource for Java also understands two built-in command options and will process them if they are found in the
argsarray:Long Command Short Command Default Value Description config-file f etc/datasource.conf Path to a DataSource configuration file. For example:
Long command option:
--config-file=etc/datasource.confShort command option:
-f etc/datasource.confIf you set the a config option with the same name more than once, DataSource for Java will use the last occurrence of the option as the value.
If you construct the
DataSourceusing this method, you can retrieve the command option values by calling thegetCommandOption(String, String...)method.- Parameters:
args- An array of arguments containing command options. DataSource for Java understands both short command options of the form-key valueand long command options of the form--key=value.logger- TheLoggerto be used by DataSource for Java.preprocessor- A Function that takes a config string and returns the preprocessed string. Note: this function will be called several times if include files are used.- Returns:
- The DataSource.
- Throws:
IllegalArgumentException- If the value of eitherargsorloggeris null.
-
fromArgs
Creates an instance ofDataSourceusing the supplied command options andLogger.Note: This is the recommended way to create your
DataSourceinstance.When this method is called, DataSource for Java uses the provided
Loggerimplementation for event logging. Packet logging must still be configured in the DataSource configuration file.DataSource for Java parses the provided arguments into command options, which take the form of key/value pairs. DataSource for Java understands both short command options of the form
-key valueand long options of the form--key=valueYou can store arbitrary arguments in DataSource for Java and use them later in your own application code. However DataSource for Java also understands two built-in command options and will process them if they are found in the
argsarray:Long Command Short Command Default Value Description config-file f etc/datasource.conf Path to a DataSource configuration file. For example:
Long command option:
--config-file=etc/datasource.confShort command option:
-f etc/datasource.confIf you set the a config option with the same name more than once, DataSource for Java will use the last occurrence of the option as the value.
If you construct the
DataSourceusing this method, you can retrieve the command option values by calling thegetCommandOption(String, String...)method.The following example shows how to construct a
DataSourcewith an argument array containing command options, and how to subsequently retrieve the command options from theDataSource:import com.caplin.datasource.DataSource; import java.util.logging.Logger; public class ArgumentProcessingWithLogger { @SuppressWarnings("unused") public static void main(String[] args) { // Set up a custom logger Logger myLogger = Logger.getAnonymousLogger(); // The args array containing the command options would generally be passed in // from the command line, but in this example we create the array manually. args = new String[5]; // A short command option takes this form: args[0] = "-f"; args[1] = "etc/datasource.conf"; // You can add any arguments, even arguments used by your application but not // used by DataSource for Java. Here is a custom long option: args[2] = "--myLongOptionName=myValue1"; // Here is a custom short option: args[3] = "-t"; args[4] = "myValue2"; // Construct the DataSource using the args and the custom logger DataSource myDataSource = DataSource.fromArgs(args, myLogger); // The following call to getCommandOption() returns "etc/datasource.conf". Note // that you can pass in any number of option names and the first matching value // will be returned. String configFileLocation = myDataSource.getCommandOption("default.conf", "config-file", "f"); // This call returns "myValue1": String myFirstVariable = myDataSource.getCommandOption("defaultValue", "myLongOptionName"); // This call returns "myValue2": String mySecondVariable = myDataSource.getCommandOption("defaultValue", "t"); } }- Parameters:
args- An array of arguments containing command options. DataSource for Java understands both short command options of the form-key valueand long command options of the form--key=value.logger- TheLoggerto be used by DataSource for Java.- Returns:
- The DataSource.
- Throws:
IllegalArgumentException- If the value of eitherargsorloggeris null.
-
fromArgs
Creates an instance ofDataSourceusing the supplied command options.When this method is called, DataSource for Java creates a
Loggerusing the logging configuration in the supplied DataSource configuration file.Note: It is recommended that you provide your own
Loggerimplementation and supply it to theDataSourceby calling thefromArgs(String[], Logger)method, rather than calling this method.DataSource for Java parses the provided arguments into command options, which take the form of key/value pairs. DataSource for Java understands both short command options of the form
-key valueand long command options of the form--key=value.You can store arbitrary arguments in DataSource for Java and use them later in your own application code. However DataSource for Java also understands two built-in command options and will process them if they are found in the
argsarray:Long Command Short Command Default Value Description config-file f conf/datasource.conf Path to a DataSource configuration file. For example:
Long command option:
--config-file=etc/datasource.confShort command option:
-f etc/datasource.confIf you set the a config option with the same name more than once, DataSource for Java will use the last occurrence of the option as the value.
If you construct the
DataSourceusing this method, you can retrieve the command option values by calling thegetCommandOption(String, String...)method.The following example shows how to construct a
DataSourcewith an argument array containing command options, and how to subsequently retrieve the command options from theDataSource:import com.caplin.datasource.DataSource; public class ArgumentProcessing { @SuppressWarnings("unused") public static void main(String[] args) { // The args array containing the command options would generally be passed in // from the command line, but in this example we create the array manually. args = new String[5]; // A short command option takes this form: args[0] = "-f"; args[1] = "etc/datasource.conf"; // You can add any arguments, even arguments used by your application but not // used by DataSource for Java. Here is a custom long option: args[2] = "--myLongOptionName=myValue1"; // Here is a custom short option: args[3] = "-t"; args[4] = "myValue2"; // Construct the DataSource using the args DataSource myDataSource = DataSource.fromArgs(args); // The following call to getCommandOption() returns "etc/datasource.conf". Note // that you can pass in any number of option names and the first matching value // will be returned. String configFileLocation = myDataSource.getCommandOption("default.conf", "config-file", "f"); // This call returns "myValue1": String myFirstVariable = myDataSource.getCommandOption("defaultValue", "myLongOptionName"); // This call returns "myValue2": String mySecondVariable = myDataSource.getCommandOption("defaultValue", "t"); } }If this method is called then DataSource for Java will create a logger using the logging configuration in the DataSource configuration file. It is recommended that you use either the
fromConfigFile(String, Logger)method orfromArgs(String[], Logger)method and provide your ownLoggerimplementation rather than calling this method.- Parameters:
args- An array of arguments containing command options. DataSource for Java understands both short command options of the form-key valueand long options of the form--key=value.- Returns:
- The DataSource.
- Throws:
IllegalArgumentException- If theargsvalue is null.
-
fromConfigFile
Creates an instance ofDataSourceusing the supplied configuration file.When this method is called, DataSource for Java creates a
Loggerusing the logging configuration in the supplied DataSource configuration file.Note 1: It is recommended that you provide your own
Loggerimplementation and supply it to the DataSource by calling thefromConfigFile(String, Logger)method orfromArgs(String[], Logger)method, rather than calling this method.Note 2: If you want to supply your own command options to the DataSource application, in addition to the configuration, call the
fromArgs(String[])method orfromArgs(String[], Logger)method, rather than this one.- Parameters:
configFileName- Path to a DataSource configuration conf file.- Returns:
- The
DataSource. - Throws:
IllegalArgumentException- If theconfigFileNameis null.
-
fromConfigFile
Creates an instance ofDataSourceusing the supplied configuration file andLogger.When this method is called, DataSource for Java uses the provided
Loggerimplementation for event logging. Packet logging must still be configured in the DataSource configuration file.Note: If you want to supply your own command options to the DataSource application, in addition to the configuration, call the
fromArgs(String[], Logger)method, rather than this one.It is recommended that you use either the
fromArgs(String[])orfromArgs(String[], Logger)factory method instead of this method in order to discourage hard coding of configuration file locations.- Parameters:
configFileName- Path to a DataSource configuration conf file.logger- TheLoggerto be used by DataSource for Java.- Returns:
- The
DataSource. - Throws:
IllegalStateException-If there is logging configuration in the DataSource configuration file. You can construct DataSource instances by either:
- calling
fromConfigFile(String, Logger)orfromArgs(String[], Logger)and ensuring that you do not have any logging configuration in your DataSource configuration file, or - calling
fromConfigFile(String)orfromArgs(String[])and ensuring that you have included logging configuration in your DataSource configuration file so that DataSource for Java can create its own logger.
- calling
IllegalArgumentException- If theconfigFileNameorLoggervalues are null.
-