Change the Java (JVM) used by tomcat.

Enterprise systems will have different versions of Java installed in it. A system administrator may have to set up Tomcat to use a particular one out of it. By default Tomcat uses the OS default; ie. the one installed into OS path. So how can we make it run with another version of Java.

This is easily achieved using the below commands(Open a terminal and run the below commands, don’t close it.):

export JAVA_HOME=<path-to-java>

or

export JRE_HOME=<path-to-java>

Run the start-up script from the same terminal and you will see from the logs that Tomcat picked up the Java from the path you set.

Notes:

JRE_HOME is set to JAVA_HOME if not set. So setting any of these variables suffice.

ActiveMQ Producer and Consumer in Java

Use this post as a reference for those who work with Apache ActiveMQ middle-ware.

You can download the needed ActiveMQ release from here.

Use this link to get through the installation, configuration and starting of ActiveMQ: Getting Started

You should have Java installed in your machine.I am using ActiveMQ 5.9.0.

Once you bring up the ActiveMQ instance, provided you left all the configurations as default,ActiveMQ will support TCP connections at port 61616. We are going to make use of this port to make our Producer and Consumer classes connect to ActiveMQ.

Disclaimer: ActiveMQ instance and Producer and Consumer programs run on the same machine. Therefore programs can use the URL tcp://localhost:61616 to connect to the ActiveMQ instance.

Producer Class is nothing but a java class which will connect to ActiveMQ and send a message to it specifying the queue to which the message should be en-queued.

Consumer Class is the one which connects to ActiveMQ to retrieve a message from a particular queue.

Lets get to the code now. I used Eclipse IDE to create this java project.
Producer Class(AMQProducer):

import java.sql.Timestamp;
import java.util.Date;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class AMQProducer implements Runnable{
    // Use the same factory for all the producer threads.
    static ActiveMQConnectionFactory activeMQConnectionFactory = 
            new ActiveMQConnectionFactory("tcp://localhost:61616");
    @Override
    public void run() {
        try {
            // Create a JMS connection from the ActiveMQ server
            Connection connection = activeMQConnectionFactory.createConnection();
            connection.start();

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

            // destination represents the message queue to which the message is en-queued
            Destination destination = session.createQueue("HelloMoto");

            // MessageProducer is used to send messages
            // Refer http://docs.oracle.com/javaee/1.4/api/javax/jms/MessageProducer.html for more
            MessageProducer messageProducer = session.createProducer(destination);

            // Sets the producer's default delivery mode. 
            messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            // Message defines the message header and the acknowledge method used for all JMS messages
            String text = "Hello Motorola from producer " + Thread.currentThread().hashCode() + "..."
            + new Timestamp((new Date()).getTime());
            Message message = session.createTextMessage(text);

            messageProducer.send(message);

            System.out.println("Producer Thread("+Thread.currentThread().hashCode()+
                    ") : Sent \'" + text + "\'");

            // Clean up 
            messageProducer.close();
            session.close();    
            connection.close();

        }
        catch (Exception e) {
            System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") Exception occured.");
        }
    }    
}

Consumer Class(AMQConsumer.java):

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;
public class AMQConsumer implements Runnable, ExceptionListener  {
	// Use the same factory for all the consumer threads.
	static ActiveMQConnectionFactory activeMQConnectionFactory = 
			new ActiveMQConnectionFactory("tcp://localhost:61616");

	@Override
	public void run() {
		try {
			// Create a JMS connection from the ActiveMQ server
			Connection connection = activeMQConnectionFactory.createConnection();
			connection.setExceptionListener(this); // override "void onException(JMSException arg0)" method
			connection.start();

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

			Destination destination = session.createQueue("HelloMoto");

			// MessageConsumer is used to receive messages
			// Refer http://docs.oracle.com/javaee/1.4/api/javax/jms/MessageConsumer.html for more
			MessageConsumer messageConsumer = session.createConsumer(destination);

			System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") : Waiting");

			// receive(long timeout) - Receives the next message that arrives within the specified
			// timeout interval
			Message message = messageConsumer.receive(10000);

			// if the received message is text message, display it on console
			if (message instanceof TextMessage ) {
				TextMessage textMessage = (TextMessage)message;
				System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+ 
						") : Recieved \'" + textMessage.getText() + "\'");
			} else {
				System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+
						") : Dont have any message to display");
			}

			// Clean up
			messageConsumer.close();
			session.close();
			connection.close();

		} catch (Exception e) {
			System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") Exception occured.");
		}		
	}

	// If a JMS provider detects a serious problem with a connection, it informs the connection's
	// ExceptionListener,
	@Override
	public void onException(JMSException arg0) {
		System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") JMS Exception occured.  "
				+ "Shutting down client.");
	}
}

Main Class(AMQMain):

import org.sree.activemqeg.AMQConsumer;
import org.sree.activemqeg.AMQProducer;

public class AMQMain {

	public static void main(String[] args) throws InterruptedException {
		(new Thread(new AMQProducer())).start();
		(new Thread(new AMQConsumer())).start();
		(new Thread(new AMQConsumer())).start();
		(new Thread(new AMQConsumer())).start();
		Thread.sleep(1000);
		(new Thread(new AMQProducer())).start();
		(new Thread(new AMQProducer())).start();
	}
}

Output:

Apache ActiveMQ Java Producer Client OutputNeglect the log4j warnings for the time being…

You can analyze the statistics of the various queues of ActiveMQ from a browser with the URL http://localhost:8161 (replace ‘localhost’ with the IP of the machine if ActiveMQ is in a different system). Have a look at the queue we created with our program.

ActiveMQ queue screenshot

Meet you in my next post “ActiveMQ Producer and Client in Java using Spring Framework” which will make things more configurable and professional. 😉

Essential Coding Standards in Java

Know more about coding standards and comments
• What is the need of coding standards and comments?
Coding standards and comments are for the programmer’s ease of understanding the program. They improve the readability of the software.
Another good reason for the need of coding standards and appropriate comments in the program is that, more than 75% of the lifetime cost of a piece of software goes to maintenance and any software is hardly maintained by its original author for its whole life. In this case, appropriate comments in the program will help the new engineers understand the logic of the original author of the program, quickly and thoroughly and take the project further. It will also be helpful to the author of the program in recollecting the logic he has used in it, in a later point of time.
• Do the comments in the program get compiled into the final executable file?
No, all the comments and blank spaces put into program as part of indentation are filtered out at the time of compiling.

Coding Standards
1. Packages
• Package names should help in understanding the program and functions of the files in it.
• Package name should have a proper hierarchy and should be in all-lowercase.
• Files of similar functionality should be put into same package.
• Use different sub packages if needed, instead of putting all your source files into one package.
• Prefix of a package name should always be one of the top-level domain names: com, edu, gov, mil, org or English two-letter codes of countries according to ISO Standard 3166, 1981 and rest of the package name can be according to the internal naming convention of the organization, it can specify division, department, working-unit, etc.
• Eg:
com.infosys.tvm.ped.apple
2. Files
• Files can have maximum of 2000 lines of code.
• Separate different sections of your file with a blank line.
• Write an optional comment for each section for identifying it.
2.1. Source files
• Source files can contain a single public class or interface.
• Private classes and interfaces associated with public classes can be put in the same source file as the public class.
• Public class or interface should be in the beginning of the source file.
• Source file structure:
o Source file should start with a comment of format given below:
/*
*Class name:
*
*Version information:
*
*Date:
*
*Copyright notice:
*/
 Eg:
/*
*
*HelloWorld.java 1.09 11th Oct 1989
*
*/
o Package and import statements:
package com.infosys.ped.apple;
import java.util.*;
o Class and Interface declarations.
2.1.1. Classes
• Class names should be nouns, in mixed case with the first letter of every word capitalized.
Eg:
class Infosys;
class InfosysEmployee
• Class names should be simple and descriptive.
• Use only widely used abbreviations and acronyms in class names; rest of the words should be as whole-words.
• Comment for the class:
/*
*Class description:
*
*Version:
*
*Author:
*/
2.1.2. Interfaces
• Interface name should follow all the standards as class names.
• Eg:
interface Car;
interface InfosysClient;
2.1.3. Methods
• Method names should be verbs in mixed cases, with starting letter lowercase and first letter of all internal words capitalized.
Eg:
erase();
getName();
averageWorkHours();

• Methods should be prefixed with a comment, describing the purpose of it, its argument list and its return value.
• Separate methods with a blank line.
• There should not be space between method name and parenthesis and opening curly braces need to be in the same line as method header; use a new line for closing curly brace.
Eg:
void sayHelloToWorld() {
String stringToPrint = “Hello World… “;
. . .
if (conditional_expression) {
System.out.println();
. . .
}
. . .
}

2.1.4. Variables
• Variable names should be in mixed case with starting letter lowercase and first letter of all internal words capitalized.
• Variable names should be short and meaningful. It should indicate the intent of its use.
• Variable names should not start with underscore (“_”) or dollar sign (“$”) even though it’s possible.
• Do not wait to declare variables until their first use.
• Variables of one character length should be avoided except for temporary variables. Common practice is to use i, j, k, m and n for integers and c, d and e for characters.
Eg:
int i;
char c;
float mySalary;
• Prefer tabs to space between data type and variables. This will make your program look aligned.
Eg:
String unitName; //preferred
int noOfEmployees; //preferred

String unitName; //not a good practice
int noOfEmployees; //not a good practice
• Using a new line for every declaration and commenting it is a good practice.
Eg:
int myAge; //present age of the user
float mySalary //annual income of the user
• Avoid declaration different types in same line.
Eg:
String name, nicknames[5]; //Wrong
2.1.5. Constants
• Constant variable’s name should be fully capitalized with words separated by underscore (“_”)
• Eg:
static final int MAX_AGE_LIMIT=65;
3. Indentation
• Avoid lines longer than 80 characters. Programs should be readable without scrolling horizontally.
• Break expressions, either after a comma or before an operator, which does not fit in a single line. Indent it properly to avoid confusion.
• Eg:
var = myFunction1( myParameter1, myParameter2, myParameter3,
myParameter4, myParameter5);
float sum1 = someNumber1 + someNumber2 + someNumber3
+ (someNumber4 – someNumber5);
Good programming practices
• Use library utilities wherever possible, instead of coding your own logic. Library utilities are optimized for speed and performance and use of these will make the program perform better.
• var1++; var2++; //Wrong practice

var1++; //Correct
var2++ //Correct
• Always use curly braces with “ if ” conditions and “ for ” statements even if there is only one statement inside the block.
• Separate expressions in a “ for ” statement with a blank space.
Eg:
for (expression1; expression2; expression3)
• Do not declare any of the class or instance variables as public unless its unavoidable.
• Avoid using of the instance variables to access class variables.
• zoo.var1 = boo.var2 = 2; //Wrong; makes the program complicated to read
• if (c==d && d==e) //Wrong practice
if ((c==d) && (d==e)) //Correct
• i == 1 ? 100 : 0; //Wrong practice
(i==1) ? 100 : 0; //Correct

References
http://www.oracle.com/technetwork/java/codeconvtoc-136057.html