Search This Blog

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");
    }
}



Friday, November 8, 2013

JBOSS 7 :: InvalidMappingException Unable to read XML readMappingDocument

In standalone.xml

Remove/Modify
*************


Add
***

           
               
           






Thursday, November 7, 2013

Jbpm web application JBoss

Simple Eclipse project which creates a deployable web app which contains all the basics to run JBPM 5.4 inside a web app ussing persistence. The project is deployed in a JBoss AS 7.1.1 server which was created using the JBPM 5.4 installer. This project uses PostgreSQL as the database. The JBPM process is read from a local Guvnor instance.

This example was created by combining a few other existing examples together and then adding some stuff I've figured out along the way.

Anyway, hopefully this will help get people going using JBPM in thier own web apps.

Here are the instructions which are also found in the web apps home page:

  1. Install your jdbc drivers into your JBoss AS installation. (I did mine as a module following this.)
  2. Create a new empty database/schema called "testJBPM" in your database with permissions for a user "jbpm" and password "jbpm". (If you are not using PostgreSQL or want to change the connection information, update jbpm-in-webapp-ds.xml)
  3. Create a new package in Guvnor called "testPackage". (Change the URL in KBaseService and the packageName in ScriptTeask.bpmn if you want to use a different package name)
  4. Create a pojo model jar containing HelloService.java and Person.java the and deploy it to the testPackage inside guvnor. (From eclipse basically select the 2 files and do "Export->Java->Jar file. Name it whatever and upload it to Guvnor")
  5. Upload ScriptTask.bpmn to Guvnor in the same package.
  6. Build the testPackage in Guvnor (Click "Build package" button in the edit tab))
  7. Deploy this web app to your jboss server (The needed tables will be built in your database because "hibernate.hbm2ddl.auto" is set to "update" in persistence.xml)
  8. Go to http://localhost:8080/jbpm-in-webapp/
Download src : https://community.jboss.org/servlet/JiveServlet/download/48240-1-75921/jbpm-in-webapp.zip
 

Eclipse plug-in Installation for jBPM5

Here are the manual steps to install jBPM5 plug-in and run a sample example in Eclipse.This install is done automatically after running jBPM5 installer. Following procedure, however, might be useful if you want to understand (or having problems completing the install) the main install steps provided in the automated install script for JBPM5.2. The install instructions for the previous release 5.1 can also be found in the attachment jbpm5.1install.zip.

1.) Download Eclipse Helios:
http://download.eclipse.org/technology/epp/downloads/release/helios/SR2/eclipse-java-helios-SR2-win32.zip

Unzip this into a directory, say JBPM5

2.) Download Drools and JBPM5 plugin, i.e., org.drools.updatesite-5.3.1.Final-assembly.zip:
https://repository.jboss.org/nexus/content/repositories/releases/org/drools/org.drools.updatesite/5.3.1.Final/org.drools.updatesite-5.3.1.Final-assembly.zip


Unzip this plugin to a temp directory, say TEMP\drools-update-site. Copy 'features' and 'plugins' directories from TEMP\drools-update-site into
JBPM5\eclipse

It is required to have a runtime dependant libraries that a jBPM5 sample can use.

3.) Download the libraries (jbpm-5.2.0.Final-bin.zip ) from http://sourceforge.net/projects/jbpm/files/jBPM%205/jbpm-5.2.0.Final/jbpm-5.2.0.Final-bin.zip/download and unzip into a directory, say JBPM5\runtime.

4.) Create a new jBPM sample project in Eclipse and use the runtime libraries downloaded in Step 4.

Install JBPM in Eclipse

jBPM 5 application using a simple Hello World project in combination with the Eclipse jBPM plugin.

jBPM 5 can be freely downloaded from sourceforge here.
jBPM 5 is basically distributed in two formats: the jbpm-5.X.X.Final-installer-full.zip which includes really lots of stuff (including the core libraries, the JBoss AS, the Eclipse plugins and the Web application consoles) and the jbpm-5.X.X.Final-bin.zip which contains just the jBPM 5 libraries and thus it's good for distributing it in production.

For the purpose of learning we will download the latest jbpm-5.X.X.Final-installer-full.zip which contains all the stuff needed to learn jBPM. Once downloaded unzip the package in a folder of your preference.
  You need to have Jakarta ant installed in order to continue
Ok now you can get started in two ways:

1# Option: Installing all the components contained in the package using:
 
ant install.demo     
2# Option: If you want to install the component step by step you will understand better the role of every single component of jBPM 5. Here's how to do it:

You need to have Eclipse Indigo installed in order to continue
Now open the file build.properties which is used by ant and specify the path where Eclipse is installed:
For example, if you have installed Eclipse into C:\
# the home of your eclipse installation will be 
# used to deploy the Eclipse plugin to
eclipse.home=C:\\eclipse
Ok, now we will install the jBPM Eclipse plugin with the following ant command:
ant install.droolsjbpm-eclipse.into.eclipse
And then we will install the jBPM runtime:
ant install.jBPM.runtime

Creating your first jBPM 5 project:

Good, that's all to get started. Now start Eclipse and create a new jBPM project:
jbpm 5 tutorial jboss example
In this tutorial we will see a basic hello world process, (in the next one e will show how to deal with of human tasks and data persistence).

jbpm 5 tutorial jboss example
Next you need to specify where your jBPM runtime environment has been installed (If you have unpacked the jbpm-installer in C:\ it will be C:\jbpm-installer\runtime)
jbpm 5 example jboss jbpm5
Ok. Now Eclipse shows your first jBPM5 project which contains barely:
  • A ProcessMain class which creates and starts a process bound to the sample.bpmn file
  • A ProcessTest which can be used for unit testing the ProcessMain class
  • A sample.bpmn resource which is our first process written in BPMN 2.0
jbpm 5 tutorial jboss example
By clicking on the sample.bpmn file, the BPMN 2 process editor will be activated:
As you can see this process contains a start node, an end node and a Script task named "Hello".
jbpm 5 tutorial jboss example
A Script Task represents a script that should be executed in this process. The associated action specifies what should be executed, the dialect used for coding the action (i.e., Java or MVEL), and the actual action code. This code can access any variables and globals. When a Script Task is reached in the process, it will execute the action and then continue with the next node.

By clicking on the "Properties" tab, in the lower part of your IDE, you can see the Action which is associated to the process.
jbpm 5 tutorial jboss example
As it is, when you run the ProcessMain, a simple "Hello world" message will display on the console.
Let's make it a bit more interesting: Right click on the "Action" of your node, where the [..] button is displayed. This will let you redefine your action. Specify the following action in the Textual editor:
jbpm 5 tutorial jboss example
The predefined variable kcontext  references the ProcessContext object (which can, for example, be used to access the current ProcessInstance or NodeInstance, and to get and set variables, or get access to the ksession using kcontext.getKnowledgeRuntime()

Now modify your ProcessMain class, so that the process is started with an HashMap containing the process variables initial value:
01.public class ProcessMain {
02. 
03.public static final void main(String[] args) throws Exception {
04.// load up the knowledge base
05.KnowledgeBase kbase = readKnowledgeBase();
06.StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
07. 
08.Map params = new HashMap();
09. 
10.params.put("name", "Arthur");
11. 
12.// start a new process instance
13.ksession.startProcess("com.sample.bpmn.hello",params);
14.}
15. 
16.private static KnowledgeBase readKnowledgeBase() throws Exception {
17.KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
18.kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2);
19.return kbuilder.newKnowledgeBase();
20.}
21. 
22.}

Ok, we have just instructed jBPM to start a process and into the Script task, to display the "name" process variable. Verify it by running the ProcessMain class.

Monday, October 28, 2013

Hibernate Dialect

1. DB2

org.hibernate.dialect.DB2Dialect

2. DB2 AS/400

org.hibernate.dialect.DB2400Dialect

3. DB2 OS390

org.hibernate.dialect.DB2390Dialect

4. PostgreSQL

org.hibernate.dialect.PostgreSQLDialect

5. MySQL

org.hibernate.dialect.MySQLDialect

6. MySQL with InnoDB

org.hibernate.dialect.MySQLInnoDBDialect

7. MySQL with MyISAM

org.hibernate.dialect.MySQLMyISAMDialect

8. Oracle 8

org.hibernate.dialect.OracleDialect

9. Oracle 9i/10g

org.hibernate.dialect.Oracle9Dialect

10. Sybase

org.hibernate.dialect.SybaseDialect

11. Sybase Anywhere

org.hibernate.dialect.SybaseAnywhereDialect

12. Microsoft SQL Server

org.hibernate.dialect.SQLServerDialect

13. SAP DB

org.hibernate.dialect.SAPDBDialect

14. Informix

org.hibernate.dialect.InformixDialect

15. HypersonicSQL

org.hibernate.dialect.HSQLDialect

16. Ingres

org.hibernate.dialect.IngresDialect

17. Progress

org.hibernate.dialect.ProgressDialect

18. Mckoi SQL

org.hibernate.dialect.MckoiDialect

19. Interbase

org.hibernate.dialect.InterbaseDialect

20. Pointbase

org.hibernate.dialect.PointbaseDialect

21. FrontBase

org.hibernate.dialect.FrontbaseDialect

22. Firebird

org.hibernate.dialect.FirebirdDialect

Saturday, October 26, 2013

Basic Hacker Skills

When people think of hackers they immediately think of the worst but there are many different types of hackers and most of them has done a great deal to improve and develop software, the Internet and electronic devices.

Hacking skills - You must have the patience and will to understand programming languages. There are dozens of programming languages and they have evolved through the years, so start out with learning the basics. You can begin learning the programming language C then progress to other languages like Pascal or Fortran. Then move on to learning Perl, XHTML and other programs used on the Internet.

Understanding computer hardware is also a must as well as all the components that a computer system needs. You need to understand banking systems, and other systems used in the financial world because this is where you'll learn the kinds of security that are in place to protect the system and its clients.

Security Audit Stages

Stage 1. Automation Auditing
Stage 2. Manual Auditing

Automation Tools:-

1. AppScan
2. Scando
3. Acunetix
etc..

Manual Testing Tools:-

1. Burp Suite
2. IE Tamper
3. Achilles
etc..


How to prevent via coding ?   [Project should implement the following points]:-

Auto Completion for important controls like password
Salted hash for password fields
Sanitization to all the input controls
Browser Refresh [use captcha]
Steal Password via Refresh or back button [use redirection, clear cache]
Session Fixation [ use new session id before/after login ]
Brute Force [use captcha]
Guessing UserID
Always clear Browser cache
Insecure direct object reference  [ in search result screens, avoid give action link with pk id ]
CSRF
Downloading Secure File [ dont take a path from parameter ]
Inproper Error Handling [use proper tr{} catch{}, move to custom error page]
XSS [use sanitization, check server side validation (type,size,input data) ]
SQL Injection [use sanitization]
Cross Account Access
Privileged Escalation
Login Trail
Audit Trail
Forgot Password [use security question, captcha, send a mail link to change password (one time link) ]
etc..

Hit Counter


View My Stats