Converge Sharing
We share what we know !
PDF Print E-mail


Classes on the fly ! Java

Ever wondered if you got your classes to speak to other classes on the fly ?
Well you can do it if you use Java 1.6 and its features.
Here is the snapshot example how you can achieve that:
/**
 * Converge Systems
 * File Name : ConvergeJavaCompiler.java
 * Package Name : 
 * Purpose: Dynamic Compilation of java classes
 *
 * @author Abhinandan Panda		
 * @version 1.0 Oct 23, 2009	
 *
 */

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Vector;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public final class ConvergeJavaCompiler {

 // Generated cless files would reside here
public static final String CLASSPATH_LOCATION = "WebContent/WEB-INF/classes";
	public ConvergeJavaCompiler() {
	}
	private static boolean compile(JavaFileObject source[]) {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);
		try {
			File file = new File(CLASSPATH_LOCATION);
			if (file.exists()) {
				fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
						Collections.singleton(file));
			} else {
				file.mkdir();
				fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
						Collections.singleton(file));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(null,
				fileManager, null, null, null, Arrays.asList(source));
		return task.call().booleanValue();
	}

	public boolean callDynamicCompiler(String className, String programText)
			throws URISyntaxException {
		boolean status = false;
		Vector vectorProgramText = (new ConvergeFileGenerator())
				.getJavaFilesInStringFormat(className, columnVector);
		int count = 0;
		for (String programText : vectorProgramText) {
			System.out.println("Compilation starting on :");
			System.out.println(programText);
			status = compile(new JavaFileObject[] { new RAMResidentJavaFileObject(
						className, programText)
			System.out.println("Compilation Status:"status);
		return status;
	}
}

                                                                                            

Using ActiveMQ

Active MQ primarily is used to do asynchronous batch processing. This can be used to send mails, poll data from database and process that in a batch. Message Queues have primarily 2 clients, a producer and one consumer. Producers are responsible to put messages to the MQ server while consumers continously listen to that port. A real world example of using MQ would be sending a mail to a user. Sending a mail requires a lot of time and is uncertain which if executed in the main thread would result in unwarranted user disruptions. So we need a producer which would just put the message in the MQ and let the MailConsumer poll data and do its work in the background.
A Simple producer :

/**
 * Converge Systems
 * File Name : ConvergeProducerTool.java
 * Package Name : 
 * Purpose: Dynamic Compilation of java classes
 *
 * @author Abhinandan Panda		
 * @version 1.0 Oct 23, 2009	
 *
 */
public class ConvergeProducerTool {

    private Destination destination;
    private long sleepTime;
    private long timeToLive;
    private String user = ActiveMQConnection.DEFAULT_USER;
    private String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private String subject = "convergesystems"; // MQ name. Create a MQ with this name in MQ server
    private boolean topic;
    private boolean transacted;
    private boolean persistent;


    public void run(String message) {
        Connection connection = null;
        try {
            if (timeToLive != 0) {
                System.out.println("Messages time to live " + timeToLive + " ms");
            }

            // Create the connection.
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
            connection = connectionFactory.createConnection();
            connection.start();

            // Create the session
            Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
            if (topic) {
                destination = session.createTopic(subject);
            } else {
                destination = session.createQueue(subject);
            }

            // Create the producer.
            MessageProducer producer = session.createProducer(destination);
            if (persistent) {
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            } else {
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            }
            if (timeToLive != 0) {
                producer.setTimeToLive(timeToLive);
            }

            // Start sending messages
            sendLoop(message,session, producer);

            System.out.println("Done.");

            // Use the ActiveMQConnection interface to dump the connection
            // stats.
            ActiveMQConnection c = (ActiveMQConnection)connection;
            c.getConnectionStats().dump(new IndentPrinter());

        } catch (JMSException e) {
            System.out.println("JMSException::" + e);
           // e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Caught: " + e);
            //e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (Throwable ignore) {
            }
        }
    }

    protected void sendLoop(String emailId,Session session, MessageProducer producer) throws Exception {
            TextMessage message = session.createTextMessage(emailId);
            producer.send(message);
            if (transacted) {
                session.commit();
            }
            Thread.sleep(sleepTime);
    }


    public void setPersistent(boolean durable) {
        this.persistent = durable;
    }

    public void setMessageCount(int messageCount) {
    }

    public void setMessageSize(int messageSize) {
    }

    public void setPassword(String pwd) {
        this.password = pwd;
    }

    public void setSleepTime(long sleepTime) {
        this.sleepTime = sleepTime;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setTimeToLive(long timeToLive) {
        this.timeToLive = timeToLive;
    }

    public void setTopic(boolean topic) {
        this.topic = topic;
    }

    public void setQueue(boolean queue) {
        this.topic = !queue;
    }

    public void setTransacted(boolean transacted) {
        this.transacted = transacted;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setVerbose(boolean verbose) {
    }
}

                                                                                                        

CS Solutions
x

Data Analysis

We will help you in analysing your requirements and your business needs.We shall do whatever we can in providing you with quality solutions in break neck speed.

CS Solutions
x

Model Design

We will help you in analysing your requirements and your business needs.We shall do whatever we can in providing you with quality solutions in break neck speed.