Pages

Friday, June 27, 2008

JExcel Tutorial

JExcel API's are used to create and read Excel files. Please go through the documentation's of JXL to find out more in detail. This API is very easy to use. I present a Utility below which does some basic operations using JXL API's. I do not like the checked exceptions that cant be handled, so, this utility wraps the checked exceptions in unchecked exception and throws it. A sample Client program is also given to show the usage of the utility class. The utility class handles the below features of the Excel file writings. I will update the Util as and when i find more features to be used.

Features:

1. Create a workbook.
2. Create a worksheet with given name.
3. Create Settings with US locale.
4. Create formatted cell with given font, point size.
5. Create formatted cell with bold, italic, Underline styles.
6. Create formatted cell with border and border style.
7. Create formatted cell with alignment(left, top, bottom etc).
8. Add label to sheet with or without formatting.
9. Add Integer to sheet with or without formatting.
10. Add formula to sheet.
11. Merge cells.
12. Find cells on specific data.
13. Get cell contents.
14. Wrap text data in Cell.

Below is the util class. JavaDocs does the needed explanations.

I am using JXL 2.6.8 release with JDK 5 update 15.

#################################################################

package com.ssb.jxl.util;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.Cell;
import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class JxlUtil {
    /**
     * Class to define a formula.
     * @author sacrosanctblood
     *
     */
    public static class Formulae{
        private String formulae;

        public String getFormulae() {
            return formulae;
        }

        public void setFormulae(String formulae) {
            this.formulae = formulae;
        }
    }
    /**
     * RuntimeException to wrap all the checked exceptions of JXL
     *
     * @author sacrosanctblood
     *
     */
    public static class JxlUtilException extends RuntimeException{
        private static final long serialVersionUID = -1189965636139763776L;
        private Exception _ex;
        public JxlUtilException(Exception ex){
            super(ex);
            this._ex = ex;           
        }
        public Exception getActualJExcelException(){
            return _ex;
        }
    }
    /**
     * Creates a WritableWorkBook from the file given.
     * @param name
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(File name){
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(name);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        return workbook;
    }
    /**
     * Creates a WritableWorkbook with a sheet given by sheet name.
     * @param name
     * @param sheetName
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(File name,String sheetName){
        WritableWorkbook workBook;
        try {
            workBook = Workbook.createWorkbook(name);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        createSheet(sheetName, workBook);
        return workBook;
    }
    /**
     * Creates a WritableWorkbook from file, with the settings given.
     * @param name
     * @param setting
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(File name,WorkbookSettings setting){
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(name,setting);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        return workbook;
    }
    /**
     * Creates a WritableWorkbook from file, with the settings given and sheetname given.
     * @param name
     * @param sheetName
     * @param setting
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(File name,String sheetName,WorkbookSettings setting){
        WritableWorkbook workBook;
        try {
            workBook = Workbook.createWorkbook(name,setting);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        createSheet(sheetName, workBook);
        return workBook;
    }
    /**
     * Creates a WritableWorkbook from file name, with the settings given.
     * @param name
     * @param setting
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(String name,WorkbookSettings setting){
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(new File(name),setting);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        return workbook;
    }
    /**
     * Creates a WritableWorkbook from file name, with the settings given and sheetname given.
     * @param name
     * @param sheetName
     * @param setting
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(String name,String sheetName,WorkbookSettings setting){
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(new File(name),setting);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        createSheet(sheetName, workbook);
        return workbook;
    }
    /**
     * Creates a WritableWorkbook from file name and sheet name given.
     * @param name
     * @param sheetName
     * @return WritableWorkbook
     */
    public WritableWorkbook createWorkBook(String name,String sheetName){
        WritableWorkbook workbook;
        try {
            workbook = Workbook.createWorkbook(new File(name));
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        createSheet(sheetName, workbook);
        return workbook;
    }
    /**
     * Creates settings with US locale.
     * @return WorkbookSettings
     */
    public WorkbookSettings createSettings(){
        WorkbookSettings wbSettings = new WorkbookSettings();
        Locale locale = Locale.US;
        wbSettings.setLocale(locale);
        return wbSettings;
    }
    /**
     * Creates sheet in the workbook with given name.
     * @param sheetName
     * @param workBook
     */
    public void createSheet(String sheetName,WritableWorkbook workBook){
        workBook.createSheet(sheetName, workBook.getNumberOfSheets());
    }
    /**
     * Creates a cell format.
     * @param pointSize
     * @param fontName Can be null, default : Times
     * @param isBold
     * @param italic
     * @param underLineStyle Can be null, default : No Underline
     * @return WritableCellFormat
     */
    public WritableCellFormat createFormattedCell(int pointSize, jxl.write.WritableFont.FontName fontName, boolean isBold, boolean italic, UnderlineStyle underLineStyle){


        WritableFont font = new WritableFont(null!=fontName?fontName:jxl.write.WritableFont.TIMES,

pointSize,

isBold?WritableFont.BOLD:WritableFont.NO_BOLD,

italic,

null!=underLineStyle?underLineStyle:UnderlineStyle.NO_UNDERLINE

);
        WritableCellFormat writableCellFormat = new WritableCellFormat(font);
        return writableCellFormat;
    }
    /**
     * Creates a cell format.
     * @param pointSize
     * @param fontName Can be null, default : Times
     * @param isBold
     * @param italic
     * @param underLineStyle Can be null, default : No Underline
     * @param border Can be null, default : ALL
     * @param lineStyle Can be null, default : THICK
     * @return WritableCellFormat
     */
    public WritableCellFormat createFormattedCell(int pointSize,jxl.write.WritableFont.FontName fontName, boolean isBold, boolean italic, UnderlineStyle underLineStyle, Border border, BorderLineStyle lineStyle){
        WritableFont font = new WritableFont(null!=fontName?fontName:jxl.write.WritableFont.TIMES, pointSize, isBold?WritableFont.BOLD:WritableFont.NO_BOLD, italic,null!=underLineStyle?underLineStyle:UnderlineStyle.NO_UNDERLINE);
        WritableCellFormat writableCellFormat = new WritableCellFormat(font);
        if(null == lineStyle){
            lineStyle = BorderLineStyle.THICK;
        }
        if(null == border){
            border = Border.ALL;
        }
        try {
            writableCellFormat.setBorder(border, lineStyle);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }
        return writableCellFormat;
    }
    /**
     * Creates a cell format.
     * @param pointSize
     * @param fontName Can be null, default : Times
     * @param isBold
     * @param italic
     * @param underLineStyle Can be null, default : No Underline
     * @param border Can be null, default : ALL
     * @param lineStyle Can be null, default : THICK
     * @param alignment Can be null, default : CENTRE
     * @return WritableCellFormat
     */
    public WritableCellFormat createFormattedCell(int pointSize,jxl.write.WritableFont.FontName fontName, boolean isBold, boolean italic, UnderlineStyle underLineStyle, Border border, BorderLineStyle lineStyle, Alignment alignment){
        WritableFont font = new WritableFont(null!=fontName?fontName:jxl.write.WritableFont.TIMES, pointSize, isBold?WritableFont.BOLD:WritableFont.NO_BOLD, italic,null!=underLineStyle?underLineStyle:UnderlineStyle.NO_UNDERLINE);
        WritableCellFormat writableCellFormat = new WritableCellFormat(font);
        if(null == lineStyle){
            lineStyle = BorderLineStyle.THICK;
        }
        if(null == border){
            border = Border.ALL;
        }
        if(null == alignment){
            alignment = Alignment.CENTRE;
        }
        try {
            writableCellFormat.setBorder(border, lineStyle);
            writableCellFormat.setAlignment(alignment);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }
        return writableCellFormat;
    }
    /**
     * Adds the Label cell to sheet at given row and column.
     *
     * @param column
     * @param row
     * @param data
     * @param format Can be null
     * @param sheet
     */
    public void addCellToSheet(int column, int row, String data,WritableCellFormat format,WritableSheet sheet){
        try {
            if(null != format){               
                sheet.addCell(new Label(column, row, data, format));
            }else{
                sheet.addCell(new Label(column, row, data));
            }
        } catch (RowsExceededException e) {
            throw new JxlUtilException(e);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }

    }
    /**
     * Adds Integer cell to sheet at given row and column.
     *
     * @param column
     * @param row
     * @param data
     * @param format Can be null.
     * @param sheet
     */
    public void addCellToSheet(int column, int row, Integer data,WritableCellFormat format,WritableSheet sheet){
        try {
            if(null != format){
                sheet.addCell(new jxl.write.Number(column, row, data, format));
            }else{
                sheet.addCell(new jxl.write.Number(column, row, data));
            }
        } catch (RowsExceededException e) {
            throw new JxlUtilException(e);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }
    }
    /**
     * Adds a formula to sheet at given row and column.
     *
     * @param column
     * @param row
     * @param data
     * @param format Can be null.
     * @param sheet
     */
    public void addCellToSheet(int column, int row, Formulae data,WritableCellFormat format,WritableSheet sheet){
        try {
            if(null != format){
                sheet.addCell(new Formula(column, row, data.getFormulae(), format));
            }else{
                sheet.addCell(new Formula(column, row, data.getFormulae()));
            }
        } catch (RowsExceededException e) {
            throw new JxlUtilException(e);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }
    }
    /**
     * Merges cell between two ranges([col1,row1] to [col2,row2])
     *
     * @param sheet
     * @param col1
     * @param row1
     * @param col2
     * @param row2
     * @return Range
     */
    public Range mergeCells(WritableSheet sheet,int col1, int row1, int col2, int row2){
        try {
            return sheet.mergeCells(col1, row1, col2, row2);
        } catch (RowsExceededException e) {
            throw new JxlUtilException(e);
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        }
    }
    /**
     * Finder on data to retrieve a cell.
     *
     * @param sheet
     * @param data
     * @param isLabelCell
     * @return Cell
     */
    public Cell find(Sheet sheet, String data,boolean isLabelCell){
        return isLabelCell?sheet.findLabelCell(data):sheet.findCell(data);
    }
    /**
     * Gets the content of Cell a given row and column.
     *
     * @param sheet
     * @param col
     * @param row
     * @return String
     */
    public String getCellContents(Sheet sheet, int col, int row){
        Cell componentCell = sheet.getCell(col, row);
        return componentCell.getContents();
    }

/**
* Set the Wrap property to true.
*
* @param format
*/
public void setWrapTrue(WritableCellFormat format){
    try {
        format.setWrap(true);
    } catch (WriteException e) {
        throw new JxlUtilException(e);
    }
}
/**
* Set the Wrap property to false.
*
* @param format
*/
public void setWrapFalse(WritableCellFormat format){
    try {
        format.setWrap(false);
    } catch (WriteException e) {
        throw new JxlUtilException(e);
    }

    /**
     * Flushes the buffer, by writing the data to file and closing the workbook.
     *
     * @param book
     */
    public void flush(WritableWorkbook book){
        try {
            book.write();
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
        try {
            book.close();
        } catch (WriteException e) {
            throw new JxlUtilException(e);
        } catch (IOException e) {
            throw new JxlUtilException(e);
        }
    }
}

 

#####################################################

JxlClient .java

package com.ssb.jxl.client;

import jxl.format.Alignment;
import jxl.format.Border;
import jxl.write.WritableCellFormat;
import jxl.write.WritableWorkbook;

import com.ssb.jxl.util.JxlUtil;

public class JxlClient {
    private static final JxlUtil util = new JxlUtil();
    public static void main(String[] args) {
        if(args.length == 0){
            args = new String[2];
            args[0] = "default.xls";
            args[1] = "defaultSheet";
        }
        if(args.length == 1){
            String[] tempArgs = new String[2];
            tempArgs[0] = args[0];
            tempArgs[1] = "defaultSheet";
            args = tempArgs;
        }
        //Create workbook and worksheet with default settings
        WritableWorkbook workBook = util.createWorkBook(args[0], args[1]);
        util.mergeCells(workBook.getSheet(args[1]), 0, 1, 4, 1);
        WritableCellFormat centerAlignedAllBoldformattedCell = util.createFormattedCell(10, null, true, false, null, null, null, Alignment.CENTRE);
        WritableCellFormat bottomBoldFormatedCell = util.createFormattedCell(6, null, false, false, null, Border.BOTTOM,null);
        //Header
        util.addCellToSheet(0, 1, "Header", centerAlignedAllBoldformattedCell, workBook.getSheet(args[1]));
        //Column 1,2,3,4,5
        util.addCellToSheet(0, 2, "Subtitle1", bottomBoldFormatedCell, workBook.getSheet(args[1]));
        util.addCellToSheet(1, 2, "Subtitle2", bottomBoldFormatedCell, workBook.getSheet(args[1]));
        util.addCellToSheet(2, 2, "Subtitle3", bottomBoldFormatedCell, workBook.getSheet(args[1]));
        util.addCellToSheet(3, 2, "Subtitle4", bottomBoldFormatedCell, workBook.getSheet(args[1]));
        util.addCellToSheet(4, 2, "Subtitle5", bottomBoldFormatedCell, workBook.getSheet(args[1]));

        util.flush(workBook);
    }

}

Wednesday, June 25, 2008

JMS with activeMQ

Now that we know basics of ActiveMQ, it better to know JMS too. There are a lot of resources on web for learning JMS, the best one being the sun's JMS tutorial that ships along the J2EE tutorial. So, I wont put too many details in this JMS sample code. The code is self explanatory, and is given just to continue upon the prev post on ActiveMQ. I will be using the JNDI properties file explained in the prev post for publishing and consuming messages.

The jndi.properties is as follows:

# START SNIPPET: jndi

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616

# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue


# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic

# END SNIPPET: jndi

This property file should be in the class path of the application. The queue is created dynamically.

JMS Producer


public class JMSProducer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSProducer.class);

public JMSProducer() {
}

//Run method implemented to run this as a thread.
public void run(){
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
String destinationName = null;
final int numMsgs;
destinationName = "MyQueue";
numMsgs = "5";
LOG.info("Destination name is " + destinationName);

/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}

/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}

/*
* Create connection. Create session from connection; false means
* session is not transacted.create producer, set the text message, set the co-relation id and send the message.
*/
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for (int i = 0; i < numMsgs; i++) {
message.setText("A message is being sent with number " + (i + 1));
message.setJMSCorrelationID("" + i);
LOG.info("Sending message: " + message.getText());
producer.send(message);
}

} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}


}


JMS Consumer

public class JMSConsumer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSConsumer.class);

public void run() {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
Destination destination = null;
String sourceName = null;
final int numMsgs;
sourceName= "MyQueue";
numMsgs = "1";
LOG.info("Source name is " + sourceName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}

/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(sourceName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}


try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
connection.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MessageListener listener = new MyQueueMessageListener();
consumer.setMessageListener(listener );
//Let the thread run for some time so that the Consumer has suffcient time to consume the message
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}

}

MessageListener

public class MyQueueMessageListener implements MessageListener {

/**
*
*/
public MyQueueMessageListener() {
// TODO Auto-generated constructor stub
}

/* (non-Javadoc)
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
* This is called on receving of a text message.
*/
public void onMessage(Message arg0) {
if(arg0 instanceof TextMessage){
try {
//Print it out
System.out.println("Recieved message in listener: " + ((TextMessage)arg0).getText());

System.out.println("Co-Rel Id: " + ((TextMessage)arg0).getJMSCorrelationID());
try {
//Log it to a file
BufferedWriter outFile = new BufferedWriter(new FileWriter("MyQueueConsumer.txt"));
outFile.write("Recieved message in listener: " + ((TextMessage)arg0).getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("~~~~Listener : Error in message format~~~~");
}

}

}

Application to run Consumer and producer

public class SimpleApp {

//Run the producer first, then the consumer
public static void main(String[] args) throws Exception {
runInNewthread(new JMSProducer());
runInNewthread(new JMSConsumer());
}

public static void runInNewthread(Runnable runnable) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(false);
brokerThread.start();
}

}

Tuesday, June 24, 2008

ActiveMQ 5.1.0 tutorial

It is always good to know at least one message brokers. ActiveMQ is one of those top brokers used actively industry wide. So, here is a small tutorial or tips to use ActiveMQ along with java messaging service.

Installations

I am using the following configuration on my system:

1. Windows XP
2. JDK 5 update 15
3. ActiveMQ 5.1.0

Download activeMQ from http://activemq.apache.org/. Unzip to any suitable location. And the installation is done!!!


Directory Structure

After you unzip, there are few basic files you need to know.

a. The bin folder contains the batch file, activemq.bat, using which you can start the server. It also contains activemq-admin.bat, using which you can get more details about activemq, like a listing of queues etc.

b. The conf folder contains the activemq.xml configuring the ActiveMQ broker. Here is where we can configure the transports, permanent queues etc.


Creating Temporary Queues

Firt run bin/activemq.bat. This should start ActiveMQ listening at port 61616. There is an admin console(http://localhost:8161/admin) that can be used to monitor the ActiveMQ server. It can also be used to create queues, but these are temporary queues. That means, once the server is shutdown, and restarted, the queues will have to be re created.

ActiveMQ is primarily build for creating queues dynamically. But, it is possible to create queues permanently in ActiveMQ 4.1 or above.


Creating Permanent Queues

The conf/activemq.xml is called broker configuration. By adding the below in that creates a permanent queue, i.e on restart of the server, the queue does exist. You dont have to create it again.

<beans>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />
<broker xmlns="http://activemq.apache.org/schema/core">
<destinations>
<queue physicalName="test.activemq.queue" />
</destinations>
</broker>
</beans>


Creating Dynamic Queues and configuration

There are two ways to create queues, and configure ActiveMQ dynamically.

a. Programatically, in java code.
b. Using JNDI

The preferred approach is JNDI. But, there is nothing wrong in knowing the first one either.

a. Programmatic usage in ActiveMQ

// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

// Create a Connection
Connection connection = connectionFactory.createConnection();
connection.start();

// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// Create the Queue
Destination destination = session.createQueue("test.prog.queue");

b. Using JNDI

Here, jndi.properties is used to configure. This should be present in the CLASSPATH for the queues, connection factory to be configured correctly.
This is taken from the activeMQ website and modified.

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616

# use the following property to specify the JNDI name the connection factory
# should appear as.
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.jndiqueue.test = test.prog.queue


# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
#topic.MyTopic = example.MyTopic

Changing the ActiveMQ listening port

Copy and paste the conf/activemq.xml, and rename to newBroker.xml. change the port address in the XML:

<!-- The transport connectors ActiveMQ will listen to -->
<transportConnectors>
<transportConnector name="openwire" uri="tcp://localhost:51616" discoveryUri="multicast://default"/>
<transportConnector name="ssl" uri="ssl://localhost:51617"/>
<transportConnector name="stomp" uri="stomp://localhost:51613"/>
<transportConnector name="xmpp" uri="xmpp://localhost:51222"/>
</transportConnectors>

Run the activeMQ batch file with command:

activemq xbean:newBroker.xml

Or place the newBroker.xml in some other directory, say, c:\configs\activemq\newBroker.xml.

Run:

activemq xbean:file:c:/configs/activemq/newBroker.xml

which will start the broker at new ports.

Points to remember:

a. Below exception indicates you are using backslashes in the file: at commandline. change to forward slashes, it will resolve the exception.

ERROR: java.net.URISyntaxException: Illegal character in opaque part at index 13
: xbean:file:E:\soft\activemq\apache-activemq-5.1.0\conf\newBroker.xml
java.net.URISyntaxException: Illegal character in opaque part at index 13: xbean
:file:E:\soft\activemq\apache-activemq-5.1.0\conf\newBroker.xml
at java.net.URI$Parser.fail(URI.java:2816)
at java.net.URI$Parser.checkChars(URI.java:2989)

b. Keep the port number in check, a very large value will also result in a out of range exception.

Running two brokers on same machine

Other than changing the port as shown above, a new datastore has to be given. This is configured in the below XML snippet in the newBroker.xml.

<persistenceAdapter>
<amqPersistenceAdapter syncOnWrite="false" directory="${activemq.base}/newBrokerdata" maxFileLength="20 mb"/>
</persistenceAdapter>

Also, though not required, you can change the jetty servlet engine port of the newBroker.xml as below to say 8162.

<jetty xmlns="http://mortbay.com/schemas/jetty/1.0">
<connectors>
<nioConnector port="8162"/>
</connectors>
<handlers>
<webAppContext contextPath="/admin" resourceBase="${activemq.base}/webapps/admin" logUrlOnStart="true"/>
<webAppContext contextPath="/demo" resourceBase="${activemq.base}/webapps/demo" logUrlOnStart="true"/>
<webAppContext contextPath="/fileserver" resourceBase="${activemq.base}/webapps/fileserver" logUrlOnStart="true"/>
</handlers>
</jetty>

Network of Brokers

We can have a network of brokers for load balancing and support even if one of the brokers fail due to any reason, say, network problem.

The network of broker can be established in two ways:

a. Statically listing the ips of the other broker.
b. using auto discovery mode.

Both the configuration uses the networkConnector element in the broker xml configuration.

a. For statically listing the ips, the below xml can be used in our newBroker.xml

<!-- The store and forward broker networks ActiveMQ will listen to -->
<networkConnectors>
<!-- by default just auto discover the other brokers -->
<!-- <networkConnector name="default-nc" uri="multicast://default"/> -->
<!-- Example of a static configuration:
<networkConnector name="host1 and host2" uri="static://(tcp://host1:61616,tcp://host2:61616)"/>
-->
<networkConnector name="newBroker" uri="static://(tcp://localhost:61616)"/>
</networkConnectors>

If you observe the console, then the following line confirms that our brokers are running as a network of brokers.

INFO DemandForwardingBridge - Network connection between vm://localhost#0 and tcp://localhost/127.0.0.1:61616(localhost) has been established.

b. For auto discovrey mode, you can use the following XML.

<!-- The store and forward broker networks ActiveMQ will listen to -->
<networkConnectors>
<!-- by default just auto discover the other brokers -->
<networkConnector name="default-nc" uri="multicast://default"/>
<!-- Example of a static configuration:
<networkConnector name="host1 and host2" uri="static://(tcp://host1:61616,tcp://host2:61616)"/>
-->
</networkConnectors>

Yes, you guessed right, this is the default configuration.

Remenber to have the below xml snipet with discoveryUri attribute in all your brokers. By default, this is present.

<transportConnector name="openwire" uri="tcp://localhost:51616" discoveryUri="multicast://default"/>

Client using failover over a network of broker

The failover protocol has to be used on the client side, so that, if any of the broker in the network of brokers fail, then the client can use an alternative broker which is up and running.

This is also just a configuration.

For our example, this will be in jndi.properties as:

java.naming.provider.url = failover:(tcp://localhost:61616,tcp://localhost:51616)

Or in code as:
String localURI = "tcp://localhost:61616";
String remoteURI = "tcp://localhost:51616";
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:("+localURI+","+"remoteURI)");

Monday, June 02, 2008

Taking care of yourself, will take care of nature

Hmm.. I am a weird guy, who also is into some amount of technical things. If I get depressed or find nothing else to do, I start reading technical books(Weird!!). Majorly, into java; but nothing specific as Java. It can be VB, C#, Shell script, php or whatever that can be typed on a computer and can be interpreted/compiled and executed.

I had written this blog so as to maintain a personal diary of things I need to remember, which I deem important or weird and should be noted down.

But, I have come to a realization that there is some thing which is more important than these; which is why i am here typing this blog and is of a category, which i have never done before in my life. My Organization, well, not in my profile, Tavant Technologies, have started a drive 'for' the cause of Mother nature. We have a team called Green Team, which does the job of causing awareness among the employees of our organization regarding environment. And, I feel it is very important for every one to be a part of this campaign as a whole with interest creeping out from deepness of each heart. And I think, may be i can show its important by putting this content on my very very very personal diary.

Here is a 'typing' dedicated for the our mother. May be this is a beginning and will give me enough enthu to write about other things i think about, namely, Life.

How many of us really care for the environment? In my estimate 99 out of 100 people will say they do care for the environment. Yes and that is true!! But, out of these 99, how many do actually contribute towards caring for nature? I think may be 10. Why is this big difference between numbers? People who care for the environment is greater than the number of people who contribute towards it. Hmm.. I think everyone should think about it for just 20 sec. Nothing more, I know, you don't have time for more than that to spare. Yeah, but you can definitely spare an hour sitting in front of TV or a computer playing games or eating ice-creams on the street or just sitting in front of your desk thinking about past or chatting with a friend of yours about someone who is not yours. Good, keep it up.

Well, you really don't have to give time for taking care of it. You just take care of yourself, that is more than sufficient. Let me put in some of my thoughts here, as in, how to achieve that.

I used to see my friends copy in B.E examinations. They used to write half the book in about 20 half the A4 size sheets, with no space left any where and still quite readable. Very very good thinking. I mean, not copying, but an innovative thinking for a different cause(of not getting caught!!) leading to saving some amount of paper. There is a lesson to learn here. To save paper we can
start educating people to write in small handwriting's.
The smaller it gets the lesser the amount of paper used to convey the same information. No extra effort required, just decrease the font size with which you type, and leave less margins around the paper.

My friend Satish always used to take printouts of the books to read. When i questioned he said it irritates his eyes to read on the system. He wears spectacles already. Then, i realized may be he is actually saving nature. we can
stop reading E-Books for hours on the computer. Better, take printouts on recycled papers, with 2 or 4 sheets per page and read.
The later has relatively higher advantages than consumption of higher power.

All of us have become a host for a fungus called 'diseases', from diabetes to heart problem. Major reason being our working style, the food we eat and laziness we have in us. If you want to stay alive a day more, start exercising. Even walking will do. But, before you start, voluntarily,
switch off the main supplies of your home for one hour in the evening. Then, go out to a park and have some fresh air.


Also, with keeping health of your own in mind,
start eating non-fried, non-microwaved food. The more you eat food like fruits, salad etc,
the more healthier you get. Also, you indirectly help in reducing the power, the oil consumed and also, the air polluted due to frying. These may look small, but, never forget even an ocean is made up of droplets of water.

Though, these are very few ways, but can be definitely done with some conscious effort.
If there are more thing you know, which are very very simple,and can be done without spending sufficient time on it, do post a comment.