Create user in OID

Using the Oracle-supplied Java SDK’s
The sample code below uses the OID SDK’s to bind to the OID directory server and then create a new user under a specific location in the directory tree.

import oracle.ldap.util.*;
import oracle.ldap.util.jndi.*;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.io.*;
import java.util.*;
 
public class NewUser
{
final static String ldapServerName = "mlc2.acme.org";
final static String ldapServerPort = "3060";
final static String rootdn = "cn=orcladmin";
final static String rootpass = "welcome1";
 
public static void main(String argv[]) throws NamingException
{
// Create the connection to the ldap server
InitialDirContext ctx = ConnectionUtil.getDefaultDirCtx(ldapServerName,
ldapServerPort,
rootdn,
rootpass);
 
// Create the subscriber object using the default subscriber
Subscriber mysub = null;
String [] mystr = null;
try {
RootOracleContext roc = new RootOracleContext(ctx);
mysub = roc.getSubscriber(ctx, Util.IDTYPE_DN, "dc=acme,dc=org", mystr);
}
catch (UtilException e) {
e.printStackTrace();
}
 
// Create ModPropertySet with user information
ModPropertySet mps = new ModPropertySet();
mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"givenname", "John");
mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"mail", "[email protected]");
mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"userpassword", "welcome1");
 
// Create the user
User newUser = null;
try {
newUser = mysub.createUser(ctx, mps, true);
System.out.println("New User DN: " + newUser.getDN(ctx));
}
catch (UtilException e) {
e.printStackTrace();
}
}
}

To use the above sample code do the following:
1. Save the above text indicated between the begin/end cut lines into a file named NewUser.java. Note that the filename and case are important and must be exactly NewUser.java unless the code has been modified.

2. Locate the Java Development Kit (JDK) on your system. For recent Oracle installations it should have been installed under $ORACLE_HOME/jdk but could be located elsewhere.

3. Compile the NewUser.java file into a binary NewUser.class file using the following command:

/bin/javac –classpath $ORACLE_HOME/jlib/ldapjclnt9.jar NewUser.java

Since the sample code makes use of the Oracle LDAP classes it is necessary to include the classpath parameter in the javac command. The above command should complete with no errors or output and should result in a file named NewUser.class being created.

4. Execute the resulting NewUser.class file using the following command:

/bin/java –cp .:$ORACLE_HOME/jlib/ldapjclnt9.jar NewUser

Note that this time there is NO extension specified (neither .java nor .class is used) and it must be executed from the same directory where the NewUser.class file is located. Again the file is case-sensitive and must be exactly as listed above. Make note of the –cp parameter as it includes the current directory and the location of the ldapjclnt9.jar file. It is necessary to include the “.:” (this is a period followed by a colon) in the –cp parameter for the program to execute correctly.

If the NewUser.class file executes it will print “New User DN: cn=john.doe,cn=Users,dc=acme,dc=org” to the screen. The user will be created within OID in the cn=users container of the default subscriber/realm. This user can then been seen via an ldapsearch or through Oracle Directory Manager (ODM).

If any errors are encountered (such as invalid user/pass, duplicate entry, etc… then an error message will be displayed. In this simple example the error messages are of very little help other than for indicating what part of the code failed. For example, if the user already existed then the following error will be displayed:

oracle.ldap.util.UtilException: NamingException encountered in ldapAdd [LDAP: error code 68 – Object alre
ady exists]
at oracle.ldap.util.Util.ldapAdd(Util.java:2016)
at oracle.ldap.util.Subscriber.createUser(Subscriber.java:1392)
at oracle.ldap.util.Subscriber.createUser(Subscriber.java:1315)
at NewUser.main(NewUser.java:46)

Using the Native Java JNDI Packages

The OID Java API documentation shows how to search and modify entries within an OID ldap server but does not give any examples or instructions for how to create a new entry in the ldap server. This example is very similar to the above java code but uses ONLY native java packages.

The sample code below uses the Java JNDI packages to bind to the OID directory server and then create a new user under a specific location in the directory tree. This code uses NO Oracle-specific Java function calls. The sample code uses only Java packages that are supplied by Sun’s Java Development Kit.

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.*;
 
public class NewUser
{
final static String ldapServerName = "mlc2.acme.org";
final static String ldapServerPort = "4032";
final static String rootdn = "cn=orcladmin";
final static String rootpass = "welcome1";
final static String entryDn = "cn=javauser,cn=users,dc=acme,dc=org";
 
public static void main(String argv[]) throws NamingException
{
Properties env = new Properties();
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
env.put( Context.PROVIDER_URL, "ldap://" + ldapServerName + ":" + ldapServerPort + "/");
env.put( Context.SECURITY_PRINCIPAL, rootdn );
env.put( Context.SECURITY_CREDENTIALS, rootpass );
DirContext ctx = new InitialDirContext(env);
 
// Create the objclassSet to hold all the entry's objectClasses.
BasicAttribute objclassSet = new BasicAttribute("objectclass");
objclassSet.add("person");
objclassSet.add("organizationalPerson");
objclassSet.add("inetOrgPerson");
objclassSet.add("top");
objclassSet.add("orcluser");
objclassSet.add("orcluserv2");
 
// load the attributes
BasicAttributes attrs = new BasicAttributes();
attrs.put(objclassSet);
attrs.put("mail", "[email protected]");
attrs.put("cn", "javauser");
attrs.put("sn", "Campbell");
attrs.put("givenname", "Mike");
attrs.put("uid", "javauser");
attrs.put("userpassword", "welcome1");
 
//create the user in OID
ctx.createSubcontext(entryDn, attrs);
}
}

To use the above sample code do the following:
1. Save the above text indicated between the begin/end cut lines into a file named NewUser.java. Note that the filename and case are important and must be exactly NewUser.java unless the code has been modified.

2. Locate the Java Development Kit (JDK) on your system. For recent Oracle installations it should have been installed under $ORACLE_HOME/jdk but could be located elsewhere.

3. Compile the NewUser.java file into a binary NewUser.class file using the following command:

/bin/javac NewUser.java

Since the sample code does not contain any Oracle-specific packages in it there is no need to specify any classpath. The above command should complete with no errors or output and should result in a file named NewUser.class being created.

4. Execute the resulting NewUser.class file using the following command:

/bin/java NewUser

Note that this time there is NO extension specified (neither .java nor .class is used) and it must be executed from the same directory where the NewUser.class file is located. Again the file is case-sensitive and must be exactly as listed above.

If the NewUser.class file executes successfully there will be no output written to the screen. The user will be created within OID in the location specified by the entryDN variable. This user can then been seen via an ldapsearch or through Oracle Directory Manager (ODM).

If any errors are encountered (such as invalid user/pass, duplicate entry, etc… then a Java exception will occur and a stack trace will be displayed showing the error. For example, if the user already existed then the following error will be displayed:

persistent disk storage in ehcache

Requirement – To have persistent storage in ehcahce

Solution-
cacheManagerPeerProviderFactory –It is used for saying “Hello, I’m here!” and allows to discover the other CacheManager in the cluster and be discovered by other nodes.

It accepts only two arguments (class and properties).

cacheEventListenerFactory — It is used for receiving notification about cache update by other nodes in cache cluster.

bootstrapCacheLoaderFactory —It is used for starting cache system and synchronize the cached elements in the cluster.

package com.techartifact.caching;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

// this is main class.
public class MainClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MainClass mainClass = new MainClass();
		mainClass.runMainClass();
	}

	private void runMainClass() {
		// TODO Auto-generated method stub
		int TOTAL=3;
	         CacheManager cacheManager = new CacheManager();
		Cache myCache = cacheManager.getCache("persistentEhcacheNew");

		System.out.println("the size of my cache at startup is: "+myCache.getSize());
		System.out.println("disk store size: "+myCache.getDiskStoreSize());
		System.out.println("memory store size: "+myCache.getMemoryStoreSize());
	        System.out.println("memory DiskStoreSize size: "+myCache.getDiskStoreSize());
	        System.out.println("boot strapCacheLoader is Asynchronous: "+myCache.getBootstrapCacheLoader().isAsynchronous());
                System.out.println("cache status: "+myCache.getStatus());
	        System.out.println("cache name: "+myCache.getName());
                List listOfKeys= myCache.getKeys();
                //myCache.removeAll();
                if(myCache.getDiskStoreSize()>0){
               for (Object temp : listOfKeys) {
                        System.out.println((String)temp.toString());
	                Element element = myCache.get(temp);  
	                     
	                      if (element != null) {  
	                       System.out.println(temp + " is in the cache!!!"); 
	                       String val = (String)element.getValue().toString();
                               System.out.println(val + " value is in the cache!!!");
                              }
	            }
                }else{
              
		System.out.println("now add 3 elements to cache");
                    for (int i = 0; i < TOTAL; i++) {
                            DataObject dataObject = new DataObject();
                           dataObject.setRandomFloat(Randomizer.returnRandomFloat());
                            dataObject.setRandomString(Randomizer.returnRandomString());			
                            Element element = new Element(i,  dataObject.getRandomFloat());
                            myCache.put(element);
                   }
                }

		cacheManager.shutdown();
		
	}

}


BootstrapCacheLoaderFactory – An abstract factory for creating BootstrapCacheLoader instances. Implementers should provide their own concrete factory extending this factory. It can then be configured in ehcache.xml.

Create a MyBootstrapCacheLoaderFactory that extends BootStrapCacheLoaderFactory, and override method load(EhCache ehcacheparam)to bring the cache up on server startup

package com.techartifact.caching;

import java.util.List;
import java.util.Properties;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
import net.sf.ehcache.bootstrap.BootstrapCacheLoaderFactory;

// 
public class MyBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory implements BootstrapCacheLoader{
	

	@Override
	public BootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {
		// TODO Auto-generated method stub
		return new MyBootstrapCacheLoaderFactory();
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
	public boolean isAsynchronous() {
		// TODO Auto-generated method stub
		return false;
	}
	public void load(Ehcache myCache) throws CacheException {
		// TODO Auto-generated method stub
		System.out.println("load your cache with whatever you want....");
		List keys = myCache.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			Element element = myCache.get((keys.get(i).toString()));
		}
		System.out.println("load complete!");
	}



}

JSF Component state Save process

JSF can save state of component tree in either session or on clients machine inform of serialized data .
While creating component tree JSF creates a key and keep all objects of component tree as UIViewRoot in session with against it.For next JSF request it will use same key to restore that view 🙂
For client side saving has performance issues like it has to serialize whole tree and write it in response ship in form of gzip to client.Next time when same client make JSF request from same page it de-serialize it and inflate all objects in corresponding state .

Setting for state saving is done in web.xml.

Server side state saving is where the component tree and all component state are stored within the user’s session. This entry within the session is tracked by writing a key in the response that is used to lookup the entry on subsequent post-backs.

Client side state saving doesn’t leverage the server side session mechanism at all, instead, the component tree and state will be serialized using Java Serialization, GZIP compressed (at least that is the default), Base64 encoded, and written to the response. When a post-back occurs, the encoding process will be reversed which will result in the tree and state we started with.

Setting in web.xml

  <context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

Why does JSF need to save the state of UI components on the server side ?

Because HTTP is stateless and JSF is stateful. The JSF component tree is subject to dynamic (programmatic) changes. JSF simply needs to know the exact state as it was when the form had been displayed to the enduser, so that it can successfully process the whole JSF lifecycle based on the information provided by the original JSF component tree when the form has been submitted back to the server. The component tree provides information about the request parameter names, the necessary converters/validators, the bound managed bean properties and action methods.

As a logged-in user on the application navigates though pages, will the state of components keep on accumulating on the server?

Technically, that depends on the implementation. If you’re talking about page-to-page navigation (just GET requests) then Mojarra won’t save anything in session. If they are however POST requests (forms with commandlinks/buttons), then Mojarra will save state of each form in session until the max limit. This enables the enduser to open multiple forms in different browser tabs in the same session.

Or, when the state saving is set to client, then JSF won’t store anything in session. You can do that by the following context param in web.xml:

<context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
</context-param>

It will then be serialized to an encrypted string in a hidden input field with the name javax.faces.ViewState of the form.

Happy learning with Vinay in techartifact