Tuesday, August 26, 2014

Tivoli LDAP V6.1 Retrieve LDAP attribute pwdChangedTime & modifytimestamp

There is requirement to show alert message to user before expire password. We have set up password policy in LDAP. User password will expire after 45 days. Before password expire alert message show on screen to change password.

I am retrieving pwdChangedTime timestamp from LDAP.  pwdChangedTime attribute value give us date and time of when password has been changed. After it will easy to find out next password expire date and according shown message to user. Make sure you have to use root and password to retrieve data


import com.sun.jndi.ldap.LdapCtxFactory;
import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;


public class LdapTest1 {

    public static void main(String[] args)  {
        try{
         DirContext ctx=null;
        // Create your search string
         String userId = "mytestuser";
        // String INITIAL_ENTRY = "uid" + "=" + userId + ",cn=" + "users" + "," + "dc=ibm,dc=com";
        
         String INITIAL_ENTRY = "uid=testuser,cn=users,DC=companyname,DC=COM";

        String pwdChangedTime = "";
        //InitialLdapContext ctx = null;
  
       
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "Ldap://127.0.0.0:1389");
           
         env.put(Context.SECURITY_PRINCIPAL, "cn=root");
         env.put(Context.SECURITY_CREDENTIALS, "password");
       
       
        env.put("java.naming.ldap.version", "3");
        ctx =new InitialDirContext(env); //new InitialLdapContext(env, null);
        Attribute attr = null;
    
            // Set up Search Controls
            SearchControls sc = new SearchControls();
            sc.setSearchScope(SearchControls.OBJECT_SCOPE);
                        String[] userAttrList = {"pwdChangedTime", "modifytimestamp"};
          //  String[] userAttrList = {"modifytimestamp"};
            sc.setReturningAttributes(userAttrList);
        
           NamingEnumeration ne = ctx.search(INITIAL_ENTRY,"(objectclass=*)", sc);

                     while(ne.hasMore()){
                        SearchResult searchresult = (SearchResult) ne.next();
                        Attributes attrs = searchresult.getAttributes();
                       /* Attribute value= attrs.get("pwdChangedTime");
                        System.out.println(value.get());
                        StringBuffer sbdate =new StringBuffer((String)value.get());
                        System.out.println("Year:"+sbdate.substring(0, 4));
                        System.out.println("Month:"+sbdate.substring(4, 6));
                        System.out.println("Day:"+sbdate.substring(6, 8));*/
                     
                       
                       
                       NamingEnumeration ae = attrs.getAll();
                        while (ae.hasMore()) {
                       
                            System.out.println(ae.nextElement());
                           
                        }
                    }
                    
                     ctx.close();
        }catch(Exception e){
            e.printStackTrace();
        }
                }// end method

    }// end class

Thursday, May 29, 2014

JAVA LDAP API EXAMPLE, Create User, Delete User, List All User and Group, LDAP Modify attribute

There are many functionality require in project related to LDAP.

1) Creating Users
2) Modifying attribute
3) Attaching Group to user
4) Deleting User and Group


Creating Users

-----------------------------------------------------------Code Start-----------------------------------

package com.ldap;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.naming.Context;
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.InitialDirContext;

import com.db.IPOPSProdDB;
import com.db.VO;

public class CreateSingleUser {

   
public  void initialize(){
       
       
        DirContext ctx=null;
        Connection conn = null;
         try{       
       
            Hashtable env = new Hashtable();           
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");          
            env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=test1,cn=users,DC=company,DC=COM");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
           
              VO vo = null;
              vo = new VO();
              vo.setCsr_id("wpsbind");
              vo.setCn("wpsbind");   
           
            adduser(ctx,vo);
       
       
           
           
           
         }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                ctx.close();
                //conn.close();
                System.out.println("context closed");
                System.out.println("connection closed");
                }catch(Exception Ignore)
                {       
                    Ignore.printStackTrace();
                }
        }
     }


private void adduser(DirContext ctx,VO vo){
   
    try{
       
         String pass="wpsbind";
       
        Attributes attributes = new BasicAttributes();
        Attribute objClasses = new BasicAttribute("objectClass");
       /* objClasses.add("top");
        objClasses.add("person");
        objClasses.add("organizationalPerson");
        objClasses.add("inetOrgPerson")*/;
       
       
        objClasses.add("inetOrgPerson");
         objClasses.add("organizationalPerson");
         objClasses.add("person");
         objClasses.add("top");
        attributes.put(objClasses);

        // Define User attributes

        attributes.put("uid", vo.getCsr_id());
        attributes.put("sn", vo.getCn());
        attributes.put("cn", vo.getCn());
        //attributes.put("givenName", "testgivenName");
        //attributes.put("displayName", "testdisplayName");           
        attributes.put("userPassword", pass);   
       
       
       
       
        if(vo.getEmail()!=null && vo.getEmail().length() > 0){
            attributes.put("mail", vo.getEmail());
        }
        if(vo.getPhone()!=null && vo.getPhone().length() >0){
            attributes.put("mobile", vo.getPhone());
        }
       
       
         ctx.createSubcontext("uid="+ vo.getCsr_id()+",cn=users,DC=company,DC=COM",attributes);
       
       
       
       
       
       
       
    }catch(Exception e){
        e.printStackTrace();
        System.out.println("exception_for_user_LDAP >> "+vo.getCsr_id());
        //e.printStackTrace();
       
    }finally{
        try{
           
            System.out.println("pstmt closed");
           
            }catch(Exception Ignore)
            {       
                Ignore.printStackTrace();
            }
    }
}



    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        CreateSingleUser createUser = new CreateSingleUser();
        createUser.initialize();

    }

}



-----------------------------------------------------------Code end-----------------------------------

Assign Group to User
Here I am reading User and Group detail from text file



--------------------Code start-----------------------------------------------------

package com.ldap;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

public class GropReadApply {

    /**
     * @param args
     */
   
    DirContext ctx=null;
   
    public void closeContext(){
        try{
            ctx.close();
            System.out.println("context closed");
            }catch(Exception Ignore)
            {      
                Ignore.printStackTrace();
            }
    }
   
    public void assingGrouptoUser(String username, String groupName)    {

      
    try {     
      
        ModificationItem[] mods = new ModificationItem[1];
        Attribute mod =new BasicAttribute("uniqueMember",  "uid="+username+",cn=users,DC=company,DC=COM");
        mods[0] =  new ModificationItem(DirContext.ADD_ATTRIBUTE, mod);
        ctx.modifyAttributes("cn="+groupName+",cn=groups,DC=company,DC=COM", mods);
    } catch (Exception e) {
        // If user is already added, ignore exception
        System.out.println("no_assignment "+username+":"+groupName);
        e.printStackTrace();
    }/*finally{
        try{
            ctx.close();
            System.out.println("context closed");
            }catch(Exception Ignore)
            {      
                Ignore.printStackTrace();
            }
    }*/
}
   
public  DirContext initialize(){
        
      
        //DirContext ctx=null;
         try{      
      
            Hashtable env = new Hashtable();          
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");
                     env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=test,cn=users,DC=company,DC=COM");          
            //env.put(Context.SECURITY_CREDENTIALS,"wpsbind");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
         }catch (Exception e) {
                e.printStackTrace();
         }
          
            return ctx;
    }
   
    public static void main(String[] args) {
        
      
        GropReadApply gropReadApply = new GropReadApply();
        gropReadApply.initialize();
        BufferedReader br = null;

        try {

            String sCurrentLine = null;

            br = new BufferedReader(new FileReader("C:\\UserGroupList.txt"));
            int couunt=0;
            int nogropu=0;
            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                int start = sCurrentLine.indexOf("uid=");
                int send = sCurrentLine.indexOf(",");
                String csr_id=sCurrentLine.substring(start+4, send);
                //System.out.println(csr_id);
                int gstart = sCurrentLine.indexOf("Group : ");
                String group = sCurrentLine.substring(gstart+7).trim();
                //System.out.println(group);
                //System.out.println("NO GROUP ASSIGNED".equalsIgnoreCase(group));
              
                if(! ("NO GROUP ASSIGNED".equalsIgnoreCase(group))){
                    gropReadApply.assingGrouptoUser(csr_id, group);
                    //System.out.println(sCurrentLine);
                    couunt++;
                }else{
                    nogropu++;
                }
              
              
              
            }
            System.out.println("Has Group value"+couunt);
            System.out.println("Has no Group value"+nogropu);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        gropReadApply.closeContext();
    }
   
   

}
---------------------------------Code end------------------------------------------------



Delete Users from LDAP

------------------------------------------------------------------------
private void deleteUser(DirContext ctx,VO vo){
    try {
        ctx.destroySubcontext("uid="+ vo.getCsr_id()+",cn=users,DC=company,DC=COM");
        System.out.println("user deleted >> "+vo.getCsr_id());
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        System.out.println("exception for deleteUser >> "+vo.getCsr_id());
        e.printStackTrace();
      
    }
}

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

Shows Group and User Ids from LDAP


----------------------------------------Code start-------------------------------------------

package com.ldap;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import javax.naming.NamingEnumeration;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

import com.db.IPOPSProdDB;
import com.db.VO;

public class LdapListAlluser {
   
   
    DirContext ctx=null;
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LdapListAlluser listAlluser = new LdapListAlluser();
        listAlluser.initialize();
        //ldapUtil.adduser(null, null);
    }
   
   
   
    private void listGroup(){
       
        String base = "cn=groups,DC=company,DC=COM"; // base for LDAP
        String[] att = { "cn", "*" };
       
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        sc.setReturningAttributes(att);
       
        try {
            //inetOrgPerson
            //inetorgperson
            NamingEnumeration results = ctx.search(base,"(objectclass=groupofuniquenames)", sc);
            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // get the attributes and attribute list
                Attributes atts = sr.getAttributes();
                NamingEnumeration attrList = atts.getAll();
                // while we have attributes
                while (attrList.hasMore()) {
                Attribute attr = (Attribute) attrList.next();
                NamingEnumeration values = attr.getAll();
                String id, value = "";
                while (values.hasMore()) {
                id = attr.getID();
                value = values.next().toString();
                System.out.println(id + " " + value);
                if("cn".equalsIgnoreCase(id)){
                    System.out.println(id + " " + value);
                }
                if("uniquemember".equalsIgnoreCase(id)){
                    System.out.println(id + " " + value);
                }
                }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }
   
    private void listUsers(){
   
        String base = "cn=users,DC=company,DC=COM"; // base for LDAP
        String[] att = { "uid", "*" };
       
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        sc.setReturningAttributes(att);
       
        try {
            //inetOrgPerson
            //inetorgperson
            NamingEnumeration results = ctx.search(base,"(objectclass=inetOrgPerson)", sc);
            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // get the attributes and attribute list
                Attributes atts = sr.getAttributes();
                NamingEnumeration attrList = atts.getAll();
                // while we have attributes
                while (attrList.hasMore()) {
                Attribute attr = (Attribute) attrList.next();
                NamingEnumeration values = attr.getAll();
                String id, value = "";
                while (values.hasMore()) {
                id = attr.getID();
                value = values.next().toString();
                //System.out.println(id + " " + value);
                if("uid".equalsIgnoreCase(id)){
                   
                    if( ("wpsbind".equalsIgnoreCase(value))){
                        System.out.println(id + " " + value);
                    }else if( ("wpsadmin".equalsIgnoreCase(value))){
                        System.out.println(id + " " + value);
                    }else {                       
                        System.out.println(id + " " + value);
                    }
                }
                }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }
   
   
     private String getUserUID(String userDN) {
            int start = userDN.indexOf("=");
            int end = userDN.indexOf(",");

            if (end == -1) {
                end = userDN.length();
            }

            return userDN.substring(start+1, end);
        }
   
     public List getMembers(String groupName) throws NamingException {
            List members = new LinkedList();

            // Set up attributes to search for
            String[] searchAttributes = new String[1];
            searchAttributes[0] = "uniqueMember";

          //  ctx.
           
            Attributes attributes =     ctx.getAttributes("cn="+groupName+",cn=groups,DC=company,DC=COM", searchAttributes);
           
           
            //Attributes attributes =      ctx.getAttributes("*");
            if (attributes != null) {
                Attribute memberAtts = attributes.get("uniqueMember");
                if (memberAtts != null) {
                    for (NamingEnumeration vals = memberAtts.getAll();
                         vals.hasMoreElements();
                         members.add(getUserUID((String)vals.nextElement()))) ;
                }
            }

            return members;
        }
   
public  void initialize(){
       
       
       
         try{       
       
            Hashtable env = new Hashtable();           
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");
                  env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=wpsbind,cn=users,DC=company,DC=COM");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            //env.put(Context.SECURITY_CREDENTIALS,"wpsbind");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
           
            listUsers();
           
            //listGroup();
       
               
                   
           
         }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                ctx.close();
                System.out.println("context closed");
                }catch(Exception Ignore)
                {       
                    Ignore.printStackTrace();
                }
        }
     }

}
-----------------------------------------Code End------------------------------------



Modify attribute

public void modifyAttribute(DirContext ctx){
         try{   
                ModificationItem[] mods = new ModificationItem[1];
                Attribute mod0 = new BasicAttribute("displayName", "test");
                mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
                ctx.modifyAttributes("uid=test1,cn=users,DC=company,DC=COM", mods);
                System.out.println("done");
         }catch (Exception e) {
                e.printStackTrace();
            }
    }

Wednesday, September 11, 2013

Put Shared Lib to WebSphere portal application ( WAR)


1. Create shared lib Under Environment > Shared Libraries
2) Navigate Servers > Application servers
3)Click WebSphere_Potal
4)Navigate Java and Process Management under Server Infrastructure
5)Click Class loader
6)click Classloader_1226779803102
7)click Shared library references
8)Add newly created Shared library. And Restart Portal server

Images

Thursday, October 4, 2012

EJB Invokation exception : org.omg.CORBA.NO_PERMISSION Exception

While invoking EJB from target system from Source System.

Whenever we are hitting ejb service from portal which is deployed on different WAS , and if we face the below stack trace:---


Exception = org.omg.CORBA.NO_PERMISSION Source = com.ibm.ws.naming.jndicos.CNContextImpl.doLookup probeid = 1489 Stack Dump = org.omg.CORBA.NO_PERMISSION: >> SERVER (id=64e777ef, host=SVHJ0898.ideaconnect.com) TRACE START: >> org.omg.CORBA.NO_PERMISSION: Subject is null. Authentication Failed. vmcid: 0x49424000 minor code: 300 completed: No >> at com.ibm.ISecurityLocalObjectBaseL13Impl.PrincipalAuthFailReason.map_auth_fail_to_minor_code(PrincipalAuthFailReason.java:88) >> at com.ibm.ISecurityLocalObjectBaseL13Impl.CSIServerRIBase.authenticateSecurityTokens(CSIServerRIBase.java:2815) >> at com.ibm.ISecurityLocalObjectBaseL13Impl.CSIServerRI.receive_request(CSIServerRI.java:622) >> at com.ibm.rmi.pi.InterceptorManager.invokeInterceptor(InterceptorManager.java:631) >> at com.ibm.rmi.pi.InterceptorManager.iterateServerInterceptors(InterceptorManager.java:535) >> at com.ibm.rmi.pi.InterceptorManager.iterateReceiveRequest(InterceptorManager.java:777) >> at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:616) >> at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:480) >> at com.ibm.rmi.iiop.ORB.process(ORB.java:512) >> at com.ibm.CORBA.iiop.ORB.process(ORB.java:1571) >> at com.ibm.rmi.iiop.Connection.respondTo(Connection.java:2680) >> at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2543) >> at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:62) >> at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118) >> at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1560) >> SERVER (id=64e777ef, host=SVHJ0898.ideaconnect.com) TRACE END. vmcid: 0x49424000 minor code: 300 completed: No at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:67)


1.Go To Security of the WAS.
2.Then go to global security on clicking Secure administration, applications, and infrastructure.
3. Go To Authentication mechanisms and expiration 
4. Put given value : password ( WAS login password) and path


 

 5. Copy keys.key to source system
6.  Import that key in Portal WAS 6
7.  Restart Server.

Thursday, June 7, 2012

Login , Logout and Session Time Out Filter in WebSphere Portal

Here useful filter used when user log in, log out and session time in WebSphere portal Example package com.filter; import com.ibm.websphere.security.WSSecurityException; import com.ibm.portal.auth.ExplicitLoginFilter; import com.ibm.portal.auth.ExplicitLoginFilterChain; import com.ibm.portal.auth.FilterChainContext; import com.ibm.portal.auth.exceptions.*; import com.ibm.portal.security.SecurityFilterConfig; import com.ibm.portal.security.exceptions.SecurityFilterInitException; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SampleLoginFilter implements ExplicitLoginFilter { public void login(HttpServletRequest req, HttpServletResponse arg1, String arg2, char[] arg3, FilterChainContext arg4, Subject arg5, String arg6, ExplicitLoginFilterChain chain) throws LoginException, WSSecurityException, PasswordInvalidException, UserIDInvalidException, AuthenticationFailedException, AuthenticationException, SystemLoginException, com.ibm.portal.auth.exceptions.LoginException { // TODO Auto-generated method stub System.out.println("SampleLoginFilter login successfull from filter 1"); chain.login(req, arg1, arg2, arg3, arg4, arg5, arg6); System.out.println("SampleLoginFilter login successfull from filter 2"); System.out.println("SampleLoginFilter login"+req.getRemoteHost()); System.out.println("SampleLoginFilter login"+req.getLocalAddr()); } public void destroy() { // TODO Auto-generated method stub } public void init(SecurityFilterConfig arg0) throws SecurityFilterInitException { // TODO Auto-generated method stub System.out.println("SampleLoginFilter init"); } } ------------------------------------------------------------------------ package com.filter; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.portal.auth.ExplicitLogoutFilter; import com.ibm.portal.auth.FilterChainContext; import com.ibm.portal.auth.LogoutFilterChain; import com.ibm.portal.auth.exceptions.LogoutException; import com.ibm.portal.security.SecurityFilterConfig; import com.ibm.portal.security.exceptions.SecurityFilterInitException; public class SampleLogoutFilter implements ExplicitLogoutFilter { public void logout(HttpServletRequest arg0, HttpServletResponse arg1, FilterChainContext arg2, LogoutFilterChain chain) throws LogoutException, LoginException { // TODO Auto-generated method stub System.out.println("SampleLogoutFilter logout successfull from filter 1"); chain.logout(arg0, arg1, arg2); System.out.println("SampleLogoutFilter logout successfull from filter 2"); } public void destroy() { // TODO Auto-generated method stub } public void init(SecurityFilterConfig arg0) throws SecurityFilterInitException { // TODO Auto-generated method stub } } ---------------------------------------------------------------------------------------------- package com.filter; import java.util.Map; import javax.servlet.http.HttpSession; import com.ibm.portal.auth.SessionTimeoutFilter; import com.ibm.portal.auth.SessionTimeoutFilterChain; import com.ibm.portal.auth.exceptions.UserSessionTimeoutException; import com.ibm.portal.security.SecurityFilterConfig; import com.ibm.portal.security.exceptions.SecurityFilterInitException; public class SampleSessionTimeoutFilter implements SessionTimeoutFilter { public void onUserSessionTimeout(HttpSession arg0, Map arg1, SessionTimeoutFilterChain chain) throws UserSessionTimeoutException { // TODO Auto-generated method stub System.out.println("SampleSessionTimeoutFilter timeout successfull from filter 1"); chain.onUserSessionTimeout(arg0, arg1); System.out.println("SampleSessionTimeoutFilter timeout successfull from filter 1"); } public void destroy() { // TODO Auto-generated method stub } public void init(SecurityFilterConfig arg0) throws SecurityFilterInitException { // TODO Auto-generated method stub } } ----------------------------------------------------------- Add above filter in WP AuthenticationService under Resources > Resource Environment > Resource Environment Providers > Custom properties Value as below name : login.explicit.filterchain Value : com.filter.SampleLoginFilter name :logout.explicit.filterchain Value :com.filter.SampleLogoutFilter name :sessiontimeout.filterchain Value : com.filter.SampleSessionTimeoutFilter

Monday, May 7, 2012

Key OR Certificate miagration on WebSphere application server

Introduction Generally Service application and Web application deployed in different WAS machine. And required to communicate web to service application either by EJB ( Remote or Web service ). Communication over EJB required certification or key ma management at both source and target application. Example . 1) Service application machine ( 127.0.0.1 ) 2) Web application machine ( 127.0.0.2 ) Now Import key from service machine to Web machine Goto
Click on Retrieve from port
Click Retrieve signer information. Do the same process for NodeDefaultTrustStore NodeLTPAKeys
Click apply, makes sure synchronize all nodes Restart server.

Tuesday, April 17, 2012

WAS 6.1 Scheduler Configuration using Stateless Session Beans

Introduction
The Scheduler service in WebSphere® Business Integration Server Foundation Version 5.1 (formerly WebSphere Application Server Enterprise) is a full-featured timer service that enables high performance, high availability, persistence and transactional scheduling of J2EE operations.
The Scheduler is comprised of two components:
• Scheduler resource
• Scheduler API.
The Scheduler resource represents a Scheduler instance that is available in the WebSphere Application Server Java™ Naming and Directory Interface (JNDI). Each Scheduler resource has unique properties that govern its behavior; for example, in which database to store the persistent schedules. The Scheduler resource is configured using the standard WebSphere Application Server administrative console (admin console) or the AdminControl scripting object.
The Scheduler API is a Java interface that enables creating and administering tasks. The API is accessible from any J2EE server application (Enterprise Java Beans and servlets).
The Scheduler enables the execution of two types of tasks:
• Calling stateless session Enterprise Java Beans (EJBs). (This approach is shown here).
• Sending Java Message Service (JMS) Messages.
The Scheduler stores its data in any database that WebSphere Application Server supports and uses the WebSphere Application Server Transaction Manager. All Scheduler operations are therefore transactional and persistent; each task is guaranteed to run successfully one time. If a task fails for any reason, the entire operation is rolled back.
The Scheduler enables application developers to create their own stateless session EJBs to receive event notifications during a task's life cycle, allowing the plugging-in of custom logging utilities or workflow applications. Stateless session EJBs are also used to provide generic calendaring. Developers can either use the supplied calendar bean or create their own for their existing business calendars.

Configuring schedulers using the administrative console
Schedulers can be created or configured using the administrative console.
Procedure
1. Start the administrative console.
2. Select Resources > Schedulers.
3. Click New.
4. Specify configuration settings.
5. Click OK or Apply to save the changes.
6. Save the changes to the configuration repository.
Here is an example .
1. Scheduler Name : MySchedular
2. JNDI Name : sched/MyScheduler
3. Data Source JNDI Name : DataSource should be created using jdbc->Data Source and list box will list that data source.
4. Data Source Alias: Alias should be create using Secure administration, applications, and infrastructure > JAAS - J2C authentication data >
Step Wise Images of from Admin console to create Scheduler,J2C Authentication Alias and Data Source.
StepWise Example with Images




JAAS - J2C authentication data

Data Source Creation Part One

DataSource Creation Part two





Creating Tables For Scheduler
1. Verify that the database to be used for this scheduler is available and accessible by the application server. Review the Creating scheduler databases and tables topic for instructions on creating a database. The remaining steps describe how to create scheduler tables in an existing database. We will be using DB2 Database here.
2. Start the administrative console.
3. Create a JDBC data source that refers to the scheduler database.
4. Test the data source connection.
5. Create a scheduler. This configuration object contains the desired table prefix and the JNDI name of the JDBC data source. Verify that you save the new Scheduler to the configuration repository before you proceed to the next step.
6. Click Resources > Schedulers to view all defined schedulers.
7. Select one or more schedulers.
8. Click Create Tables to create the tables for the selected schedulers in their associated database. The tables and indices you created reflect the table prefixes and data sources specified in each scheduler configuration.
9. Restart the server or start the poll daemon to run scheduler tasks.



Accessing schedulers
Each configured scheduler is available using the Scheduler API from a J2EE server application, such as a servlet or EJB module. Use a JNDI name or resource reference to access schedulers. Each scheduler is also available using the JMX API, using its associated WASScheduler MBean. However we will use the first one here.
StartUpBeans
We have used A startUpBeans here to fire the Scheduler. An application startup bean is a session bean that is loaded when an application starts. Application startup beans enable Java 2 Platform Enterprise Edition (J2EE) applications to run business logic automatically, whenever an application starts or stops normally.
A. Startup beans are especially useful when used with asynchronous bean features. For example, a startup bean might create an alarm object that uses the Java Message Service (JMS) to periodically publish heartbeat messages on a well-known topic. This enables clients or other server applications to determine whether the application is available.
B. For Application startup beans, use the home interface, com.ibm.websphere.startupservice.AppStartUpHome, to designate a bean as an Application startup bean and use the remote interface, com.ibm.websphere.startupservice.AppStartUp, to define start() and stop() methods on the bean.



C. The startup bean start() method is called when the module or application starts and contains business logic to be run at module or application start time.
D. The start() method returns a boolean value. True indicates that the business logic within the start() method ran successfully. Conversely, False indicates that the business logic within the start() method failed to run completely. A return value of False also indicates to the Application server that application startup is aborted.
E. The startup bean stop() methods are called when the module or application stops and contains business logic to be run at module or application stop time. Any exception thrown by a stop() method is logged only. No other action is taken.
F. The start() and stop() methods must never use the TX_MANDATORY transaction attribute. A global transaction does not exist on the thread when the start() or stop() methods are invoked. Any other TX_* attribute can be used. If TX_MANDATORY is used, an exception is logged, and the application start is aborted.
G. The start() and stop() methods on the remote interface use Run-As mode. Run-As mode specifies the credential information to be used by the security service to determine the permissions that a principal has on various resources. If security is on, the Run-As mode needs to be defined on all of the methods called. The identity of the bean without this setting is undefined.
H. There are no restrictions on what code the start() and stop() methods can run, since the full Application Server programming model is available to these methods.
An Example of Start method in StartUp Bean.






Developing a TaskHandler Session Bean
This topic describes how to create a task to call a method on a TaskHandler session bean. We will use EJB Session Beans to fire the Job.
Procedure
1. Create a new enterprise application with an EJB module. This application hosts the TaskHandler EJB module.
2. Create a stateless session bean in the EJB Module that implements the process() method in the com.ibm.websphere.scheduler.TaskHandler remote interface. Place the business logic you want created in the process() method. The process() method is called when the task runs. The process method should contain the actual business method that should be fired by the Scheduler. The Home and Remote interfaces must be set as follows in the deployment descriptor bean:
o com.ibm.websphere.scheduler.TaskHandlerHome
o com.ibm.websphere.scheduler.TaskHandler




3. Create an instance of the BeanTaskInfo interface by using the following example factory method. Using a JavaServer Pages (JSP) file, servlet or EJB component, create the instance as shown in the following code example (Example is above used and Stateless EJB to call TaskHandler). This code should coexist in the same application as the previously created TaskHandler EJB module:
4. // Assume that a scheduler has already been looked-up in JNDI.
5. BeanTaskInfo taskInfo = (BeanTaskInfo) scheduler.createTaskInfo(BeanTaskInfo.class).


Startup beans service settings
Use this page to enable startup beans that control whether application-defined startup beans function on this server. Startup beans are session beans that run business logic through the invocation of start and stop methods when applications start and stop. If the startup beans service is disabled, then the automatic invocation of the start and stop methods does not occur for deployed startup beans when the parent application starts or stops. This service is disabled by default. Enable this service only when you want to use startup beans. Startup beans are especially useful when used with asynchronous beans.
To view this administrative console page, click Servers > Application servers >server_name > Container services > Startup beans service.


Summary
In this way we can schedule a task or any business logic inside Websphere Application Server. The moment Server is up and Application starts up Start Up Beans will start firing the Scheduler using TaskHandler process method.
For API/Resources about
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/scheduler/TaskHandler.html

Followers