Search This Blog

Wednesday, November 19, 2014

Grails - Getting Back Entered UserName LoginController->authfail Spring Security

1. Open Config.groovy
Add
grails.plugin.springsecurity.apf.storeLastUsername=true

2. login/auth.gsp
 
${session['SPRING_SECURITY_LAST_USERNAME']}" name='j_username' id='username' />

 
 --Enjoy

Friday, August 22, 2014

How to Comment the section / paragraph / set of lines in Grails GSP ?

html



grails [ .gsp ]

<%--
         stmt 1
         stmt 2
         ---
--%>

grails [ .groovy ]

// stmt1

or

/*
stmt1
stmt2
*/
 

Grails : How to pass or get param values in g:createLinks

in view.GSP





in YourController.gsp

def displayImageOnFileName ()
    {
        print params
        String fileName = params.fileName        // or params["fileName"]
...
}

Grails Configuring your own Bean or Groovy Object

Configuring Additional Beans

Using the Spring Bean DSL

You can easily register new (or override existing) beans by configuring them in grails-app/conf/spring/resources.groovy which uses the Grails Spring DSL. Beans are defined inside a beans property (a Closure):
 
beans = {
    // beans here
}
 
As a simple example you can configure a bean with the following syntax:
import my.company.MyBeanImpl
beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } }
Once configured, the bean can be auto-wired into Grails artifacts and other classes that support dependency injection (for example BootStrap.groovy and integration tests) by declaring a public field whose name is your bean's name (in this case myBean):
 
class ExampleController {
def myBean … }


Referencing Existing Beans

Beans declared in resources.groovy or resources.xml can reference other beans by convention. For example if you had a BookService class its Spring bean name would be bookService, so your bean would reference it like this in the DSL:
beans = {
    productUtility ( ProductUtility )
            {
          someProperty = 42
          otherProperty = "blue"
          springSecurityService = ref ( "springSecurityService" )
            }
}
or like this in XML:
"myBean" class="my.company.MyBeanImpl"> 
"someProperty" value="42" />
    "otherProperty" value="blue" />
  "springSecurityService" ref="springSecurityService" />
The bean needs a public setter for the bean reference (and also the two simple properties), which in Groovy would be defined like this:
package my.company
class MyBeanImpl { Integer someProperty String otherProperty
   SpringSecurityService springSecurityService  or def springSecurityService 
}




Wednesday, August 13, 2014

Grails Debugging Enable Intelj Idea

Step 1:-
Add in config.groovy

plugin.platformCore.events.catchFlushExceptions = true

Step 2:-
Add in buildconfig.groovy

grails.project.fork = [
        test: false,
        run: false
]



That's It, 
 Just run in debug mode..  [ click debug button, instead of run button/from menu]

Wednesday, May 28, 2014

Tomcat to Support HTTPS / SSL Apache Portable Runtime (APR) with Private key Public Key

1 System Configuration

This document applies to Windows systems running Tomcat 5.5, not to Tomcat 4.1, so it should only be used for sites running MIRC T27 or later. Further, these instructions apply to Tomcat sites running the Apache Portable Runtime (APR). On a Windows computer, this is a dynamically linked library (DLL) that is installed automatically during a Tomcat installation if the user selects the Native option. The APR is strongly recommended, especially on high volume sites, because it is more efficient than the normal Tomcat web server.
You can check whether your system has the APR installed by looking for Tomcat/bin/tcnative-1.dll. If that file is present, Tomcat will automatically use the APR. If your Windows system does not have the APR, you can get it at: http://tomcat.apache.org/tomcat-5.5-doc/apr.html

2 Overview of the Process

When an application (A) establishes an SSL connection to another application (B), it receives encrypted information that identifies B. This information is called a certificate. Certificates are encoded mathematically with keys.
Enabling SSL on a Tomcat installation that is running the APR involves the following steps:
  • Create a private key for Tomcat.
  • Create a certificate for Tomcat.
  • Place the private key and the certificate where Tomcat can find them.
  • Configure Tomcat to enable SSL and use the key and certificate.
  • Do any MIRC configuration necessary for clinical trials.
The first two steps require the use of an open source SSL tool called OpenSSL.

3 Getting OpenSSL

OpenSSL is developed by the OpenSSL Project. Its web site is: http://www.openssl.org.
A special OpenSSL installer for Windows is available on the Shining Light site at: http://www.slproweb.com/products/Win32OpenSSL.html.
After downloading the installer, run it. The result is a directory called OpenSSL. Inside that directory is a bin directory. Although the installer will create entries in the Programs menu, those entries only point to documentation (and to the uninstaller). The OpenSSL program is a command-line utility. In the instructions that follow, it is assumed that the OpenSSL directory is located in the root of the D drive (D:\OpenSSL).

4 Creating a Private Key for Tomcat

To enable SSL communication, Tomcat must have a certificate. To create a certificate for Tomcat, you must first have a private key. This section will demonstrate how to create a private key using OpenSSL.
To start, create a directory in which to work. In this example, the directory is called sandbox.
  • Launch a DOS window. (Click Start -- Run… and type cmd. Then click OK.)
  • Navigate to your sandbox directory.
  • Enter the command:
d:\openssl\bin\openssl.exe
  • OpenSSL will prompt with: OpenSSL>
  • Enter the command:
genrsa –des3 –out tomcatkey.pem 2048
  • OpenSSL will then ask you for a pass phrase for the key. Enter any phrase you want. In this example, we will use the pass phrase tomcat. After entering the pass phrase, OpenSSL will ask you to repeat it.
  • OpenSSL will then create the private key and store it in the sandbox directory in a file called tomcatkey.pem.
You can remain in the OpenSSL program for the next step.

5 Creating a Certificate for Tomcat

Once you have a private key for Tomcat, you must create a certificate. Assuming you are still running the OpenSSL program from the previous step, enter the command:
req –new –x509 –key tomcatkey.pem –out tomcatcert.pem –days 1095
OpenSSL will ask you for the pass phrase that you defined for the private key. This command creates a self-signed certificate with a lifetime of 3 years (1095 days), using the private key. OpenSSL will store that certificate in the sandbox directory in a file called tomcatcert.pem.

6 Storing the Private Key and the Certificate

You must now place the tomcatkey.pem and tomcatcert.pem files where Tomcat can find them. The easiest place to put them is in the top-level Tomcat directory.

7 Enabling SSL in the Tomcat server.xml File

Having put the files in the top-level Tomcat directory, you must now enable SSL in the server.xml file which is located in the conf directory under the top-level Tomcat directory. Using the Tomcat directory in the section above as an example, first make a backup copy of the Tomcat\conf\server.xml file (just in case) and store it somewhere safe. Then open Tomcat\conf\server.xml with a text editor.
Look for the section of code that contains the main connector:
    

 
About 10 lines under that look for the code for the SSL connector:
    


Remove the start and end comment lines, making the code read:
 

 
Next, it is necessary to tell Tomcat where the key and certificate are and how to access them. Add the four indented lines near the bottom of the box below, making the code read:
 

 
In place of tomcat in the SSLPassword attribute, you must use the pass phrase you chose for the private key. Then, save the file.
This will create an SSL connector on port 8443 when Tomcat is restarted. If you decide to use a different port than 8443, you must change the redirectPort attributes in other Connector elements to point to the port you chose; otherwise, redirections to the SSL port will not occur.
Note: enabling SSL on your site does not disable non-SSL connections, so your site will also continue to work with browsers that are not SSL-enabled.
When modifying XML files, it is usually a good idea to confirm that you have not made a mistake in typing and inadvertently created a file that is not well-formed. An easy way to check is to open the file with Internet Explorer, which will parse the file and either display the text in a nicely formatted window or tell you about the first error it found.
At this point, start (or restart) Tomcat. Launch a browser and go to:
https://localhost:8443/tomcat.gif
If your certificate is self-signed, your browser will warn you. You should tell the browser to import the certificate and proceed. You should then see the little Tomcat logo. If you do, you’re done configuring Tomcat.

Enable SSL Https in Tomcat

1. Generate Keystore

First, uses “keytool” command to create a self-signed certificate. During the keystore creation process, you need to assign a password and fill in the certificate’s detail.
$Tomcat\bin>keytool -genkey -alias mkyong -keyalg RSA -keystore c:\mkyongkeystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  yong mook kim
What is the name of your organizational unit?
  //omitted to save space
  [no]:  yes
 
Enter key password for <mkyong>
        (RETURN if same as keystore password):
Re-enter new password:
 
$Tomcat\bin>
Here, you just created a certificate named “mkyongkeystore“, which locate at “c:\“.


Certificate Details
You can use same “keytool” command to list the existing certificate’s detail
$Tomcat\bin>keytool -list -keystore c:\mkyongkeystore
Enter keystore password:
 
Keystore type: JKS
Keystore provider: SUN
 
Your keystore contains 1 entry
 
mkyong, 14 Disember 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): C8:DD:A1:AF:9F:55:A0:7F:6E:98:10:DE:8C:63:1B:A5
 
$Tomcat\bin>
 
 

2. Connector in server.xml

Next, locate your Tomcat’s server configuration file at $Tomcat\conf\server.xml, modify it by adding a connector element to support for SSL or https connection.
File : $Tomcat\conf\server.xml
 //...
 <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
 
 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
        keystoreFile="c:\mkyongkeystore"
        keystorePass="password" />
  //...
Note
keystorePass="password" is the password you assigned to your keystore via “keytool” command.
 
 

3. Done

Saved it and restart Tomcat, access to https://localhost:8443/

In this example, we are using Google Chrome to access the Tomcat configured SSL site, and you may notice a crossed icon appear before the https protocol :), this is caused by the self-signed certificate and Google chrome just do not trust it.
In production environment, you should consider buy a signed certificate from trusted SSL service provider like verisign/digicert or sign it with your own CA server
 
 

Wednesday, April 30, 2014

LDAP - ADS User Creation

Here is the example to create LDAP - ADS User Creation.

Files:-
Create a main folder and paste this two properties file.
Create a sub folders like com/vijay/ldap and paste the java content in Ldap.java.

Ldap.properties
         To make connection with your Ldap/ADS.
Ldap-user-settings.properties
         To make settings for your new user.
 Ldap.java
          It is a java program which can connect ldap and create user based on your distinguish Name.


ldap.properties

#* @author drvijay
#* @date 29-04-2014 4PM

ldap.initial.context.factory=com.sun.jndi.ldap.LdapCtxFactory
ldap.security.authentication=simple

ldap.domain.name=domain.com
ldap.domain.root=DC=sdex,DC=com
ldap.admin.name=CN=Administrator,CN=Users,DC=domain,DC=com
ldap.organisationUnit=ou=subOrg,ou=parentOrg
ldap.admin.pass=test123
ldap.domain.url=ldap://127.0.0.1:389



#ldap.organisationUnit=ou=subOrg,ou=parentOrg  you can change the ou= based on your ldap structure


ldap-user-settings.properties

#* @author drvijay
#* @date 29-04-2014 4PM

#loop configuration
ldap.concatenate.start.value=1
ldap.concatenate.end.value=1

#loop attributes
ldap.userName=userName{0}
ldap.firstName=Vijay{0}
ldap.displayName={0} D R

#repeated attributes
ldap.lastName=P
ldap.userPassword=test123
ldap.mobile=9842088860
ldap.company=infovijay
ldap.mail=drvijayy2k2@gmail.com
ldap.postalCode=636702
ldap.st=TN
ldap.city=DPI
ldap.country=IN


Ldap.Java

package com.vijay.ldap;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 *
 * @author drvijay
 * @date 29-04-2014 4PM
 */

public class Ldap
{

    private static ResourceBundle                ldapSystemProperties        = ResourceBundle.getBundle ( "ldap" );
    private static ResourceBundle                ldapUserSettingsProperties    = ResourceBundle.getBundle ( "ldap-user-settings" );

    private static String                        DOMAIN_NAME                    = ldapSystemProperties.getString ( "ldap.domain.name" );
    private static String                        DOMAIN_ROOT                    = ldapSystemProperties.getString ( "ldap.domain.root" );
    private static String                        ADMIN_NAME                    = ldapSystemProperties.getString ( "ldap.admin.name" );
    private static String                        ADMIN_PASS                    = ldapSystemProperties.getString ( "ldap.admin.pass" );
    private static String                        DOMAIN_URL                    = ldapSystemProperties.getString ( "ldap.domain.url" );
    private static String                        INITIAL_CONTEXT_FACTORY        = ldapSystemProperties.getString ( "ldap.initial.context.factory" );
    private static String                        SECURITY_AUTHENTICATION        = ldapSystemProperties.getString ( "ldap.security.authentication" );
    private static String                        _organisationUnit            = ldapSystemProperties.getString ( "ldap.organisationUnit" );

    // some useful constants from lmaccess.h
    private static int                            UF_ACCOUNTDISABLE            = 0x0002;
    private static int                            UF_PASSWD_NOTREQD            = 0x0020;
    private static int                            UF_PASSWD_CANT_CHANGE        = 0x0040;
    private static int                            UF_NORMAL_ACCOUNT            = 0x0200;
    private static int                            UF_DONT_EXPIRE_PASSWD        = 0x10000;
    private static int                            UF_PASSWORD_EXPIRED            = 0x800000;

    private static String                        _userName                    = ldapUserSettingsProperties.getString ( "ldap.userName" );
    private static String                        _firstName                    = ldapUserSettingsProperties.getString ( "ldap.firstName" );
    private static String                        _lastName                    = ldapUserSettingsProperties.getString ( "ldap.lastName" );
    private static String                        _userPassword                = ldapUserSettingsProperties.getString ( "ldap.userPassword" );
    private static String                        _mobile                        = ldapUserSettingsProperties.getString ( "ldap.mobile" );
    private static String                        _company                    = ldapUserSettingsProperties.getString ( "ldap.company" );
    private static String                        _displayName                = ldapUserSettingsProperties.getString ( "ldap.displayName" );
    private static String                        _mail                        = ldapUserSettingsProperties.getString ( "ldap.mail" );
    private static String                        _postalCode                    = ldapUserSettingsProperties.getString ( "ldap.postalCode" );
    private static String                        _st                            = ldapUserSettingsProperties.getString ( "ldap.st" );
    private static String                        _city                        = ldapUserSettingsProperties.getString ( "ldap.city" );
    private static String                        _country                    = ldapUserSettingsProperties.getString ( "ldap.country" );

    private static String                        cnValue;

    private static int                            loopStart                    = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.start.value" ) );
    private static int                            loopEnd                        = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.end.value" ) );

    private static LdapContext                    context;
    private static Hashtable     env                            = new Hashtable ();

    /**
     * Instantiates a new ldap.
     */
    public Ldap ()
    {
    }

    /**
     * Instantiates a new ldap.
     *
     * @param userName
     *            the user name
     * @param firstName
     *            the first name
     * @param lastName
     *            the last name
     * @param organisationUnit
     *            the organisation unit
     */
    public Ldap ( String userName, String firstName, String lastName, String organisationUnit )
    {
        this._userName = userName;
        this._firstName = firstName;
        this._lastName = lastName;
        this._organisationUnit = organisationUnit;
    }

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main ( String [] args )
    {
        // Ldap user = new Ldap ( userName, firstName, lastName, organisationUnit );
        Ldap user = new Ldap ();

        try
        {
            env.put ( Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY );
            env.put ( Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION );
            env.put ( Context.SECURITY_PRINCIPAL, ADMIN_NAME );
            env.put ( Context.SECURITY_CREDENTIALS, ADMIN_PASS );
            env.put ( Context.PROVIDER_URL, DOMAIN_URL );
            context = new InitialLdapContext ( env, null );

            for ( int i = loopStart; i <= loopEnd; i++ )
            {
                try
                {
                    // replace dynamic parameters from properties
                    _userName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.userName" ), i );
                    _firstName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.firstName" ), i );
                    _displayName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.displayName" ), _firstName );

                    // create user
                    System.out.println ( "User : " + _userName + " created Status : " + user.addUser () );

                    // DirContext sslCtx = new InitialDirContext ( env );
                    // changePassword ( sslCtx, getUserDN ( cnValue, user.organisationUnit ), "test123" );
                }
                catch ( Exception e )
                {
                    System.err.println ( e.getMessage () );
                    e.printStackTrace ();
                }
            }

        }
        catch ( NamingException e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
        catch ( Exception e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
    }

    /**
     * Gets the user dn.
     *
     * @param aUsername
     *            the a username
     * @param aOU
     *            the a ou
     * @return the user dn
     */
    private static String getUserDN ( String aUsername, String aOU )
    {
        return "cn=" + aUsername + "," + aOU + "," + DOMAIN_ROOT;
    }

    /**
     * Adds the user.
     *
     * @return true, if successful
     * @throws NamingException
     *             the naming exception
     */
    public boolean addUser () throws NamingException
    {

        Attributes container = new BasicAttributes ();

        try
        {

            Attribute objClasses = new BasicAttribute ( "objectClass" );
            objClasses.add ( "top" );
            objClasses.add ( "person" );
            objClasses.add ( "organizationalPerson" );
            objClasses.add ( "user" );
            container.put ( objClasses );

            cnValue = new StringBuffer ( _firstName ).append ( " " ).append ( _lastName ).toString ();

            Attribute cn = new BasicAttribute ( "cn", cnValue );
            Attribute sAMAccountName = new BasicAttribute ( "sAMAccountName", _userName );
            Attribute principalName = new BasicAttribute ( "userPrincipalName", _userName + "@" + DOMAIN_NAME );

            Attribute givenName = new BasicAttribute ( "givenName", _firstName );
            Attribute sn = new BasicAttribute ( "sn", _lastName );
            Attribute uid = new BasicAttribute ( "uid", _userName );

            Attribute userPassword = new BasicAttribute ( "userpassword", _userPassword );
            Attribute mobile = new BasicAttribute ( "mobile", _mobile );
            Attribute company = new BasicAttribute ( "company", _company );
            Attribute displayName = new BasicAttribute ( "displayName", _displayName );
            Attribute mail = new BasicAttribute ( "mail", _mail );
            Attribute postalCode = new BasicAttribute ( "postalCode", _postalCode );
            Attribute st = new BasicAttribute ( "st", _st );
            Attribute l = new BasicAttribute ( "l", _city );
            Attribute c = new BasicAttribute ( "c", _country );
            Attribute userAccountControl = new BasicAttribute ( "userAccountControl", Integer.toString ( UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_DONT_EXPIRE_PASSWD ) );

            container.put ( sAMAccountName );
            container.put ( principalName );
            container.put ( cn );
            container.put ( sn );
            container.put ( givenName );
            container.put ( uid );
            container.put ( c );
            container.put ( l );
            container.put ( st );
            container.put ( postalCode );
            container.put ( mail );
            container.put ( displayName );
            container.put ( company );
            container.put ( mobile );
            container.put ( userAccountControl );
            container.put ( userPassword );

            context.createSubcontext ( getUserDN ( cnValue, _organisationUnit ), container );
            return true;
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            return false;
        }
    }

    /**
     * Gets the time.
     *
     * @param pwdLastSet
     *            the pwd last set
     * @return the time
     */
    private static Calendar getTime ( long pwdLastSet )
    {
        long javaTime = pwdLastSet - 0x19db1ded53e8000L;
        javaTime /= 10000;

        Calendar cal = Calendar.getInstance ();
        cal.setTimeInMillis ( javaTime );
        return cal;
    }

    /**
     * Encode password.
     *
     * @param pass
     *            the pass
     * @return the byte[]
     * @throws UnsupportedEncodingException
     *             the unsupported encoding exception
     */
    private static byte [] encodePassword ( String pass ) throws UnsupportedEncodingException
    {
        String ATT_ENCODING = "UTF-16LE";
        String pwd = "\"" + pass + "\"";
        byte bytes[] = pwd.getBytes ( ATT_ENCODING );

        return bytes;
    }

    /**
     * Change password.
     *
     * @param ctx
     *            the ctx
     * @param argRDN
     *            the arg rdn
     * @param argNewPassword
     *            the arg new password
     * @throws NamingException
     *             the naming exception
     */
    public static void changePassword ( DirContext ctx, String argRDN, String argNewPassword ) throws NamingException
    {

        ModificationItem [] modificationItem = new ModificationItem[1];
        try
        {
            modificationItem[0] = new ModificationItem ( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute ( "unicodePwd", encodePassword ( argNewPassword ) ) );
            ctx.modifyAttributes ( argRDN, modificationItem );
        }
        catch ( UnsupportedEncodingException e1 )
        {
            throw new RuntimeException ( e1.toString () );
        }
        catch ( NamingException e1 )
        {
            throw e1;
        }
    }

}








Tuesday, April 22, 2014

Point to Point Queue Messaging

Point to Point Messaging Program

The Hello World application consists of a sender application that sends a "Hello" message to a queue. This message will be received by one queue receiver connected to the queue in question. If no receivers are connected, the message will be retained on the queue. If more queue receivers are connected, they will receive messages in a round-robin fashion
There are four sample programs for this section:
  • Queue Sender
  • Synchronous Queue Receiver
  • Asynchronous Queue Receiver
  • Queue Browser
Note that none of the examples in this section show code for handling exceptions. Although this improves the readability of the example code, application programmers should notice that almost all methods in the JMS API's may raise a JMSException if the JMS provider fails.

Queue Sender

The queue sender application performs the following steps:
  1. Obtain an InitialContext object for the JMS server.
  2. Use the context object to lookup a specific queue, in this case, queue0.
  3. Use the context object to lookup the queue connection factory. You only need to specify the queue/connectionFactory with the lookup because the batch file that you run this sample from has set the System properties to point to the appropriate root context for the System namespace. If you were using the JMS server with the Novell exteNd Application Server, you would have to specify the lookup as follows:
     QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
                lookup("iiop://localhost:53506/queue/connectionFactory");
     
  4. Use the QueueConnectionFactory to create a QueueConnection. The QueueConnection represents a physical connection to the JMS server.
  5. Create a queue session. The first parameter in the createQueueSession method decides whether or not the session is transacted. Here, we use a non-transacted session. The second parameter decided the delivery mode, which is never used for sending applications.
  6. Create a queue sender for queue0 and create a message.
  7. Send the "Hello" message to queue0.
  8. Close the queue connection. This will in turn close both the session and the QueueSender.
The full source code for the sender application is shown below:
package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSender;
import javax.jms.DeliveryMode;
import javax.jms.QueueSession;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Sender
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.DUPS_OK_ACKNOWLEDGE);
                                                                          
       // create a queue sender
       QueueSender queueSender = queueSession.createSender(queue);
       queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                                                                          
       // create a simple message to say "Hello"
       TextMessage message = queueSession.createTextMessage("Hello");
                                                                          
       // send the message
       queueSender.send(message);
                                                                          
       // print what we did
       System.out.println("sent: " + message.getText());
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
The Sender class sets the delivery mode to NON_PERSISTENT before sending the message. This means that the message will be lost in case the JMS server crashes. Since NON_PERSISTENT messages giver better performance than PERSISTENT messages, applications should set the delivery mode to NON_PERSISTENT whenever guaranteed delivery is not a requirement.

Synchronous Queue Receiver

The receive application performs the same initial steps as the queue sender because you always have to find a queue object using the initial context, connect to the queue and create a session as shown here.
Instead of a QueueSender object, the receiver application creates a QueueReceiver from which messages can be received synchronously. Note that the receiver application must start the connection before any messages can be received.
The receiver application uses a non-transacted session with automatic message acknowledgement. This means that message will automatically be acknowledged by the session right before the receive method returns the message to the application.
Below is the source for the Receiver class:

package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Receiver
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // receive a message
       TextMessage message = (TextMessage) queueReceiver.receive();
                                                                          
       // print the message
       System.out.println("received: " + message.getText());
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
If the connection is not started, the receive method will block forever (or until some other thread starts the connection). If a client want to temporarily stop delivery of messages, the connection can be stopped and then re-started later.

Asynchronous Queue Receiver

The AsyncReceiver class illustrates the use of message listeners. A message listener is a regular Java class that implements the MessageListener interface. This interface has a single onMessage method, which is called by JMS when messages arrive at a destination.
As with the synchronous receiver, the AsyncReceiver class performs the same initial steps to create a QueueReceiver. Then, the setMessageListener method is called to register this as a message listener. As with a synchronous receiver, messages will not be delivered until the start method is called on the connection.
Since acknowledge mode is set to automatic, JMS will acknowledge messages right after calls to the onMessage method returns. Note that onMessage is not allowed to throw any exceptions. You must catch all exceptions and deal with them somehow in the onMessage method.
In the synchronous receiver, the receive method can raise an exception if the JMS provider fails. Due to its asynchronous nature, this is not possible with message listeners. Therefore, it is possible to register an exception listener with the connection, which can pick up such exceptions.
Below is the full source for the AsyncReceiver class:
package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.jms.MessageListener;
import javax.jms.JMSException;
import javax.jms.ExceptionListener;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class AsyncReceiver implements MessageListener, ExceptionListener
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);
                                                                          
       // set an asynchronous message listener
       AsyncReceiver asyncReceiver = new AsyncReceiver();
       queueReceiver.setMessageListener(asyncReceiver);
                                                                          
       // set an asynchronous exception listener on the connection
       queueConn.setExceptionListener(asyncReceiver);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // wait for messages
       System.out.print("waiting for messages");
       for (int i = 0; i < 10; i++) {
          Thread.sleep(1000);
          System.out.print(".");
       }
       System.out.println();
                                                                          
       // close the queue connection
       queueConn.close();
    }
                                                                           
    /**
       This method is called asynchronously by JMS when a message arrives
       at the queue. Client applications must not throw any exceptions in
       the onMessage method.
       @param message A JMS message.
     */
    public void onMessage(Message message)
    {
       TextMessage msg = (TextMessage) message;
       try {
          System.out.println("received: " + msg.getText());
       } catch (JMSException ex) {
          ex.printStackTrace();
       }
    }
                                                                           
    /**
       This method is called asynchronously by JMS when some error occurs.
       When using an asynchronous message listener it is recommended to use
       an exception listener also since JMS have no way to report errors
       otherwise.
       @param exception A JMS exception.
     */
    public void onException(JMSException exception)
    {
       System.err.println("an error occurred: " + exception);
    }
}
As documented in the source code, it is recommended to always set a connection exception listener when using asynchronous message listeners. This will allow you to detect any runtime problems, including a crash of the JMS server.
The JMSException API supports the getLinkedException method, which can be used to get the root cause of the exception (if any). As an example, if you raise a RuntimeException in the onMessage method, the linked exception will be this runtime exception when onException is called.

Queue Browser

A queue browser can be used to look at a queue without consuming any messages. The queue browser must perform the same initial steps as any other JMS client application, i.e. get a session object, which is a factory for QueueBrowser objects.
The QueueBrowser supports an iterator, which can be used to enumerate the messages on a queue. The following example shows how to count the number of messages on a queue. Note that acknowledge mode is not meaningful to a queue browser:
package pointToPoint;
                                                                           
import java.util.Enumeration;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.QueueSession;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Browser
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue browser
       QueueBrowser queueBrowser = queueSession.createBrowser(queue);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // browse the messages
       Enumeration e = queueBrowser.getEnumeration();
       int numMsgs = 0;
                                                                          
       // count number of messages
       while (e.hasMoreElements()) {
          Message message = (Message) e.nextElement();
          numMsgs++;
       }
                                                                          
       System.out.println(queue + " has " + numMsgs + " messages");
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
The order of messages returned by the enumeration reflects the order of messages a regular message receiver would see. Note that a queue browser represents a static snapshop of the queue. If more messages are added to the queue while browsing, this will not be available to the queue browser.

Thanks to 
http://www.novell.com  [Copy Paste]



Wednesday, April 16, 2014

How to Send Mail to Outlook i Calender Meeting Remainder ( ICS )


//use below sample and enjoy, which i taken from another site and modify with my choice..
//hope this will help you a lot and give me a copy of yours if u done any modification..

package com.test;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailRemainder
{
    public BodyPart buildHtmlTextPart () throws MessagingException
    {

        MimeBodyPart descriptionPart = new MimeBodyPart ();

        // Note: even if the content is spcified as being text/html, outlook won't read correctly tables at all
        // and only some properties from div:s. Thus, try to avoid too fancy content
        String content = "Sample Body Content";
        descriptionPart.setContent ( content, "text/html; charset=utf-8" );

        return descriptionPart;
    }

    // define somewhere the icalendar date format
    private static SimpleDateFormat    iCalendarDateFormat    = new SimpleDateFormat ( "yyyyMMdd'T'HHmm'00'" );

    public BodyPart buildCalendarPart (String fromMailId, String location, String description ) throws Exception
    {

        BodyPart calendarPart = new MimeBodyPart ();

        //System.out.println ( TimeZone.getTimeZone ( "UTC" ) );
        Calendar cal = Calendar.getInstance ();   //TimeZone.getDefault () //TimeZone.getTimeZone ( "UTC" )
        //cal.add ( Calendar.DAY_OF_MONTH, 1 );
        cal.add ( Calendar.MINUTE, 10 );
        Date start = cal.getTime ();
        System.out.println ( "Meeting Start Time : " + start );
       
        //cal.add ( Calendar.HOUR_OF_DAY, 3 );
        cal.add ( Calendar.MINUTE, 15 );
        Date end = cal.getTime ();
        System.out.println ( "Meeting End Time : " + end );
       
        // check the icalendar spec in order to build a more complicated meeting request
        String calendarContent =
                "BEGIN:VCALENDAR\n"
               
                    + "METHOD:REQUEST\n"
                    + "PRODID:-//Sdex Portal//NONSGML Sdex//EN\n"
                    + "VERSION:2.0\n"
               
                    + "BEGIN:VTIMEZONE\n"
                    + "TZID:India Standard Time\n"
                        + "BEGIN:STANDARD\n"
                        + "DTSTART:" + iCalendarDateFormat.format ( start ) + "\n"
                        + "TZOFFSETFROM:+0530\n"
                        + "TZOFFSETTO:+0530\n"
                        + "END:STANDARD\n"
                    + "END:VTIMEZONE\n"
                   
                    + "BEGIN:VEVENT\n"
                    + "DTSTAMP:" + iCalendarDateFormat.format ( start ) + "\n"
                    + "DTSTART:" + iCalendarDateFormat.format ( start ) + "\n"
                    + "DTEND:" + iCalendarDateFormat.format ( end ) + "\n"
                    + "SUMMARY:test request\n"
                    + "UID:" + Math.random () +"\n"
                    + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"+ fromMailId +"\n"
                    + "ORGANIZER:MAILTO:"+ fromMailId +"\n"
                    + "LOCATION:"+ location +"\n"
                    + "DESCRIPTION:"+ description +"\n"
                    + "SEQUENCE:1\n"
                    + "PRIORITY:1\n"
                    + "CLASS:PUBLIC\n"
                    + "STATUS:CONFIRMED\n"
                    + "TRANSP:OPAQUE\n"
                        + "BEGIN:VALARM\n"
                        + "ACTION:DISPLAY\n"
                        + "DESCRIPTION:REMINDER\n"
                        + "TRIGGER;RELATED=START:-PT00H15M00S\n"
                        + "END:VALARM\n"
                    + "END:VEVENT\n"
                   
                + "END:VCALENDAR";

        calendarPart.addHeader ( "Content-Class", "urn:content-classes:calendarmessage" );
        calendarPart.setContent ( calendarContent, "text/calendar;method=REQUEST" );

        return calendarPart;
    }

    public static void main ( String args[] ) throws Exception
    {
        String fromMailId = "vijay@XXXXXXX.com";
        String toMailId = "vkumar@XXXXXXX.com";
        final String userName = "vijay@XXXXXXX.com";
        final String password = "test123";
        String protocol = "smtp";
        int port  = 25;
       
        Session session = null;
        // Security.addProvider ( new com.sun.net.ssl.internal.ssl.Provider () ); //this will use for SSL/HTTPS
        Properties props = new Properties ();
        props.setProperty ( "mail.transport.protocol", protocol );
        props.setProperty ( "mail.host", "smtp.yourserver.com" );
        props.put ( "mail.debug", "false" );
        props.put ( "mail.smtp.port", port );
        if ( Boolean.parseBoolean ( "true" ) )
        {
            props.put ( "mail.smtp.auth", "true" );
            props.put ( "mail.smtp.socketFactory.port", port );
        }
        if ( Boolean.parseBoolean ( "false" ) )
        {
            props.put ( "mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );
            props.put ( "mail.smtp.socketFactory.fallback", "false" );
        }
        if ( Boolean.parseBoolean ( "true" ) )
        {
            session = Session.getDefaultInstance ( props, new javax.mail.Authenticator () {
                // @Override
                protected PasswordAuthentication getPasswordAuthentication ()
                {
                    return new PasswordAuthentication ( userName, password );
                }
            } );
        }
        else
        {
            session = Session.getInstance ( props );
        }

        // session.setDebug ( true );

        EmailRemainder emailRemainder = new EmailRemainder ();
        MimeMessage message = new MimeMessage ( session );
        message.setFrom ( new InternetAddress ( fromMailId ) );
        message.setSubject ( "Subject: Hi 2" );
        message.addRecipient ( Message.RecipientType.TO, new InternetAddress ( toMailId ) );
        // Create an alternative Multipart
        Multipart multipart = new MimeMultipart ( "alternative" );
        // part 1, html text
        BodyPart messageBodyPart = emailRemainder.buildHtmlTextPart ();
        multipart.addBodyPart ( messageBodyPart );

        // Add part two, the calendar
        BodyPart calendarPart = emailRemainder.buildCalendarPart ( fromMailId, "Meeting on your domain.com", "sample description" );
        multipart.addBodyPart ( calendarPart );

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

        // send the message
        Transport transport = session.getTransport ( protocol );
        transport.connect ();
        transport.sendMessage ( message, message.getAllRecipients () );
        transport.close ();

            System.out.println ("done");
    }
}



Hit Counter


View My Stats