### Install Solace JavaScript API Library Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/README.md Copy the Solace JavaScript API (Browser) library to the 'lib' directory within the cloned repository. This is required for the samples to function. ```bash cp -R /lib . ``` -------------------------------- ### Clone Solace JavaScript Samples Repository Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/README.md Clone the Solace JavaScript samples repository from GitHub to get started. Ensure you are using Solace JavaScript API version 10 or later. ```bash git clone https://github.com/SolaceSamples/solace-samples-javascript cd solace-samples-javascript ``` -------------------------------- ### Implement Message Replay Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Configures a message consumer to retrieve historical data from the broker's replay log using various start locations. Includes event handling for replay-specific status updates and errors. ```javascript // Create consumer with replay from beginning of log var replayConsumer = session.createMessageConsumer({ queueDescriptor: { name: 'replay/queue', type: solace.QueueType.QUEUE }, acknowledgeMode: solace.MessageConsumerAcknowledgeMode.CLIENT, replayStartLocation: solace.SolclientFactory.createReplayStartLocationBeginning(), createIfMissing: true }); // Alternative: Replay from specific date var replayFromDate = solace.SolclientFactory.createReplayStartLocationDate( new Date('2024-01-01T00:00:00Z') ); // Alternative: Replay from specific message ID var rgmid = message.getReplicationGroupMessageId(); var replayFromMessage = solace.SolclientFactory.createReplicationGroupMessageId( rgmid.toString() ); // Handle replay-specific events replayConsumer.on(solace.MessageConsumerEventName.DOWN_ERROR, function (details) { switch (details.subcode) { case solace.ErrorSubcode.REPLAY_STARTED: console.log('Router initiated replay, reconnecting...'); // Recreate flow without client-initiated replay break; case solace.ErrorSubcode.REPLAY_START_TIME_NOT_AVAILABLE: console.log('Requested time not in replay log, replaying from beginning'); // Recreate with createReplayStartLocationBeginning() break; case solace.ErrorSubcode.REPLAY_FAILED: case solace.ErrorSubcode.REPLAY_CANCELLED: case solace.ErrorSubcode.REPLAY_LOG_MODIFIED: console.log('Replay error: ' + details.subcode); break; } }); replayConsumer.on(solace.MessageConsumerEventName.MESSAGE, function (message) { // Process replayed and live messages var rgmid = message.getReplicationGroupMessageId(); console.log('Message RGMID: ' + (rgmid ? rgmid.toString() : 'N/A')); message.acknowledge(); }); replayConsumer.connect(); ``` -------------------------------- ### Initialize and Configure Topic Publisher Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/TopicPublisher/TopicPublisher.html Initializes the Solace factory with version 10.5 defaults and sets the logging level to WARN. Creates a topic publisher instance for 'tutorial/topic' and assigns event listeners to UI buttons for connect, disconnect, and publish actions. ```javascript var publisher = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the publisher, specifying name of the subscription topic publisher = new TopicPublisher('tutorial/topic'); // assign buttons to the publisher functions document.getElementById("connect").addEventListener("click", publisher.connect); document.getElementById("disconnect").addEventListener("click", publisher.disconnect); document.getElementById("publish").addEventListener("click", publisher.publish); }; ``` -------------------------------- ### Initialize and Connect Queue Producer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/ConfirmedPublish/ConfirmedPublish.html Initializes the Solace client factory, sets the log level, creates a QueueProducer instance, and assigns event listeners to UI elements for connect, disconnect, and publish actions. Ensure the Solace router host URL, message-VPN, username, and password are provided. ```javascript var producer = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the producer, specifying name of the subscription topic producer = new QueueProducer('tutorial/queue'); // assign buttons to the producer functions document.getElementById("connect").addEventListener("click", producer.connect); document.getElementById("disconnect").addEventListener("click", producer.disconnect); document.getElementById("publish").addEventListener("click", producer.publish); }; function iframeloaded(){ if (producer) { producer.connectToSolace(); } }; ``` -------------------------------- ### Initialize Solace Factory and Event Listeners Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/NoLocalPubSub/NoLocalPubSub.html Sets up the Solace factory properties, logging level, and binds UI button events to the NoLocalPubSub instance. ```javascript var sample = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the requestor, specifying name of the request topic sample = new NoLocalPubSub('tutorial/topic'); // assign buttons to the requestor functions document.getElementById("connect").addEventListener("click", sample.connect); document.getElementById("disconnect").addEventListener("click", sample.disconnect); document.getElementById("request").addEventListener("click", sample.startDemo); }; function iframeloaded(){ if (sample) { sample.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure DTE Consumer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/DTEConsumer/DTEConsumer.html Sets up the Solace factory, configures logging levels, and attaches event listeners to UI buttons for managing the consumer lifecycle. ```javascript var consumer = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the consumer, specifying name of the queue consumer = new DTEConsumer('tutorial/dte', 'tutorial/topic'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", consumer.connect); document.getElementById("disconnect").addEventListener("click", consumer.disconnect); document.getElementById("startconsume").addEventListener("click", consumer.startConsume); document.getElementById("stopconsume").addEventListener("click", consumer.stopConsume); }; function iframeloaded(){ if (consumer) { consumer.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure Solace Requestor Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/BasicRequestor/BasicRequestor.html Initializes the Solace client factory with specified properties and sets the logging level. This code should be run on window load. ```javascript var requestor = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the requestor, specifying name of the request topic requestor = new BasicRequestor('tutorial/topic'); // assign buttons to the requestor functions document.getElementById("connect").addEventListener("click", requestor.connect); document.getElementById("disconnect").addEventListener("click", requestor.disconnect); document.getElementById("request").addEventListener("click", requestor.request); }; function iframeloaded(){ if (requestor) { requestor.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure Solace Replier in JavaScript Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/GuaranteedReplier/GuaranteedReplier.html Initializes the Solace client factory with specific API version and sets the logging level. This code should be run on window load to prepare the Solace client for use. ```javascript var replier = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the replier, specifying name of the request topic replier = new GuaranteedReplier('tutorial/requesttopic'); // assign buttons to the replier functions document.getElementById("connect").addEventListener("click", replier.connect); document.getElementById("disconnect").addEventListener("click", replier.disconnect); document.getElementById("subscribe").addEventListener("click", replier.startService); document.getElementById("unsubscribe").addEventListener("click", replier.stopService); }; ``` -------------------------------- ### Initialize Solace API and Queue Consumer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/MessageReplay/MessageReplay.html Initializes the Solace client factory with API defaults and creates a queue consumer. Assigns event listeners to control connection and replay actions. ```javascript var subscriberWithReplay = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the consumer, specifying name of the queue subscriberWithReplay = new QueueConsumer('tutorial/queue'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriberWithReplay.connect); document.getElementById("disconnect").addEventListener("click", subscriberWithReplay.disconnect); document.getElementById("startreplay").addEventListener("click", subscriberWithReplay.startReplay); document.getElementById("stopconsume").addEventListener("click", subscriberWithReplay.stopConsume); }; ``` -------------------------------- ### Initialize and Configure Queue Producer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/QueueProducer/QueueProducer.html Initializes the Solace client factory with specific properties and sets the logging level. Assigns event listeners to UI elements for producer actions. ```javascript var producer = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the producer, specifying name of the queue producer = new QueueProducer('tutorial/queue'); // assign buttons to the producer functions document.getElementById("connect").addEventListener("click", producer.connect); document.getElementById("disconnect").addEventListener("click", producer.disconnect); document.getElementById("publish").addEventListener("click", producer.sendMessage); document.getElementById("clear").addEventListener("click", producer.clear); }; ``` -------------------------------- ### Initialize and Configure Solace Replier Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/BasicReplier/BasicReplier.html Initializes the Solace factory with API defaults and sets the log level. This code should be run on window load. ```javascript var replier = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the replier, specifying name of the request topic replier = new BasicReplier('tutorial/topic'); // assign buttons to the replier functions document.getElementById("connect").addEventListener("click", replier.connect); document.getElementById("disconnect").addEventListener("click", replier.disconnect); document.getElementById("subscribe").addEventListener("click", replier.subscribe); document.getElementById("unsubscribe").addEventListener("click", replier.unsubscribe); }; function iframeloaded(){ if (replier) { replier.connectToSolace(); } }; ``` -------------------------------- ### Initialize Solace Subscriber and Event Listeners Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/TopicSubscriber/TopicSubscriber.html Initializes the Solace factory, sets logging levels, and binds UI buttons to subscriber methods. ```javascript var subscriber = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the subscriber, specifying name of the subscription topic subscriber = new TopicSubscriber('tutorial/topic'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriber.connect); document.getElementById("disconnect").addEventListener("click", subscriber.disconnect); document.getElementById("subscribe").addEventListener("click", subscriber.subscribe); document.getElementById("unsubscribe").addEventListener("click", subscriber.unsubscribe); }; function iframeloaded(){ if (subscriber) { subscriber.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure Solace Subscriber Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/SecureSession/SecureSession.html Initializes the Solace factory with API defaults and sets the log level. This code should be run on window load to ensure the DOM is ready. ```javascript var subscriber = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclient-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the subscriber, specifying name of the subscription topic subscriber = new SecureTopicSubscriber('tutorial/topic'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriber.connect); document.getElementById("disconnect").addEventListener("click", subscriber.disconnect); document.getElementById("subscribe").addEventListener("click", subscriber.subscribe); document.getElementById("unsubscribe").addEventListener("click", subscriber.unsubscribe); }; ``` -------------------------------- ### Initialize and Configure Solace Consumer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/ActiveConsumerIndication/ActiveConsumerIndication.html Initializes the Solace factory, sets the log level, and attaches event listeners to UI elements for connection and consumption management. ```javascript var consumer = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the requestor, specifying name of the request topic consumer = new QueueConsumer('tutorial/queue'); // assign buttons to the requestor functions document.getElementById("connect").addEventListener("click", consumer.connect); document.getElementById("disconnect").addEventListener("click", consumer.disconnect); document.getElementById("request").addEventListener("click", consumer.startConsume); }; function iframeloaded(){ if (consumer) { consumer.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure Solace Requestor Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/GuaranteedRequestor/GuaranteedRequestor.html Initializes the Solace factory with version 10.5 defaults and sets up event listeners for connection and request actions. ```javascript var requestor = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the requestor, specifying name of the request topic requestor = new GuaranteedRequestor('tutorial/requesttopic'); // assign buttons to the requestor functions document.getElementById("connect").addEventListener("click", requestor.connect); document.getElementById("disconnect").addEventListener("click", requestor.disconnect); document.getElementById("request").addEventListener("click", requestor.request); }; function iframeloaded(){ if (requestor) { requestor.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Connect Guaranteed Subscriber Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/GuaranteedSubscriber/GuaranteedSubscriber.html Initializes the Solace client factory with version 10.5 defaults, sets the log level to WARN, and creates a guaranteed subscriber instance for a specific queue and topic subscription. It then assigns event listeners to UI buttons for controlling the subscriber's connection and consumption. ```javascript var subscriber = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the consumer, specifying name of the queue subscriber = new GuaranteedSubscriber('tutorial/queue', 'solace/samples/js/pers/>'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriber.connect); document.getElementById("disconnect").addEventListener("click", subscriber.disconnect); document.getElementById("startconsume").addEventListener("click", subscriber.startConsume); document.getElementById("stopconsume").addEventListener("click", subscriber.stopConsume); document.getElementById("clear").addEventListener("click", subscriber.clear); }; function iframeloaded(){ if (subscriber) { subscriber.connectToSolace(); } }; ``` -------------------------------- ### Initialize and Configure Guaranteed Publisher Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/GuaranteedPublisher/GuaranteedPublisher.html Initializes the Solace factory with specific profile settings and binds DOM events to publisher methods. ```javascript var publisher = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the publisher, specifying name of the topic publisher = new GuaranteedPublisher('solace/samples/js/pers'); // assign buttons to the publisher functions document.getElementById("connect").addEventListener("click", publisher.connect); document.getElementById("disconnect").addEventListener("click", publisher.disconnect); document.getElementById("publish").addEventListener("click", publisher.publish); document.getElementById("clear").addEventListener("click", publisher.clear); }; function iframeloaded(){ if (publisher) { publisher.connectToSolace(); } }; ``` -------------------------------- ### Initialize Solace Queue Consumer Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/QueueConsumer/QueueConsumer.html Initializes the Solace factory, sets logging levels, and binds UI elements to consumer methods. ```javascript var subscriber = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the consumer, specifying name of the queue subscriber = new QueueConsumer('tutorial/queue'); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriber.connect); document.getElementById("disconnect").addEventListener("click", subscriber.disconnect); document.getElementById("startconsume").addEventListener("click", subscriber.startConsume); document.getElementById("stopconsume").addEventListener("click", subscriber.stopConsume); document.getElementById("clear").addEventListener("click", subscriber.clear); }; function iframeloaded(){ if (subscriber) { subscriber.connectToSolace(); } }; ``` -------------------------------- ### Initialize Solace Factory Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Initializes the Solace factory with recommended profile for Guaranteed Messaging. Sets up logging and global configuration. Check API version after initialization. ```javascript // Initialize the Solace factory with recommended profile for Guaranteed Messaging var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; factoryProps.logLevel = solace.LogLevel.WARN; solace.SolclientFactory.init(factoryProps); // Check API version console.log('Solace API Version: ' + solace.Version.summary); ``` -------------------------------- ### Utilize Structured Data Types (SDT) Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Demonstrates creating and reading SDT Map and Stream containers for typed message payloads. ```javascript // Create SDT Map container var sdtMap = new solace.SDTMapContainer(); // Add fields with explicit types sdtMap.addField('stringField', solace.SDTFieldType.STRING, 'Hello'); sdtMap.addField('intField', solace.SDTFieldType.INT32, 42); sdtMap.addField('boolField', solace.SDTFieldType.BOOL, true); sdtMap.addField('doubleField', solace.SDTFieldType.DOUBLETYPE, 3.14159); sdtMap.addField('bytesField', solace.SDTFieldType.BYTEARRAY, new Uint8Array([1, 2, 3])); // Set map as message payload var message = solace.SolclientFactory.createMessage(); message.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.MAP, sdtMap)); // Read SDT Map from received message var container = message.getSdtContainer(); if (container && container.getType() === solace.SDTFieldType.MAP) { var map = container.getValue(); var keys = map.getKeys(); keys.forEach(function(key) { var field = map.getField(key); console.log(key + ' (' + field.getType() + '): ' + field.getValue()); }); } // Create SDT Stream container var sdtStream = new solace.SDTStreamContainer(); sdtStream.addField(solace.SDTFieldType.STRING, 'First'); sdtStream.addField(solace.SDTFieldType.INT32, 100); sdtStream.addField(solace.SDTFieldType.BOOL, false); message.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STREAM, sdtStream)); // Read SDT Stream var stream = message.getSdtContainer().getValue(); stream.rewind(); while (stream.hasNext()) { var field = stream.getNext(); console.log('Type: ' + field.getType() + ', Value: ' + field.getValue()); } ``` -------------------------------- ### Clone Solace Samples JavaScript Repository Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Clone the Solace Samples JavaScript repository locally, ensuring all submodules are included. Replace `` with your GitHub repository URL. ```sh git clone --recurse-submodules https://github.com//solace-samples-javascript ``` -------------------------------- ### Implement Request/Reply Pattern in JavaScript Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Implement synchronous-style request/reply messaging. The requestor sends a message and waits for a response; the replier processes requests and sends replies. Ensure proper subscription and message handling for both sides. ```javascript // === REQUESTOR SIDE === var request = solace.SolclientFactory.createMessage(); request.setDestination(solace.SolclientFactory.createTopicDestination('service/request')); request.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, 'Get User Profile')); request.setDeliveryMode(solace.MessageDeliveryModeType.DIRECT); // Send request with callbacks session.sendRequest( request, 5000, // Timeout in milliseconds function (session, message) { // Reply received callback var replyText = message.getSdtContainer().getValue(); console.log('Received reply: ' + replyText); }, function (session, event) { // Request failed callback if (event.requestEventCode === solace.RequestEventCode.REQUEST_TIMEOUT) { console.log('Request timed out'); } else { console.log('Request failed: ' + event.infoStr); } }, { requestId: 12345 } // User correlation object ); // === REPLIER SIDE === // Subscribe to request topic session.subscribe( solace.SolclientFactory.createTopicDestination('service/request'), true, 'service-request', 10000 ); // Handle incoming requests session.on(solace.SessionEventCode.MESSAGE, function (message) { var requestText = message.getSdtContainer().getValue(); console.log('Received request: ' + requestText); // Create and send reply var reply = solace.SolclientFactory.createMessage(); reply.setSdtContainer(solace.SDTField.create( solace.SDTFieldType.STRING, 'Response to: ' + requestText )); // sendReply automatically sets destination and correlation from request session.sendReply(message, reply); console.log('Reply sent'); }); ``` -------------------------------- ### Handle Iframe Load for Producer Connection Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/QueueProducer/QueueProducer.html Establishes a connection to Solace once the iframe has loaded, provided the producer object is initialized. ```javascript function iframeloaded(){ if (producer) { producer.connectToSolace(); } }; ``` -------------------------------- ### Initialize Solace Subscriber and UI Events Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/EventMonitor/EventMonitor.html Initializes the Solace factory with version 10.5 defaults and binds DOM button elements to subscriber methods. ```javascript var subscriber = null; window.onload = function () { // Initialize factory with the most recent API defaults var factoryProps = new solace.SolclientFactoryProperties(); factoryProps.profile = solace.SolclientFactoryProfiles.version10_5; solace.SolclientFactory.init(factoryProps); // enable logging to JavaScript console at WARN level // NOTICE: works only with "solclientjs-debug.js" solace.SolclientFactory.setLogLevel(solace.LogLevel.WARN); // create the subscriber, specifying name of the subscription topic subscriber = new EventSubscriber(); // assign buttons to the subscriber functions document.getElementById("connect").addEventListener("click", subscriber.connect); document.getElementById("disconnect").addEventListener("click", subscriber.disconnect); document.getElementById("subscribe").addEventListener("click", subscriber.subscribe); document.getElementById("unsubscribe").addEventListener("click", subscriber.unsubscribe); }; function iframeloaded(){ if (subscriber) { subscriber.connectToSolace(); } }; ``` -------------------------------- ### Subscribe to Topics with Solace JavaScript Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Set up message handlers and subscribe to topics, including wildcard subscriptions. Handles TEXT and binary messages, and logs subscription events. ```javascript // Set up message handler before subscribing session.on(solace.SessionEventCode.MESSAGE, function (message) { var topic = message.getDestination().getName(); // Handle text message (SDT String) if (message.getType() === solace.MessageType.TEXT) { var payload = message.getSdtContainer().getValue(); console.log('Received TextMessage on ' + topic + ': ' + payload); } else { // Handle binary message var binaryPayload = message.getBinaryAttachment(); console.log('Received BinaryMessage on ' + topic + ', length: ' + binaryPayload.length); } // Debug: dump full message details console.log(message.dump(solace.MessageDumpFlag.MSGDUMP_FULL)); }); // Handle subscription events session.on(solace.SessionEventCode.SUBSCRIPTION_OK, function (sessionEvent) { console.log('Subscribed to: ' + sessionEvent.correlationKey); }); session.on(solace.SessionEventCode.SUBSCRIPTION_ERROR, function (sessionEvent) { console.log('Subscription error: ' + sessionEvent.infoStr); }); // Subscribe to a topic with confirmation var topicName = 'tutorial/topic'; session.subscribe( solace.SolclientFactory.createTopicDestination(topicName), true, // Request confirmation topicName, // Correlation key 10000 // Timeout in milliseconds ); // Subscribe with wildcard session.subscribe( solace.SolclientFactory.createTopicDestination('tutorial/*/messages/>'), true, 'wildcard-sub', 10000 ); // Unsubscribe when done session.unsubscribe( solace.SolclientFactory.createTopicDestination(topicName), true, topicName, 10000 ); ``` -------------------------------- ### Connect to Solace after iframe load Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/MessageReplay/MessageReplay.html Establishes a connection to Solace once the iframe has finished loading, provided the subscriber object is initialized. ```javascript function iframeloaded(){ if (subscriberWithReplay) { subscriberWithReplay.connectToSolace(); } }; ``` -------------------------------- ### Create and Connect Solace Session Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Creates a Solace session with specified connection properties and sets up event handlers for connection status. The session manages the connection lifecycle and provides methods for publishing and subscribing. Infinite reconnect attempts are configured. ```javascript // Create session with connection properties var session = solace.SolclientFactory.createSession({ url: 'wss://broker.example.com:443', vpnName: 'default', userName: 'solace-client', password: 'secret', connectRetries: 3, reconnectRetries: -1, // Infinite reconnect attempts reconnectRetryWaitInMsecs: 5000, publisherProperties: { acknowledgeMode: solace.MessagePublisherAcknowledgeMode.PER_MESSAGE } }); // Set up session event handlers session.on(solace.SessionEventCode.UP_NOTICE, function (sessionEvent) { console.log('Session connected successfully'); }); session.on(solace.SessionEventCode.CONNECT_FAILED_ERROR, function (sessionEvent) { console.log('Connection failed: ' + sessionEvent.infoStr); }); session.on(solace.SessionEventCode.DISCONNECTED, function (sessionEvent) { console.log('Session disconnected'); session.dispose(); }); session.on(solace.SessionEventCode.RECONNECTING_NOTICE, function (sessionEvent) { console.log('Session reconnecting...'); }); session.on(solace.SessionEventCode.RECONNECTED_NOTICE, function (sessionEvent) { console.log('Session reconnected'); }); // Connect the session try { session.connect(); } catch (error) { console.log('Connect error: ' + error.toString()); } ``` -------------------------------- ### Handle Iframe Load for Solace Connection Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/SecureSession/SecureSession.html Connects to Solace once the iframe has loaded, provided the subscriber object has been initialized. ```javascript function iframeloaded(){ if (subscriber) { subscriber.connectToSolace(); } }; ``` -------------------------------- ### Handle IFrame Load for Connection Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/TopicPublisher/TopicPublisher.html This function is called when an iframe finishes loading. If the publisher object is initialized, it attempts to connect to Solace. ```javascript function iframeloaded(){ if (publisher) { publisher.connectToSolace(); } }; ``` -------------------------------- ### CSS for IE11 Specific Instructions Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/GuaranteedReplier/GuaranteedReplier.html Provides CSS rules to conditionally display instructions relevant only to Internet Explorer 11. This ensures users on older browsers receive necessary guidance. ```css .warning { padding: 5px; border: 1px solid black; background-color: #ff8; } .ie11 { /* Hide instructions that only apply to IE11/Edge */ display: none; } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .ie11 { /* Show instructions in IE11. If you're trying this sample from the local filesystem, it's easy to miss the prompt at the bottom of the window. */ display: block !important; } } ``` -------------------------------- ### Basic Requestor CSS Styling Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/BasicRequestor/BasicRequestor.html Provides basic styling for warnings and specific display adjustments for IE11/Edge browsers. ```css .warning { padding: 5px; border: 1px solid black; background-color: #ff8; } .ie11 { /* Hide instructions that only apply to IE11/Edge */ display: none; } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .ie11 { /* Show instructions in IE11. If you're trying this sample from the local filesystem, it's easy to miss the prompt at the bottom of the window. */ display: block !important; } } ``` -------------------------------- ### CSS for IE11 Specific Styling Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/SecureSession/SecureSession.html Provides CSS rules to hide instructions not relevant to IE11 and to show specific instructions for IE11 users, particularly when running from a local filesystem. ```css .warning { padding: 5px; border: 1px solid black; background-color: #ff8; } .ie11 { /* Hide instructions that only apply to IE11/Edge */ display: none; } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .ie11 { /* Show instructions in IE11. If you're trying this sample from the local filesystem, it's easy to miss the prompt at the bottom of the window. */ display: block !important; } } ``` -------------------------------- ### Push Branch to Fork Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Push your local branch 'my-fix-branch' to your fork on GitHub. ```sh git push origin my-fix-branch ``` -------------------------------- ### Fetch Upstream Changes Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Fetch the latest changes from the upstream repository. ```sh git fetch upstream ``` -------------------------------- ### CSS Styling for IE11 Compatibility Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/basic-samples/TopicSubscriber/TopicSubscriber.html Defines styles for handling IE11-specific instructions and warnings. ```css .warning { padding: 5px; border: 1px solid black; background-color: #ff8; } .ie11 { /* Hide instructions that only apply to IE11/Edge */ display: none; } @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .ie11 { /* Show instructions in IE11. If you're trying this sample from the local filesystem, it's easy to miss the prompt at the bottom of the window. */ display: block !important; } } ``` -------------------------------- ### Publish Guaranteed Messages with Solace JavaScript Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Configure session for guaranteed messaging acknowledgments and publish persistent messages. Includes error handling for GM unavailability and send errors. ```javascript // Configure session for guaranteed messaging acknowledgments session.on(solace.SessionEventCode.ACKNOWLEDGED_MESSAGE, function (sessionEvent) { console.log('Message acknowledged, correlation key: ' + sessionEvent.correlationKey.id); }); session.on(solace.SessionEventCode.REJECTED_MESSAGE_ERROR, function (sessionEvent) { console.log('Message rejected, correlation key: ' + sessionEvent.correlationKey.id); console.log('Reason: ' + sessionEvent.infoStr); }); // Create and publish a persistent message var message = solace.SolclientFactory.createMessage(); message.setDestination(solace.SolclientFactory.createTopicDestination('persistent/topic')); message.setDeliveryMode(solace.MessageDeliveryModeType.PERSISTENT); // Set binary payload var payload = new TextEncoder().encode('Guaranteed Message Content'); message.setBinaryAttachment(payload); // Set correlation key for acknowledgment tracking var correlationKey = { name: 'MESSAGE_CORRELATIONKEY', id: Date.now() }; message.setCorrelationKey(correlationKey); // Optional: Set time-to-live and dead message queue eligibility message.setTimeToLive(60000); // 60 seconds TTL message.setDMQEligible(true); // Move to DMQ on expiry try { session.send(message); console.log('Persistent message sent with key: ' + correlationKey.id); } catch (error) { if (error.subcode === solace.ErrorSubcode.GM_UNAVAILABLE) { console.log('Guaranteed Messaging not available on broker'); } else { console.log('Send error: ' + error.toString()); } } ``` -------------------------------- ### Add Upstream Remote Repository Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Add the SolaceSamples GitHub repository as a remote named 'upstream' if it has not been set previously. ```sh git remote add upstream https://github.com/SolaceSamples/solace-samples-javascript ``` -------------------------------- ### Monitor Session Statistics Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Retrieve performance metrics using session.getStat and reset counters with session.resetStats. These metrics track throughput and guaranteed messaging health. ```javascript // Get individual statistics var txMsgs = session.getStat(solace.StatType.TX_TOTAL_DATA_MSGS); var rxMsgs = session.getStat(solace.StatType.RX_TOTAL_DATA_MSGS); var txBytes = session.getStat(solace.StatType.TX_TOTAL_DATA_BYTES); var rxBytes = session.getStat(solace.StatType.RX_TOTAL_DATA_BYTES); console.log('Messages sent: ' + txMsgs + ', received: ' + rxMsgs); console.log('Bytes sent: ' + txBytes + ', received: ' + rxBytes); // Guaranteed messaging stats var acks = session.getStat(solace.StatType.TX_ACKS_RXED); var windowClose = session.getStat(solace.StatType.TX_WINDOW_CLOSE); var ackTimeout = session.getStat(solace.StatType.TX_ACK_TIMEOUT); console.log('Acks received: ' + acks + ', window closes: ' + windowClose); // Reset all statistics session.resetStats(); ``` -------------------------------- ### Attach and Read User Property Map Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Use SDTMapContainer to attach metadata to messages for routing or filtering. Ensure properties are read from the message object after receipt. ```javascript // Create message with user properties var message = solace.SolclientFactory.createMessage(); message.setDestination(solace.SolclientFactory.createTopicDestination('orders/new')); message.setBinaryAttachment(new TextEncoder().encode('Order data')); // Set user properties var userProps = new solace.SDTMapContainer(); userProps.addField('correlationId', solace.SDTFieldType.STRING, 'order-12345'); userProps.addField('priority', solace.SDTFieldType.INT32, 1); userProps.addField('timestamp', solace.SDTFieldType.INT64, Date.now()); userProps.addField('region', solace.SDTFieldType.STRING, 'us-west-2'); message.setUserPropertyMap(userProps); session.send(message); // Read user properties from received message session.on(solace.SessionEventCode.MESSAGE, function (message) { var props = message.getUserPropertyMap(); if (props) { var correlationId = props.getField('correlationId'); if (correlationId) { console.log('Correlation ID: ' + correlationId.getValue()); } var priority = props.getField('priority'); if (priority) { console.log('Priority: ' + priority.getValue()); } } }); ``` -------------------------------- ### Handle Iframe Load for Solace Connection in JavaScript Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/src/features/GuaranteedReplier/GuaranteedReplier.html Establishes the Solace connection when an iframe has finished loading. This is a callback function to ensure the connection attempt is made after the necessary page elements are ready. ```javascript function iframeloaded(){ if (replier) { replier.connectToSolace(); } }; ``` -------------------------------- ### Commit Changes Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Commit your changes with a descriptive message. The '-a' option stages all modified tracked files and commits them. ```sh git commit -a -m "Your Commit Message" ``` -------------------------------- ### Perform Graceful Disconnection Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Stop and dispose of consumers before disconnecting the session to ensure clean resource cleanup. Handle the DISCONNECTED event to finalize session disposal. ```javascript function gracefulShutdown() { // Stop and dispose message consumers first if (messageConsumer) { messageConsumer.stop(); messageConsumer.disconnect(); messageConsumer.dispose(); messageConsumer = null; } // Disconnect session if (session !== null) { try { session.disconnect(); } catch (error) { console.log('Disconnect error: ' + error.toString()); } } } // Handle disconnected event to dispose session session.on(solace.SessionEventCode.DISCONNECTED, function () { console.log('Session disconnected'); if (session !== null) { session.dispose(); session = null; } }); // Call on application exit gracefulShutdown(); ``` -------------------------------- ### Create a New Git Branch Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Create a new git branch named 'my-fix-branch' based on the 'master' branch to make your changes. ```sh git checkout -b my-fix-branch master ``` -------------------------------- ### Monitor Active Consumer Status Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Enables active/inactive event notifications for exclusive queues to manage standby consumer states. ```javascript var consumer = session.createMessageConsumer({ queueDescriptor: { name: 'exclusive/queue', type: solace.QueueType.QUEUE }, acknowledgeMode: solace.MessageConsumerAcknowledgeMode.CLIENT, activeIndicationEnabled: true // Enable active/inactive events }); consumer.on(solace.MessageConsumerEventName.ACTIVE, function () { console.log('This consumer is now ACTIVE and will receive messages'); }); consumer.on(solace.MessageConsumerEventName.INACTIVE, function () { console.log('This consumer is now INACTIVE (standby)'); }); consumer.on(solace.MessageConsumerEventName.MESSAGE, function (message) { // Only received when active console.log('Processing message...'); message.acknowledge(); }); consumer.connect(); ``` -------------------------------- ### Consume Messages from Queues with MessageConsumer Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Use MessageConsumer for guaranteed message delivery from queues. Messages require client acknowledgment to be removed. Configure auto-creation of queues, prefetch window size, and reconnection behavior. ```javascript // Create a message consumer bound to a queue var messageConsumer = session.createMessageConsumer({ queueDescriptor: { name: 'tutorial/queue', type: solace.QueueType.QUEUE }, acknowledgeMode: solace.MessageConsumerAcknowledgeMode.CLIENT, createIfMissing: true, // Auto-create queue if it doesn't exist windowSize: 50, // Prefetch window connectTimeoutInMsecs: 10000, reconnectAttempts: -1, // Auto-reconnect reconnectIntervalInMsecs: 3000 }); // Consumer lifecycle events messageConsumer.on(solace.MessageConsumerEventName.UP, function () { console.log('Consumer connected and ready to receive messages'); }); messageConsumer.on(solace.MessageConsumerEventName.CONNECT_FAILED_ERROR, function (error) { console.log('Consumer connect failed: ' + error.message); }); messageConsumer.on(solace.MessageConsumerEventName.DOWN, function () { console.log('Consumer disconnected'); }); messageConsumer.on(solace.MessageConsumerEventName.DOWN_ERROR, function (error) { console.log('Consumer error: ' + error.message + ', subcode: ' + error.subcode); }); // Message handler with acknowledgment messageConsumer.on(solace.MessageConsumerEventName.MESSAGE, function (message) { console.log('Received message from queue'); if (message.getType() === solace.MessageType.TEXT) { var payload = message.getSdtContainer().getValue(); console.log('Text payload: ' + payload); } else { var binary = message.getBinaryAttachment(); var text = new TextDecoder().decode(binary); console.log('Binary payload: ' + text); } // Acknowledge message to remove from queue message.acknowledge(); }); // Connect the consumer messageConsumer.connect(); // Add topic subscription to queue (attracts messages to queue) messageConsumer.on(solace.MessageConsumerEventName.SUBSCRIPTION_OK, function (event) { console.log('Queue subscription added: ' + event.correlationKey); }); messageConsumer.addSubscription( solace.SolclientFactory.createTopicDestination('persistent/topic/>'), 'topic-subscription', // Correlation key 10000 // Timeout ); // Stop and disconnect consumer messageConsumer.stop(); // Stop receiving messages messageConsumer.disconnect(); // Disconnect from queue messageConsumer.dispose(); // Release resources ``` -------------------------------- ### Publish Direct Message Source: https://context7.com/solacesamples/solace-samples-javascript/llms.txt Publishes a direct message with a string payload to a specified topic. Direct messages offer at-most-once delivery with low latency. Handles transport buffer full errors. ```javascript // Create and configure a direct message var message = solace.SolclientFactory.createMessage(); message.setDestination(solace.SolclientFactory.createTopicDestination('tutorial/topic')); message.setDeliveryMode(solace.MessageDeliveryModeType.DIRECT); // Set text payload using SDT container var messageText = 'Hello World'; message.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, messageText)); // Alternative: Set binary payload // var binaryPayload = new TextEncoder().encode(messageText); // message.setBinaryAttachment(binaryPayload); // Publish the message try { session.send(message); console.log('Message published to topic: tutorial/topic'); } catch (error) { if (error.subcode === solace.ErrorSubcode.INSUFFICIENT_SPACE) { console.log('Transport buffer full, retry later'); } else { console.log('Send error: ' + error.toString()); } } ``` -------------------------------- ### Rebase Branch onto Upstream Master Source: https://github.com/solacesamples/solace-samples-javascript/blob/master/CONTRIBUTING.md Rebase your current branch onto the upstream 'master' branch to incorporate the latest changes. This is recommended if you haven't pushed your branch yet. ```sh git rebase upstream/master ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.