Apache Http Server And SVN

Every developer and Every Project in this world uses a version system. Of all versioning systems i’ve used the most elegent one is SVN.  With its ease of use and over the http access facility it made my life easier than any otehr system.

There are 2 different ways we can host SVN over HTTP. One is Using World’s most Successfully Apache Http Server and other is using SunServe. Here i Would explain how to configure Apache and SVN and which versions ae compatible

There are many versions of apache and svn. And if we try to configure any combination we end up wasting our time as there are lots of compatability issues. Following are 2 of tested combinations by me.

————————————–

SVN Version 1.4.5
Apache 2.2.6

————————————–
Server version: Apache/2.0.59
Server built:   Jul 27 2006 15:55:03
svn-1.4.3-setup

————————————–

Scheduler In Java

Whenever people think of creating any scheduler in java the first thing that come to mind is Quartz. Quartz is Enterprise Job Scheduler which is well tested across the J2EE Industry. So here i’ll explain How to use Quartz and few of its useful features.

First and Foremost thing one has to do to create a scheduler is to Create an Instance of scheduler either by implementing the interface and implementing its methods or By using a default one which Quartz Provides.

Quartz provides a default scheduler which can be get by calling StdSchedulerFactory.getDefaultScheduler()

Now let me explain some basic Features of a scheduler

  1. Job   : This is the actual job which we want to run
  2. JobDetail : This is the data which we supply for JOB to run (Like context we pass to servlet)
  3. Trigger : This actually attached the Job with Scheduler in sense that Scheduler triggers the Job using Trigger Provided

Now Lets See How Simple is to create all the above Elements

			Trigger durectoryReaderTrigger = TriggerUtils
					.makeMinutelyTrigger(1);
			durectoryReaderTrigger.setName("DirectoryListener");
			durectoryReaderTrigger.setGroup("DirectoryListenerGroup");
			durectoryReaderTrigger.setCalendarName("DirectoryListener");

			JobDetail directoryListenerDetail = null;
			try {
				directoryListenerDetail = new JobDetail("DirectoryListenerJob",
						"DirectoryListenerGroup", FilePresenceListener.class);
			} catch (Throwable e) {
				System.out.println("Exception in Creation of Job Detail"
						+ e.getLocalizedMessage());
			}

			logger.info("Job Scheduled For Every 1 Minute");
			// Now Attach Job To Scheduler
			sched.scheduleJob(directoryListenerDetail, durectoryReaderTrigger);
			// Now Start The Scheduler
			sched.start();

In The above code you can see how easy it is to create a scheduler and attach a trigger. Scheduler also provides a facility where we can create a Trigger Using Cron Expression.

TBC…………

SOAP Message Using Sockets

Recently i had to call a webservice for creation of a demo. And i had no time to learn any packages which create SOAP envelope’s. The only thing i know is plan old java. Then i thought why not use sockets for sending messages. Here is a sample Program which sends soap messages and gets response using sockets in Java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.net.*;
import java.io.*;
/**
 *
 * @author Ashwin
 */
public class PostXml {

    public static void main(String[] args) {

        try {
            String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xsi:schemaLocation=\"http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tab = \"http://j2ee.netbeans.org/xsd/tableSchema\" > <soapenv:Body><tab:PURCHASE_ORDER> <tab:PURCHASE_ORDER_Record><tab:CUSTOMER_ID>1</tab:CUSTOMER_ID><tab:ORDER_NUM>14</tab:ORDER_NUM><tab:QUANTITY>1</tab:QUANTITY><tab:SHIPPING_DATE>2006-07-28</tab:SHIPPING_DATE><tab:FREIGHT_COMPANY>PRimeSOft</tab:FREIGHT_COMPANY><tab:SALES_DATE>2006-07-26</tab:SALES_DATE><tab:SHIPPING_COST>901</tab:SHIPPING_COST><tab:PRODUCT_ID>980001</tab:PRODUCT_ID></tab:PURCHASE_ORDER_Record></tab:PURCHASE_ORDER></soapenv:Body></soapenv:Envelope>";

            //http://localhost:11080/PlaceOrderService/PlaceOrderPort
            //Create socket
            String hostname = "localhost";
            int port = 11080;
            InetAddress addr = InetAddress.getByName(hostname);
            Socket sock = new Socket(addr, port);

            //Send header
            String path = "/PlaceOrderService/PlaceOrderPort";
            BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
            // You can use "UTF8" for compatibility with the Microsoft virtual machine.
            wr.write("POST " + path + " HTTP/1.0\r\n");
            wr.write("Host: localhost\r\n");
            wr.write("Content-Length: " + xmldata.length() + "\r\n");
            wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
            wr.write("\r\n");

            //Send data
            wr.write(xmldata);
            wr.flush();

            // Response
            BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println("Response :"+line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

:- More to Continue On Webservices

Creating A Service Out of Java Class

Recently i got a small request from one of my client to provide him a windows/linux service which runs like a deamon and mails some files in the pc every fortnight. As i’m a java guy was trying to find out options how to do this. Luckily we guys have an option in form of Java Service Wrapper .

http://wrapper.tanukisoftware.org

This is a wonderful tool in hands of java developers. It is very simple to create service using this. Following are the things tou have to do.

Import Following Classes In the Main Class which you want interact with Windows/Linux Service.

import org.tanukisoftware.wrapper.WrapperListener;   ( This is implemented so that we can listen to Widows/Linux Service actions Like Start|Stop)
import org.tanukisoftware.wrapper.WrapperManager;  ( This is used to manage our service )

And you have to configure the Wrapper.conf provided here is basic configuration you have to change in default one

# Java Main class.  This class must implement the WrapperListener interface
#  or guarantee that the WrapperManager class is initialized.  Helper
#  classes are provided to do this for you.  See the Integration section
#  of the documentation for details.
wrapper.java.mainclass=com.webaging.DirectoryChangeMailer   (This is class which gets invoked on Service Actions)

# Java Classpath (include wrapper.jar)  Add class path elements as
#  needed starting from 1
wrapper.java.classpath.1=../lib/*.jar   Give path to all jars Similarly
wrapper.java.classpath.2=../conf        This where you have all your property files like log4j.properties

# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=../lib

Here is How you change Java Code

For Example Look at following Main Class

/**
 *
 */
package com.webaging;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;

import com.webaging.listener.FilePresenceListener;

/**
 * @author Ashwin
 *
 */
public class DirectoryChangeMailer implements WrapperListener {

	private static final transient Log logger = LogFactory
			.getLog(DirectoryChangeMailer.class);
	public static Properties prop = null;

	private Scheduler sched = null;

	static {
		try {
			prop = PropertiesLoaderUtils.loadAllProperties("mailer.properties");
		} catch (IOException e) {
			logger.error("Can not find mailer.properties", e);
		}
	}

	private DirectoryChangeMailer() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Start the application. If the JVM was launched from the native
		// Wrapper then the application will wait for the native Wrapper to
		// call the application's start method. Otherwise the start method
		// will be called immediately.
		WrapperManager.start(new DirectoryChangeMailer(), args);

	}

	public void controlEvent(int arg0) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.tanukisoftware.wrapper.WrapperListener#start(java.lang.String[])
	 */
	public Integer start(String[] arg0) {
		try {

			System.out.println("Testing Console Output");

			sched = StdSchedulerFactory.getDefaultScheduler();

			Trigger durectoryReaderTrigger = TriggerUtils
					.makeMinutelyTrigger(1);
			durectoryReaderTrigger.setName("DirectoryListener");
			durectoryReaderTrigger.setGroup("DirectoryListenerGroup");
			durectoryReaderTrigger.setCalendarName("DirectoryListener");

			JobDetail directoryListenerDetail = null;
			try {
				directoryListenerDetail = new JobDetail("DirectoryListenerJob",
						"DirectoryListenerGroup", FilePresenceListener.class);
			} catch (Throwable e) {
				System.out.println("Exception in Creation of Job Detail"
						+ e.getLocalizedMessage());
			}

			directoryListenerDetail.getJobDataMap().put("mailer.from",
					prop.getProperty("mailer.from"));
			directoryListenerDetail.getJobDataMap().put("mailer.to",
					prop.getProperty("mailer.to"));
			directoryListenerDetail.getJobDataMap().put("mailer.subject",
					prop.getProperty("mailer.subject"));
			directoryListenerDetail.getJobDataMap().put("mailer.content",
					prop.getProperty("mailer.content"));
			directoryListenerDetail.getJobDataMap().put("file.directory",
					prop.getProperty("file.directory"));
			directoryListenerDetail.getJobDataMap().put("archive.directory",
					prop.getProperty("archive.directory"));
			directoryListenerDetail.getJobDataMap().put("mailer.host",
					prop.getProperty("mailer.host"));

			logger.info("Job Scheduled For Every 1 Minute");
			sched.scheduleJob(directoryListenerDetail, durectoryReaderTrigger);
			sched.start();

		} catch (Exception e) {
			logger.debug("Exception in Scheduler", e);
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.tanukisoftware.wrapper.WrapperListener#stop(int)
	 */
	public int stop(int arg0) {
		// TODO Auto-generated method stub

		try {
			sched.shutdown();
		} catch (Exception e) {
			logger.error(e);
		}
		return 0;
	}

}

The above Class is self explanatory. It actually implements Following following 3 methods of WrapperListener

public Integer start(String[] arg0) {

public int stop(int arg0) {

public void controlEvent(int arg0) {

One Of These three methods are called when ever you Apply any action on service like start/stop a service.

NOTE:- For all those use class ResourceAsStream method to load some file.

.class.getResource(“/”).getPath();   Gives you path to LIb so be Careful in placing your files to load

Here is sample Directory Structure of How I Placed Files

C:\FileListener
├───bin
│       InstallFileListener-NT.bat
│       PauseFileListener-NT.bat
│       ResumeFileListener-NT.bat
│       StartFileListener-NT.bat
│       StopFileListener-NT.bat
│       UninstallFileListener-NT.bat
│       wrapper-windows-x86-32.exe

├───conf
│       log4j.properties
│       wrapper.conf

├───lib
│       activation.jar
│       commons-beanutils.jar
│       commons-logging-api.jar
│       commons-logging.jar
│       FileListener.jar
│       log4j-1.2.5.jar
│       mail.jar
│       mailapi.jar
│       mailer.properties
│       quartz-all-1.5.2.jar
│       spring.jar
│       wrapper-windows-x86-32.dll
│       wrapper.jar

└───logs
wrapper.log

More tutorials on above subject

Java Mail Over SSL(Gmail As Example)

This is a sample program which can send a mail using gmail server as smtp host.

import java.security.Security;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This sends mail to Intended receipients using Gmail SMTP Server and Account
 *
 * @author Ashwin
 *
 */
public class MailSender {

    private static final transient Log logger = LogFactory
    .getLog(MailSender.class);

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "filelistener.fujitsu@test";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "ashwin.rayaprolu@idhasoft.com",
            "ashwin.rayaprolu@gmail.com" };

    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        String[] filenames = { "c:\\create_tables_oracle.sql" };

        new MailSender().sendSSLMessage(Arrays.asList(sendTo), emailSubjectTxt, emailMsgTxt,
                emailFromAddress, filenames);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    /**
     * @param recipients
     * @param subject
     * @param messageContent
     * @param from
     * @param attachments
     * @throws Exception
     */
    public static void sendMail(List recipients, String subject,
            String messageContent, String from, String[] attachments)
            throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        String[] filenames = { "c:\\create_tables_oracle.sql" };

        new MailSender().sendSSLMessage(recipients, subject, messageContent,
                from, filenames);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    /**
     * @param attachments
     * @param multipart
     * @throws MessagingException
     * @throws AddressException
     */
    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();

            // use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            // assume that the filename you want to send is the same as the
            // actual file name - could alter this to remove the file path
            attachmentBodyPart.setFileName(filename);

            // add the attachment
            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    /**
     * @param recipients
     * @param subject
     * @param messageContent
     * @param from
     * @throws MessagingException
     */
    public void sendSSLMessage(List recipients, String subject,
            String messageContent, String from, String[] attachments)
            throws MessagingException {
        boolean debug = false;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "username", "password");
                    }
                });

        session.setDebug(debug);

        Message message = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        message.setFrom(addressFrom);

        for (Iterator it = recipients.iterator(); it.hasNext();) {
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) it.next()));
        }

        // Setting the Subject and Content Type
        message.setSubject(subject);

        // Create a message part to represent the body text
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(messageContent, "text/html");

        // use a MimeMultipart as we need to handle the file attachments
        Multipart multipart = new MimeMultipart();

        // add the message body to the mime message
        multipart.addBodyPart(messageBodyPart);

        // add any file attachments to the message
        addAtachments(attachments, multipart);

        // Put all message parts in the message
        message.setContent(multipart);

        Transport.send(message);

        logger.info("Sent Mail ");
    }
}

Kindly comment incase of any queries

Few Tips / Useful Statements And Functions in SQL

Whenever i try to write some sql to retreive a report to display to a business user there comes a Question of Formatting. You can do it in 2 ways either by retreiving the data and then start formatting it respective language before creating report or use Database functions and Constructs to achieve this.

Of the above 2 options i prefer logic to be embeeded in SQL to the maximum extent as possible

  1. Because it increases the response time.
  2. It decreases dependency on Programming langugage.

Ofcourse there is a negative side of it . You are not much database agnostic. But i think we can live with it. As changing few hundred lines of SQL isn’t too hard than writing whole logic in new framework.

Listed are Few SQL Constructs We Would Love to Use in our Day to Day Life

  1. COALESCE, NULLIF
  2. CASE …. THEN ….ELSE …. END
  3. FORMAT
  4. DATE_FORMAT
  5. STR_TO_DATE
  6. CONCAT, SUBSTR

I Would explain each of them with an Example.

COALESCE

The wiki definition of the above construct is “COALESCE function accepts a list of parameters, returning the first non-Null value from the list”

In RealWorld when we generate reports we wouldn’t like to show business users values like null ..etc. There come the use of this. Lets case scenario where we store Unit_Price of each and every product we sell in a table and our business head requires a report of all products and their corresponding unit prices. But our database might be also containing products which are not yet launched or for which price i not yet determined. Here comes the use of COALESCE.

Here is sample Query SELECT PRODUCT_NAME,COALESCE(UNIT_PRICE,0) FROM PRODUCTS_TABLE;

This displays report where unit price is shown as ‘0’ for all those products whose price tag is not yet decided.

NULLIF :- This does the same function as above statement. But COALESCE is prefered as this is ubiqutious across DB Server

To Be Continued…