Amazon

Tuesday, September 27, 2016

Websphere 8: JMS : File Store and Data Store

File stores
File stores use a file system to preserve operating information and to persist the objects that messaging engines need for recovery in the event of a failure.

A file store is a type of message store that directly uses files in a file system through the operating system. The data storage in a file store is split into three levels: the log file, permanent store file, and temporary store file.

The relationship between a messaging engine and its file store 
Log file
This file contains information about currently active transactions and data that is not yet written to a store file. It is a circular log and its file size is static while a messaging engine is running, but can be changed if required. A restart of the messaging engine is required for the changes to take effect. The size of the log file limits the maximum size of a message that can be sent.

Permanent store file
This file contains permanent data that is retained after the restart of the messaging engine, such as persistent messages, queue data, and information about the storage and transmission of persistent messages.
The permanent store file can be configured to have a maximum and minimum size, or to be unlimited in size. The file can grow from the minimum size (or as required in the unlimited case) but will never shrink (even if the maximum size is set lower than its current size). The file sizes can be changed in the administration console, but a restart of the messaging engine is required for the changes to take effect.
Similar to a file system, when data is deleted from the store, the data in the file is not deleted, only the directory information is updated. This means that if a message is consumed, the message data may still be present in the store file, but the directory information that includes this data in the store is updated to reflect the fact that it is deleted.

Temporary store file
This file contains temporary data that is not retained after the restart of the messaging engine, such as non-persistent messages that were spilled to the file store to release memory from the JVM heap. The temporary store file contents are truncated when the messaging engine starts.
The temporary store file can be configured to have a maximum and minimum size, or to be unlimited in size. The file can grow from the minimum size (or as required in the unlimited case) but will never shrink (even if the maximum size is set lower than its current size). The file sizes can be changed in the administration console, but a restart of the messaging engine is required for the changes to take effect.

Similar to a file system, when data is deleted from the store, the data in the file is not deleted, only the directory information is updated. This means that if a message is consumed, the message data may still be present in the store file, but the directory information that includes this data in the store is updated to reflect the fact that it is deleted.


You can configure where the file store files must be placed. By default, the file store uses a subdirectory in the following path: ${USER_INSTALL_ROOT}/filestores/com.ibm.ws.sib/${ME_NAME}. The file store directory contains two other directories; the log directory that contains the log file and the store directory that contains both the PermanentStore and TemporaryStore files.

Data stores
A data store is a message store that uses a relational database. A messaging engine uses a data store to store operating information in the database, as well as to preserve essential objects that the messaging engine needs for recovery in the event of a failure.

A data store consists of the set of tables that a messaging engine uses to store persistent data in a database. See Data store tables for a list of the tables that comprise a data store. All the tables in a data store are held in the same database schema. You can create multiple data stores in the same database, provided that you use a different schema name for each data store.


The one-to-one relationship between a messaging engine and a data store means that every messaging engine must have its own data store. A messaging engine uses an instance of a JDBC data source to interact with the database that contains the data store for that messaging engine. The relationship between a messaging engine and its data store. illustrates these relationships.

The relationship between a messaging engine and its data store

All the tables in the data store must be stored in the same schema. You can create more than one data store in a database, provided that you use a different schema name for each data store. Although every messaging engine uses the same table names, its relationship with the schema gives each messaging engine exclusive use of its own tables.

Data store topologies
You have several options for the relative location of a data store and its messaging engine. The topology also defines the relationship of a data store with other data stores.
The following options affect your choice of data store topology:
The data store can either run on the same node as its messaging engine or on a remote node.
The data store can either have a dedicated database or it can share a database with other data stores.

Tip: If you are using the Informix® RDBMS, configure a separate database instance for each messaging engine.
A data store uses a relational database management system (RDBMS), working through JDBC, to store data as rows in a set of tables. This data is important when you are backing up or restoring a data store.
The following table summarizes the purpose of each data store table.

Table name
Purpose
SIBOWNER
Ensures exclusive access to the data store by an active messaging engine.
SIBOWNERO
Used for locking the data store. This table stores no data in its one EMPTY_COLUMN column.
SIBCLASSMAP
Catalogs the different object types in the data store.
SIBLISTING
Catalogs the SIBnnn tables.
SIBXACTS
Maintains the status of active two-phase commit transactions.
SIBKEYS
Assigns unique identifiers to objects in the messaging engine.
SIBnnn, where nnn is a number
Contains persistent objects such as messages and subscription information. These tables hold both persistent and nonpersistent objects, using separate tables for the different types of data.
Note: The SIBOWNERO table was introduced for WebSphere® Application Server Version 7.0 and must be created when you are migrating to WebSphere Application Server Version 7.0 or later from an earlier version of WebSphere Application Server.

Message store high availability
High availability is achieved by failing over messaging engines between servers. Both file stores and data stores can be deployed in a highly available environment.

In this figure, two servers access a message store that is either a file store accessed through a network file system or a data store that is accessed through a remote database server. This means a messaging engine running on one of the servers can be failed over to the other server, and will retain access to the message store.


Figure 1. Failover of a messaging engine between servers 



Relative advantages of a file store and a data store

When you will use file store over data store?
Better performance
To achieve best performance using a data store, you often have to use a separate remote database server. With file store you can achieve even better performance without having to use a separate remote database server.

Low administration requirements
The file store combines high throughput with little or no administration. This makes it suitable for those who do not want to worry about where the messaging engine is storing its recoverable data. File store improves on the throughput, and scalability of Apache Derby.

Lower deployment costs
Use of data store might require database administration to configure and manage your messaging engines. File store can be used in environments without a database server.

When you will use data store over file store?
Some organizations prefer to use data store because it uses their existing resources more effectively. For example, this might be the case for a company with a strong team of database specialists, or a stable database infrastructure.

If there is a transient connectivity loss to the file system, the application server must be restarted once the connectivity to the file system is restored. Whereas, in the case of the data store, the messaging engine can recover from the database itself. In such situations, the data store will be a preferred high availability option than the file store system.
With data store, some Java EE applications can share JDBC connections and benefit from one-phase commit optimization. File store does not support this optimization.

Security in Message Store : File or Data
Data stored in both data store and file store benefit from security features provided by WebSphere® Application Server when accessed using the WebSphere Application Server APIs, that is when using JMS messaging. Further security features are available depending on the type of message store you use. 

Data store: you access your chosen database by using a userid and password that is administered using the supplied tools for your specified DBMS. Logical and physical separation of your database server can also be used to improve the overall security of your data.

File store: additional security can be provided when using a file store by careful consideration of your file store files. For example, using a secure network-attached drive to store your file store files improves the physical security of your data. Another example is storing your files on an operating system encrypted file system.

Friday, September 23, 2016

SEPA Payments - Some information

Below info is consolidated from Quora.com

What  is SEPA?

SEPA, or the Single Euro Payments Area, is a payment system that simplifies bank transfers denominated in EUR. SEPA is an initiative by the European Union. As of January 2016 SEPA consists of the 28 member states of the EU, Switzerland, Iceland, Norway, Liechtenstein, Monaco and San Marino. In 2016 Andorra will also join.
SEPA payments are either free or very cheap, which is great for intra-European business. In countries where the euro is not the national currency many banks still allow people to hold bank accounts denominated in euro.
SEPA introduced a lot of harmonization on 3 domains:
·         Credit transfers
·         Direct Debits
·         Card payments

The harmonization was done on the standards themselves (everyone now talks XML ISO20022), pricing aspect, and speed of processing and the rules of behind each of 3 domains. You can find a lot of information on the EPC websites.

SEPA, together with PSD (Payment Services Directive) and other innovations from the past decade,  has allowed fintech startups to come up with innovative solutions.

Most of the principles of SEPA could be carried over to a successor system:

·         use of IBAN (with or without BIC)
·         use of XML data formats
·         fees for cross-border payments equal to national payments (in the same currency)
·         schemes for credit transfer and direct debit

What  is SEPA Direct Debit (SDD)?
The Single Euro Payments Area (SEPA) Direct Debit is a payment arrangement where the debtor/payer authorizes a creditor to collect payments from his or her bank account through a signed mandate. The SEPA Direct Debit allows users to pay for goods and services through bank transfers as long as they come from the 34 SEPA member countries in the European Union. 

SEPA is a payment method supported by Paymentwall (company)


Can I open a bank account for corporation at SEPA bank from Japan?

You need a bank with an activity in the SEPA zone. You can ask your Japanese bank to open it via the local branch in one of the Sepa countries. All Japanse banks I know with an activity in Brussels are already doing this.

What are the differences between ACH, SEPA and RTGS?

ACH stands for Automated Clearing House. It is an electronic network for bank transactions. The term was originally used for the US clearing network(e-check). All ACH payments in the US are done by one of the two ACH: either the EPN or FedACH. ACH rules are governed by NACHA. Its now being used for other country's clearing house as well. To put in the context of India, NEFT is our ACH.

RTGS is a settlement technique; it is used by various central banks around the world to do large payment settlement of their member banks. Best way to describe RTGS is as a real-time settlement system for banks for large value payments. Banks hold Nostro accounts with the central banks and all large payments are settled on a gross basis by the central bank. It is also the mechanism via which deferred net settlement is done on a periodic basis. 
The primary difference between ACH/NEFT and RTGS is that payment instructions in ACH are settled in batches whereas payment instructions in RTGS are settled individually. RTGS is gross settlement whereas NEFT/ACH is net settlement. 


SEPA is the European equivalent of bank transfer for all countries Euro. It is implemented in all the countries where Euro is and a couple of other participating countries. So the payment is a single payment instruction/set regardless if the payment is being made within the Euro country or to another (cross-border) Euro country. It is not real-time yet, but eventually would be heading there.
SEPA stands for Single Euro Payments Area. It really is ACH for European countries under EURO zone. All EURO countries participate in clearing network like domestic market. Under SEPA, there's no difference between transactions within or between EURO countries.

Wednesday, September 21, 2016

Enumerations


  • Enumerations are of class type, and have all the capabilities that a Java class has.
  • Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces. Constructors cannot be public
  • Enumerations are not instantiated using new keyword.
  • All Enumerations by default inherit java.lang.Enum class.
  • Enumeration with Constructor, instance variable and Method
  • Because they are constants, the names of an enum fields are created in uppercase (like other Java constants).
  • You can use an enum any time you need to represent a fixed set of constants.

How to Define and Use an Enumeration

An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject variable, with different subjects in the list.

enum Subject{
 Java, Cpp, C, Dbms
}

Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public, static final by default.

Variables of Enumeration can be defined directly without any new keyword.

Subject sub

Variables of Enumeration type can have only enumeration constants as value.
sub = Subject.Java;

Example of Enumeration

enum WeekDays { 
sun, mon, tues, wed, thurs, fri, sat 
}

class Test{
 public static void main(String args[])  {
  WeekDays wk;
  wk = WeekDays.sun;
  System.out.println("Today is "+wk);
 }
}
Output :  
Today is sun

Values( ) and ValueOf( ) method

All the enumerations have values() and valueOf() methods in them. values() method returns an array of enum-type containing all the enumeration constants in it. Its general form is,

public static enum-type[ ] values() 

valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as argument while calling this method. It's general form is,

public static enum-type valueOf (String str)

enum Student {
John(11), Bella(10), Sam(13), Viraaj(9);
private int age;                   //age of students
int getage() { return age; }

Student(int age)  {  //Constructor cannot be public
this.age= age;
}
}

public class EnumDemo{
 public static void main( String args[] )  {
Student S=Student.Bella;
System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");

System.out.println("Age of "+Student.valueOf("Bella")+" is " +(Student.valueOf("Bella")).getage()+ " years");
System.out.println(S.values());

for(Student s : S.values()){
System.out.println(s);
}

 }
}

Output
Age of Viraaj is 9years
Age of Bella is 10 years
[LStudent;@7e199049
John
Bella
Sam
Viraaj

A Java enum switch statement example
You can also use a Java enum in a switch statement. Here’s the source code for a complete Java enum switch statement example:

public class JavaEnumSwitchCaseExample {

  enum Margin  {
    TOP, RIGHT, BOTTOM, LEFT
  }

  public static void main(String[] args)  {
    System.out.println(getMarginValue(Margin.TOP));
  }

  /**
   * @param A valid Margin value.
   * @return A String representing the value for the given Margin,
   *         or null if the Margin is not valid.
   */
  public static String getMarginValue(Margin margin)  {
    // use the enum values in our switch statement here
    switch (margin)        {
      case TOP:     return "1em";
      case RIGHT:   return "12px";
      case BOTTOM:  return "1.5em";
      case LEFT:    return "6px";
      default:      return null;
    }
  }
  
}

enums and implementation of serialization and singleton:

1) Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.

/**
* Singleton pattern example using Java Enumj
*/
public enum EasySingleton{
    INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.


2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singleton as shown in below example :

    //readResolve to prevent another instance of Singleton
    private Object readResolve(){
        return INSTANCE;
    }

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but within Enum Singleton, Serialization is guaranteed by JVM.

3) Creation of Enum instance is thread-safe
As stated in point 1 since creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking. 

Tuesday, September 20, 2016

JMS Message Structure

The basic structure of a JMS message consists out of three parts: headers,properties and body

JMS Message Headers
Header Field Set By Description
JMSDestination send or publish method Returns a Destination object (a Topic or a Queue, or their temporary version) describing where the message was directed.
JMSDeliveryMode send or publish method Can be DeliveryMode.NON_PERSISTENT orDeliveryMode.PERSISTENT; only persistent messages guarantee delivery in case of a crash of the brokers that transport it.
JMSExpiration send or publish method Returns a timestamp indicating the expiration time of the message; it can be 0 on a message without a defined expiration.
JMSPriority send or publish method Returns a 0-9 integer value (higher is better) defining the priority for delivery. It is only a best-effort value.
JMSMessageID send or publish method Contains a generated ID for identifying a message, unique at least for the current broker. All generated IDs start with the prefix 'ID:', but you can override it with the corresponding setter.
JMSTimestamp send or publish method Returns a long indicating the time of sending.
JMSCorrelationID Client Can link a message with another, usually one that has been sent previously (typically used for a request/response scenario). For example, a reply can carry the ID of the original request message.
JMSReplyTo Client Is a Destination object where replies should be sent, it can be null.
JMSType Client Defines a field for provider-specific or application-specific message types.
JMSRedelivered JMS provider Returns a boolean indicating if the message is being delivered again after a delivery which was not acknowledge.


JMS Message Properties
Application-related properties A Java application can assign application-related properties, which are set before the message is delivered.
Provider-related properties Every JMS provider can define proprietary properties that can be set either by the client or automatically by the provider. Provider-related properties are prefixed with 'JMS_' followed by the vendor name and the specific property name; for example: JMS_I
Standard properties These standardized properties are set by the JMS provider (if supported) when a message is sent. Standard property names start with 'JMSX'; for example: JMSXUserid or JMSXDeliveryCount.


JMS Message Body
Message Type Body Contains
TextMessage A java.lang.String object (for example, the contents of an XML file).
MapMessage A set of name-value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.
BytesMessage A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format.
StreamMessage A stream of primitive values in the Java programming language, filled and read sequentially.
ObjectMessage A Serializable object in the Java programming language.

Monday, September 19, 2016

WMQ Poison Message, Dead Letter Queue and Backout Queue

Dead-letter queues
The dead-letter queue (or undelivered-message queue) is the queue to which messages are sent if they cannot be routed to their correct destination.

Messages are put on this queue when they cannot be put on the destination queue. For example, because the queue does not exist, or because it is full. Dead-letter queues are also used at the sending end of a channel, for data-conversion errors.

Consider defining a dead-letter queue for each queue manager. If you do not, and the MCA is unable to put a message, it is left on the transmission queue and the channel is stopped.

Also, if fast, non-persistent messages (see Fast, nonpersistent messages) cannot be delivered, and no dead-letter queue exists on the target system, these messages are discarded.

However, using dead-letter queues can affect the sequence in which messages are delivered, and so you might choose not to use them.

You can use the USEDLQ channel attribute to determine whether the dead-letter queue is used when messages cannot be delivered. This attribute can be configured so that some functions of the queue manager use the dead-letter queue, while other functions do not. For more information about the use of the USEDLQ channel attribute on different MQSC commands, see DEFINE CHANNEL, DISPLAY CHANNEL, ALTER CHANNEL, and DISPLAY CLUSQMGR.


Use Dead-Letter Queue (USEDLQ)
This attribute determines whether the dead-letter queue (or undelivered message queue) is used when messages cannot be delivered by channels.

Possible values are:
NO
Messages that cannot be delivered by a channel are treated as a failure. The channel either discards these messages, or the channel ends, in accordance with the setting of NPMSPEED.
YES (default)
If the queue manager DEADQ attribute provides the name of a dead-letter queue, then it is used, otherwise the behaviour is as for NO.


Handling poison messages in WebSphere MQ classes for JMS
A poison message is one which cannot be processed by a receiving MDB application. If a poison message is encountered, the JMS MessageConsumer and ConnectionConsumer objects can requeue it according to two queue properties, BOQNAME, and BOTHRESH.

Sometimes, a badly formatted message arrives on a queue, the receiving application cannot process the message correctly. Such a message can cause the receiving application to fail and to back out this badly formatted message. The message can then be repeatedly delivered to the input queue and repeatedly backed out by the application. These messages are known as poison messages. The JMS MessageConsumer object detects poison messages and reroutes them to an alternative destination.

The WebSphere® MQ queue manager keeps a record of the number of times that each message has been backed out. When this number reaches a configurable threshold value, the message consumer requeues the message to a named backout queue. If this requeuing fails for any reason, the message is removed from the input queue and either requeued to the dead-letter queue, or discarded.

The threshold value and the name of the back out queue are attributes of a WebSphere MQ queue. The names of the attributes are BackoutThreshold and BackoutRequeueQName.

To set the BackoutThreshold and BackoutRequeueQName attributes, issue the following MQSC command:
ALTER QLOCAL(your.queue.name) BOTHRESH(threshold value) BOQNAME(your.backout.queue.name)

If the BackoutThreshold attribute is set to a value other than zero, to avoid unexpected behavior set the BackoutRequeueQName attribute to a valid queue name.

For publish/subscribe messaging, if your system creates a dynamic queue for each subscription, these attribute values are obtained from the WebSphere MQ classes for JMS model queue, SYSTEM.JMS.MODEL.QUEUE. To alter these settings, use:
ALTER QMODEL(SYSTEM.JMS.MODEL.QUEUE) BOTHRESH(threshold value) BOQNAME(your.backout.queue.name)

If the backout threshold value is zero, poison message handling is disabled, and poison messages remain on the input queue. Otherwise, when the backout count reaches the threshold value, the message is sent to the named backout queue. If the backout count reaches the threshold value, but the message cannot go to the backout queue, the message is sent to the dead-letter queue or it is discarded. This situation occurs if the backout queue is not defined, or if the MessageConsumer object cannot send the message to the backout queue

IBM WebSphere MQ Series Important Concepts

QueueManager:
QueueManager is responsible for storing and routing messages to other Queue Manager within MQ and it also communicate with outside world e.g. Java program or any other MQ client.

Channel:
Queue Manager use channel to transmit messages to other QueueManager. Channel carries one way traffic in MQ Series (i.e. channels are uni directional). You can have either sending channel or receiving channel in MQ

Dead Letter Queue:
A queue which is used by QueueManager to archive messages for a non existent queue. Also, if a local queue is full, in that case also, messages are routed to Dead Letter Queue.

CCDT file (Client Channel Definition table):
CCDT file is a binary file which contains connection details required by MQ clients e.g. Java application using JMS to connect to MQ Server. In order to connect to MQ Server, MQ clients needs MQ Server host name, MQ Server port name and server channel name. All these details are encapsulated in CCDT file named as AMQCLCHL.TAB. In order to create MQ Connection, MQ clients needs location of this file, which is provided as configuration. most of MQ errors comes either with incorrect CCDT files.

SSLPEER (SSL Peer):
SSLPEER is a String usually DN (Distinguished name) of MQ Client which connect to QueueManager securely using QueueManager. This is a mechanism WMQ uses to identify client. In case of Java or JMS client, SSLPEER is DN of client certificate stored in its keyStore and sent to server during SSL handshake.

Backout Queue:
Dead letter queue is used to store messages which is received for non existent queue. On the other hand backout queue are application specific queue.If MQ client is not able to process message and ask for redelivery, message is redelivered to client with incremented delivery count. Once this deliveryCount crossed a configured threshold, message is moved to back-out queue for later processing or error handling. In short if MQ Series not able to deliver message to client after a preconfigured attempt, WMQ moves message to backout queue.

If the application is unable to move the message to the Back Out Queue (BOQ) for some reason, then an attempt is made to move the queue to the Dead Letter Queue (DLQ).  For example, there are some permission issues on the Back Out Queue, so the message could not be written to the BOQ and it will be moved to Dead letter Queue.

Binding connection and Client Connection:
If MQ clients sits on same physical server where QueueManager is located than it can create binding connection which is relatively faster than client connection, which is usually created by MQ clients residing on same network but not same host. Most of application uses MQ client connection to connect QueueMangaer, which is easy and flexible.

Local Queue and Remote Queue:
local queues are queue on same QueueManager while remote queue refers to queue on different QueueManager.

Friday, September 16, 2016

Why Threads Hung in Java Application


  1. Is the query you are using is not having correct indexes? While querying large data from DB, the thread will get hung if its not having indexes in query.
  2. Are you dumping very big object using logger of log4j? 
  3. Are you doing database hit and trying to fietch large amount of data simultaneously in multiple requests?

Wednesday, September 14, 2016

JMS - General and Important Concepts

Transacted Message in JMS

In a Java SE environment or in the Java EE application client container:
If transacted is set to true then the session will use a local transaction which may subsequently be committed or rolled back by calling the session's commit or rollback methods. The argument acknowledgeMode is ignored.
·         If transacted is set to false then the session will be non-transacted. In this case the argument acknowledgeMode is used to specify how messages received by this session will be acknowledged. The permitted values are Session.CLIENT_ACKNOWLEDGE, Session.AUTO_ACKNOWLEDGE and Session.DUPS_OK_ACKNOWLEDGE. For a definition of the meaning of these acknowledgement modes see the links below.
Modifier and Type
Field and Description
static int
With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.
static int
With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method.
static int
This acknowledgment mode instructs the session to lazily acknowledge the delivery of messages.
static int
This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

In a Java EE web or EJB container, when there is an active JTA transaction in progress:
Both arguments transacted and acknowledgeMode are ignored. The session will participate in the JTA transaction and will be committed or rolled back when that transaction is committed or rolled back, not by calling the session's commit or rollback methods. Since both arguments are ignored, developers are recommended to use createSession(), which has no arguments, instead of this method.

Interface TopicConnectionFactory

Modifier and Type
Method and Description
Creates a topic connection with the default user identity.
createTopicConnection(String userName, String password)
Creates a topic connection with the specified user identity.
public class FirstClient {
      private Context context = null;
      private TopicConnectionFactory factory = null;
      private TopicConnection connection = null;
      private TopicSession session = null;
      private Topic topic = null;
      private TopicPublisher publisher = null;

      public FirstClient() {
            Properties initialProperties = new Properties();
            initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY,
                                  "org.exolab.jms.jndi.InitialContextFactory");
            initialProperties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035");
            try {
                  context = new InitialContext(initialProperties);
                  factory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
                  topic = (Topic) context.lookup("topic1");
                  connection = factory.createTopicConnection();
                 
                  session = connection.createTopicSession(false//Transacted
                                                          TopicSession.AUTO_ACKNOWLEDGE);
                  publisher = session.createPublisher(topic);
                  EventMessage eventMessage = new EventMessage(1, "Message from FirstClient");
                  ObjectMessage objectMessage = session.createObjectMessage();
                  objectMessage.setObject(eventMessage);
                  connection.start();
                  publisher.publish(objectMessage);
                  System.out.println(this.getClass().getName()+ " has sent a message : " + eventMessage);
                  session.close();
                  connection.close();
                  context.close();
            } catch (Exception e) {
            }
      }
}

Synchronous Messaging and Asynchronous Messaging

In case of asynchronous consumption, the consumer is implementing the MessageListener interface .So the overridden onMessage() method gets the message. But in case of synchronous consumption, the client is waiting to get the message since we used the receive() method of the consumer.
public interface MessageListener
A MessageListener object is used to receive asynchronously delivered messages.

Each session must ensure that it passes messages serially to the listener. This means that a listener assigned to one or more consumers of the same session can assume that the onMessage method is not called with the next message until the session has completed the last call.
Implement MessageListener Interface for implement Asynchronous Consumer.
Modifier and Type
Method and Description
void
onMessage(Message message)
Passes a message to the listener.


JMS Reliablity Mechanisms-Message persistence in JMS

1)Persistent delivery mode  This is the default  delivery mode. It forces the JMS provider to take extra care to avoid the loss of message in case of failure. Message is persisted in secondary storage. When the provider comes alive again message will be delivered to consumer. This ensures reliable message delivery.
2)Non-Persistent delivery mode– If we specify the delivery mode as non-persistent then the provider is not taking extra effort to persist the message if a provider failure occurs.

By using the setDeliveryMode(int value) method of MessageProducer interface .
DeliveryMode.PERSISTENT =2
DeliveryMode.NON_PERSISTENT=1 .
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

Or Use the overloaded send() or publish() method of MessageProducer interface .The second argument in the method call specifies the delivery mode.
producer.send(message, DeliveryMode.PERSISTENT);

Setting Message Priority Levels in JMS

1.       Priority levels – 0 to 9
2.       Default Priority Level – 4
3.       Messages having highest priority are delivered first.
4.       Setting Message Priority
-By using setPriority(int value) method of MessageProducer interface.            
-By using the overloaded publish() method.The third argument  will be the priority.               
     void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException
                topicPublisher.publish(message, DeliveryMode.NON_PERSISTENT, 3,20000)
message - the message to send
deliveryMode - the delivery mode to use
priority - the priority for this message
timeToLive - the message's lifetime (in milliseconds)

Message Expiry in JMS
By default a message never expires.In some cases message will become obsolete after a particular time period. In such situation it is  desirable to set expiration time . After the message expires, it will not be delivered.
We can set the expiration time in program in two ways.
 
Using setTimeToLive() method of MessageProducer interface to set the expiry time of messages from that producer.
Example: topPublisher .setTimeToLive(10000)
The above statement sets the expiry time 10000 milliseconds(10 seconds)
 
Using the overridden method publish() of MessageProducer
Example :topPublisher.publish(message, DeliveryMode.PERSISTENT, 3,10000)
The fourth argument gives the expiry time as 10000 milliseconds
The reliability mechanisms we discussed so far are :
 
Creating Durable Subscriptions in JMS

This ensures message delivery to Subscriber, when it comes alive.
 
topic = (Topic) context.lookup("topic1");
connection = factory.createTopicConnection();
session = connection.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);
subscriber = session.createDurableSubscriber(topic,"sampleSubscription");
// subscriber = session.createSubscriber(topic);
connection.start();
Message message = subscriber.receive();
A durable subscriber can have only one active subscriber at a time.
A  durable subscriber registers a durable subscription with a unique identity (“sampleSubscriptionin above example). Subsequent subscribers with the same identity will resume the subscription in the state where the previous subscriber was left.
If there is no active subscriber, then the JMS provider keeps the messages till they are received by any subscriber or till the message expires.
 
 




Amazon Best Sellors

TOGAF 9.2 - STUDY [ The Open Group Architecture Framework ] - Chap 01 - Introduction

100 Feet View of TOGAF  What is Enterprise? Collection of Organization that has common set of Goals. Enterprise has People - organized by co...