Custom Search

Tuesday, January 27, 2009

JMS (ActiveMQ) using Spring

For a recent project - I wanted to get started with JMS implementations and finally settled on ActiveMQ . I chose the Spring framework because of the range of integration options it gives us with the other parts of the stack.

Here is the sample code fragment using the same. Pre-requisites: Download Apache ActiveMQ 5.2.0 and Spring JMS 2.5.6.A (use ivy from the spring repository to grab the same).

Launch the activemq binary , before running the program below. The binary is usually available in $ACTIVEMQ_HOME/bin/activemq. The binary launches the tcp listening endpoint using the openwire protocol. You will see a line similar to below

INFO  TransportServerThreadSupport   - Listening for connections at: <b>tcp://hostname:61616</b>
INFO  TransportConnector             - Connector <b>openwire</b> Started


package mymq;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class Producer {

public static class FlyWeight implements Serializable {

public FlyWeight(String _msg) {
msg = _msg;
}

private String msg;

@Override
public String toString() {
return msg;
}
}

/**
* @param args
* @throws JmsException
*/
public static void main(String[] args) {
Producer prod = new Producer();
prod.startProducer();
prod.startConsumer();
}

public void startProducer() {
service.submit(new Runnable() {

public void run() {
try {
JmsTemplate template = new JmsTemplate(getConnectionFactory());
template.afterPropertiesSet();
final DateFormat fmt = new SimpleDateFormat("HH:mm:ss");
while (true) {
Thread.sleep(1000 * 2);
template.send(QUEUE_NAME, new MessageCreator() {

@Override
public Message createMessage(Session session) throws JMSException {
ActiveMQObjectMessage msg = new ActiveMQObjectMessage();
msg.setObject(new FlyWeight(fmt.format(new Date())));
return msg;
}

});

}
} catch (Exception ex) {

}
}
});
}

public void startConsumer() {
service.submit(new Runnable() {
public void run() {
try {
JmsTemplate template = new JmsTemplate(getConnectionFactory());
template.afterPropertiesSet();
while (true) {
Thread.sleep(1000 * 2);
Message msg = template.receive(QUEUE_NAME);
if (msg instanceof ActiveMQObjectMessage) {
ActiveMQObjectMessage text = (ActiveMQObjectMessage) msg;
System.out.println(text.getObject());
} else {
System.err.println("Message type invalid " + msg.getClass());
}
}
} catch (Exception ex) {

}
}
});
}

static ConnectionFactory getConnectionFactory() {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
// Default port.
// Important: The script 'activemq' must be launched for this program to
// work
// By default - activemq binds a tcp listener (openwire protocol)
// listening to requests at the same.
factory.setBrokerURL("tcp://localhost:61616");
return factory;
}

static final String QUEUE_NAME = "MyQueue";

static ExecutorService service = Executors.newFixedThreadPool(2);
}

Sunday, December 21, 2008

Creating a new user in mysql

If we want to create a new user in mysql , we can use the following command.


mysql > create database newdb
> grant all privileges on newdb.* to newuser@"localhost" identified by 'newpassword';


This would create the new user identified by that username and password. This can be validated by logging in again.


mysql > mysql -u newuser -p
Enter password:

So - now we have created this user and password and tested the same.

Thursday, December 18, 2008

Solr - Http Caching enabled by default - how to disable the same.

Solr is a system , that provides service access (among many other things)  to the underlying Lucene implementation  and provides a much faster distributed search indexing / retrieval feature.

Much of the configuration in the Solr application is based on solrconfig.xml in the solr.solr.home directory .  Among the important set of options - that might be useful for development is ( especially when testing responses over the browser ) could be, disabling http caching so as to not to continue to clear the browser cache before viewing the page.

This is done as follows, by setting the never304 ,attribute to be true for httpCaching as follows.

<httpcaching never304="true" .... />



This should disable httpCaching so that we do not need to refresh the browser. But for the deployment in production - make sure to deploy the same with the property false ,(as it was by default).

Tuesday, December 16, 2008

JMeter - JUnit Sampler

JMeter has a JUnit sampler since release  . More details are available in the following PDF.  I will post an example once I get my first cut example working on the same.

Wednesday, December 10, 2008

Encryption library for Java - JBCrypt

I was looking for a good encryption library for Java.

The JBCrypt library (ported from BCrypt, a C++ implementation) is a very useful one for the given purpose.

An introductory article in GWT incubator discusses the plugin in detail.

Tuesday, December 9, 2008

Lucene 2.4.0 - Hello World

Lucene 2.4.0 - Hello World application to play around with indexing / searching capabilities of Lucene. The original code is attributed to Lucene tutorial mentioned here.

Some of the API in the code like Hits have been deprecated that creates costly Document objects. The revised code, after addressing compilation warnings is shown herewith.




import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class HelloLucene {
public static void main(String[] args) throws IOException, ParseException {
// 1. create the index
Directory index = new RAMDirectory();
IndexWriter w = new IndexWriter(index, new StandardAnalyzer(), true, new MaxFieldLength(25000));

addDoc(w, "Lucene in Action");
addDoc(w, "Lucene for Dummies");
addDoc(w, "Managing Gigabytes");
addDoc(w, "The Art of Computer Science");
w.close();

// 2. query
String querystr = args.length > 0 ? args[0] : "lucene";
Query q = new QueryParser("title", new StandardAnalyzer()).parse(querystr);

// 3. search
IndexSearcher s = new IndexSearcher(index);
TopDocs docs = s.search(q, null, 100);

// 4. display results
System.out.println("Found " + docs.totalHits + " hits.");
ScoreDoc [] hits = docs.scoreDocs;
int i = 0;
for(ScoreDoc scoreDoc : hits) {
System
.out.println((i + 1) + ". " + s.doc(scoreDoc.doc) );
++i;
}
s.close();
}

private static void addDoc(IndexWriter w, String value) throws IOException {
Document doc = new Document();
doc.add(new Field("title", value, Field.Store.YES, Field.Index.ANALYZED));
w.addDocument(doc);
}
}

Thursday, December 4, 2008

GWT - 1.5.3 - Ubuntu - libstdc++.so.5: cannot open shared object file

Started my work successfully on GWT 1.5.3 for a test project of mine.

I followed the sample instructions as given in the GWT website.

After using the projectCreator and applicationCreator scripts - when I tried to import the project in eclipse and run it - I encountered the following error trace.
/opt/software/gwt-linux/mozilla-1.7.12/libxpcom.so:libstdc++.so.5: cannot open shared object file: No such file or directory
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1751)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1647)
at java.lang.Runtime.load0(Runtime.java:770)
at java.lang.System.load(System.java:1005)
at com.google.gwt.dev.shell.moz.MozillaInstall.load(MozillaInstall.java:190)
at com.google.gwt.dev.BootStrapPlatform.go(BootStrapPlatform.java:40)
at com.google.gwt.dev.GWTShell.main(GWTShell.java:318)

I was working on Ubuntu 8.04.

I did the following

 sudo apt-get install libstdc++5
to get rid of the above mentioned error to install the missing .so files.  That fixed the issue.