Sunday, April 15, 2012

Spring Java Configuration - in shot

JavaConfig simply provides another mechanism to configure the Spring IoC container, this time in pure Java rather than requiring XML to get the job done

But, you are still allowed to use the classic XML way to define beans and configuration, the JavaConfig is just another alternative solution.
See the different between classic XML definition and JavaConfig to define a bean in Spring container.

Spring XML file: 
 
 
Equivalent configuration in JavaConfig:


package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.HelloWorld;
import com.HelloWorldImpl;

@Configuration
public class AppConfig {

    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
}

now
Spring JavaConfig Sample Java Project-
 
1.  We need to write an Interface first-

package com;
public interface EmployeeAction {
    void printHelloWorld(String msg);
}


2.  Provide the Implementation –

package com; 
public class EmployeeActionImpl implements EmployeeAction {    
private EmployeeService employeeService;     
public EmployeeActionImpl(EmployeeService employeeService) {
        super();
        this.employeeService = employeeService;
    }

    @Override
    public void printHelloWorld(String msg) {
        employeeService.printHelloWorld(msg);
       
    }
 }



3.  Interface for Service
package com;

public interface EmployeeService {

    void printHelloWorld(String msg);
}

4.     Providing Implementation for the above Service

package com;

public class EmployeeServiceImpl implements EmployeeService {

    /* (non-Javadoc)
     * @see com.EmployeeService#printHelloWorld(java.lang.String)
     */
    @Override
    public void printHelloWorld(String msg) {
        System.out.println("Hello Thanooj, Welcome to " + msg);
    }
}




 
/**
 * Configuring JavaConfig class
 */
package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.EmployeeAction;
import com.EmployeeActionImpl;
import com.EmployeeService;
import com.EmployeeServiceImpl;
/**
 * @author thanooj
 *
 */
public @Configuration class AppConfig {
      
    public @Bean EmployeeAction employeeAction() {
        return new EmployeeActionImpl(employeeService());
    }
    public @Bean EmployeeService employeeService() {
        return new EmployeeServiceImpl();
    }
 }
 
Now, working with Client program-

package com.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.EmployeeAction;
import com.config.AppConfig;

public class Client {
   
    public static void main(String[] args) {

        /* ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); */

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        EmployeeAction empObj = (EmployeeAction) context.getBean("employeeAction");
        empObj.printHelloWorld("Spring3 Java Config world.");

    }
}
                      output:
  ----------------------------------------------------------------------------------
 Now
Spring JavaConfig web based sample
 
 
package com;

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

public class EmployeeActionImpl implements EmployeeAction {

    private final Log LOGGER  = LogFactory.getLog(getClass());
    private EmployeeService employeeService;
   
    public EmployeeActionImpl(EmployeeService employeeService) {
        super();
        this.employeeService = employeeService;
    }

    @Override
    public String getWelcomeString() {
        LOGGER.info("inside EmployeeActionImpl getWelcomeString()");
        return employeeService.getWelcomeString();
    }
}

package com;

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

public class EmployeeServiceImpl implements EmployeeService {
   
    private final Log LOGGER  = LogFactory.getLog(getClass());
   
    @Override
    public String getWelcomeString() {
        LOGGER.info("inside EmployeeServiceImpl getWelcomeString()");
        return "Spring 3 MVC Hello World NEW";
    }
}

package com;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.EmployeeAction;

@Controller
public class HelloController {
   
    private final Log LOGGER  = LogFactory.getLog(getClass());
    @Autowired
    private EmployeeAction employeeAction;
   
    @RequestMapping("/welcome")
    public ModelAndView getWelcomeString() {
        LOGGER.info("inside HelloController getWelcomeString()");
        String msg = employeeAction.getWelcomeString();
        LOGGER.info("return value of getWelcomeString() : "+msg);
        return new ModelAndView("message", "msg", msg);
    }
}
-----------------------

 
package config;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.EmployeeAction;
import com.EmployeeActionImpl;
import com.EmployeeService;
import com.EmployeeServiceImpl;


public @Configuration class AppConfig {
   
    private final Log LOGGER  = LogFactory.getLog(getClass());
   
    public @Bean EmployeeAction employeeAction() {
        LOGGER.info("inside AppConfig EmployeeAction");
        return new EmployeeActionImpl(employeeService());
    }
    public @Bean EmployeeService employeeService() {
        LOGGER.info("inside AppConfig EmployeeService");
        return new EmployeeServiceImpl();
    }
   }
------------------ 
                                       mvc-dispatcher-servlet.xml
 
web.xml
message.jsp

output:
References:
http://www.mkyong.com/spring3/spring-3-javaconfig-example/
http://blog.springsource.org/2008/03/26/spring-java-configuration-whats-new-in-m3/


Saturday, April 14, 2012

Install Spellcheck for Notepad++ on Windows

Download Aspell: Visit Aspell’s web site here, download the full installer, and at least one precompiled dictionary. Make sure you are installing the win32 versions of each file.
     

Install Aspell: Now double click on the Aspell full installer which will be titled something like 
Aspell-0-50-3-3-Setup.exe. This will launch the installer and you will have to click Next a few times and choose what icons you also want installed. Keep the default location for the installation which will be C:\Program Files\Aspell.
 

Install Dictionary: Now double click on the precompiled dictionary you have downloaded which in my case was the English dictionary and the file name was Aspell-en-0.50-2-3.exe. This will install an English dictionary into Aspell and allow you to start using it. You can install multiple dictionaries if you would like to spellcheck in multiple languages.
   
 Configure Notepad++: Now click on Notepad++ and it will ask the location of Aspell so type the following into the location field minus the quotes, “C:\Program Files\Aspell\bin”.
     


Test Spellcheck: Now restart Notepad++, enter some text into a new file, and click the spellcheck button to see if it is working.

Wednesday, February 22, 2012

Java Message Service (JMS) using ActiveMQ

Java Message Service(JMS) is an API for standardizing Messaging services. we can send and receive the messages using JMS via Message-Oriented Middleware(MOM) like ActiveMQ.
ActiveMQ is provided by Apache software foundation, one of the popular JMS Provider.

Download the Apache ActiveMQ from Here
Set CLASSPATH = C:\Downloads\apache-activemq-5.5.1\lib
Set PATH = C:\Downloads\apache-activemq-5.5.1\bin

The home directory look like this:
 Start ActiveMQ Server:
  
Testing the Installation
If ActiveMQ is up and running without problems, the Window's console window or the Unix command shell will display information similar to the following log line:
INFO  ActiveMQ JMS Message Broker (ID:apple-s-Computer.local-51222-1140729837569-0:0) has started


ActiveMQ's default port is 61616. From another window run netstat and search for port 61616.
From a Windows console, type:
netstat -an|find "61616" 
 

Monitoring ActiveMQ

http://localhost:8161/admin/

Here we see a sample Producer/consumer application -


 Here is the code of the program sending (producing) the messages:
/**
 * Producer
 */
package com;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;


/**
 * @author thanooj
 *
 */
public class Producer {

    // URL of the JMS server. DEFAULT_BROKER_URL will just mean
    // that JMS server is on localhost
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the queue we will be sending messages to
    private static String subject = "TESTQUEUE";

    public static void main(String[] args) throws JMSException {
        // Getting JMS connection from the server and starting it
        ConnectionFactory connectionFactory =
            new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // JMS messages are sent and received using a Session. We will
        // create here a non-transactional session object. If you want
        // to use transactions you should set the first parameter to 'true'
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

        // Destination represents here our queue 'TESTQUEUE' on the
        // JMS server. You don't have to do anything special on the
        // server to create it, it will be created automatically.
        Destination destination = session.createQueue(subject);

        // MessageProducer is used for sending messages (as opposed
        // to MessageConsumer which is used for receiving them)
        MessageProducer producer = session.createProducer(destination);

        // We will send a small text message saying 'Hello ActiveMQ World!'
        TextMessage message = session.createTextMessage("Hello ActiveMQ World!");

        // Here we are sending the message!
        producer.send(message);
        System.out.println("Sent message '" + message.getText() + "'");

        connection.close();
    }

}

if you run the Producer, you will get output like :

Sent message 'Hello ActiveMQ World!'

If you see something similar to the output above (especially the ‘Sent message’ part) then it means that the message was successfully sent and is now inside the TESTQUEUE queue. You can enter the Queues section in the ActiveMQ’s admin console http://localhost:8161/admin/queues.jsp and see that there is one message sitting in TESTQUEUE:






------------------------------------


/**
 * Consumer
 */
package com;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * @author thanooj
 *
 */
public class Consumer {

    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the queue we will receive messages from
    private static String subject = "TESTQUEUE";

    public static void main(String[] args) throws JMSException {
        // Getting JMS connection from the server
        ConnectionFactory connectionFactory
            = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // Creating session for seding messages
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

        // Getting the queue 'TESTQUEUE'
        Destination destination = session.createQueue(subject);

        // MessageConsumer is used for receiving (consuming) messages
        MessageConsumer consumer = session.createConsumer(destination);

        // Here we receive the message.
        // By default this call is blocking, which means it will wait
        // for a message to arrive on the queue.
        Message message = consumer.receive();

        // There are many types of Message and TextMessage
        // is just one of them. Producer sent us a TextMessage
        // so we must cast to it to get access to its .getText()
        // method.
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message '"
                + textMessage.getText() + "'");
        }
        connection.close();
    }

}
In order to receive that message run now the Consumer program:

output:
Received message 'Hello ActiveMQ World!'
If you are getting above input (or something similar) everything went ok. The message was successfully received.

Monday, February 20, 2012

How to sign JAR files

C:\Documents and Settings\thanooj>keytool -genkey -keystore myKeystore -alias myself
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  thanooj kalathuru
What is the name of your organizational unit?
  [Unknown]:  IT
What is the name of your organization?
  [Unknown]:  Keane India
What is the name of your City or Locality?
  [Unknown]:  Bangalore
What is the name of your State or Province?
  [Unknown]:  KA
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=thanooj kalathuru, OU=IT, O=Keane India, L=Bangalore, ST=KA, C=IN correct?

  [no]:  yes

Enter key password for
        (RETURN if same as keystore password):
Re-enter new password:

-----------------------------------
C:\Documents and Settings\thanooj>keytool -selfcert -alias myself -keystore myKeystore
Enter keystore password:
Enter key password for

C:\Documents and Settings\thanooj>keytool -list -keystore myKeystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

myself, Feb 20, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5): 2F:A9:E8:6F:67:88:9F:A4:C0:03:F1:A9:4D:91:24:A7

---------------------------------------
C:\Documents and Settings\thanooj>jarsigner -keystore myKeystore C:\CoreJava\
SignJarUsingAnt\dist\SayHelloToMe.jar  myself

Enter Passphrase for keystore:
Enter key password for myself:

Warning:
The signer certificate will expire within six months.

C:\Documents and Settings\thanooj>

-----------------------Note----------------------
Enter Password for keystore and myself should be differ.

You can also ref. here for more details

Sunday, January 22, 2012

Open hiper link with new tab or window



The addition of the TARGET attribute to a hyperlink lets you dictate where the linked page opens.
  • target="_blank" Opens the linked page in a new tab or window. 
  • target="_self" Opens the linked page in the same tab or window.. This is the default for ordinary pages and doesn't need to be specified. It has a use when working with frames.
  • target="_parent" Opens the linked page in the parent frame in a frames page. 
  • target="_top" Opens the linked page in a full (i.e. top level) window when used in frames pages. This one is useful for letting a linked page 'break out' of a frame.

Artifactory - Advanced repository manager.

Please visit the configuration page

Friday, January 13, 2012

How to Find All Unread Messages in Gmail

we have two ways:

A. To view all (and only) unread messages in your Gmail account:


  • Type  "is:unread" (or "label:unread") (not including the quotation marks) in the Gmail search field.
  • Click Search Mail.
B. There is a way faster:


  • Choose Settings-> filters.
  • Filters-> Create a new Filter
  • Write: " is: unread" ( without quotes)-> Next( you can use test search before clicking Next)
  • Ok( there is a box appearing, but click OK if you see)
  • the key is: you can see many options for filters
  • if you want to delete it-> check the Delete it box
  • And Remember to check the Also Apply Filter to..( it will be easier to delate a large number of emails at once)
  • You should delete the filter once you finish since it will delete your new emails