Tuesday, 23 November 2010

Create a Simple Google Chrome Extension Within JDeveloper 11g

After having a quick look at the chrome extension tutorial I realized  all I really need to create extensions was to use basic web techologies like HTML, CSS, JavaScript etc. Finally a chance to use the JavaScript editor with JDeveloper 11g , so here are the steps to build a demo from a JDeveloper project and eventually load the  extension within Google Chrome itself.

Note: JDeveloper 11g provides a JavaScript debugger making it a good choice to develop JavaScript from and also provides JavaScript insight which makes it productive at the same time.

1. New empty project called "HelloApples"
2. Right click on the project and select "New -> Web Tier -> HTML - JSON File"
3. Name the file "manifest.json"
4. Add contents as follows

{
  "name": "Apples First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  }
}

5. Right click on the project and select "New -> Web Tier -> HTML -> HTML Page"
6. Name the page "popup.html" and replace the file contents as follows.

<style> 
body {
  min-width:357px;
  overflow-x:hidden;
}
</style>

<SCRIPT LANGUAGE="JavaScript">
var now = new Date();

var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();

function fourdigits(number) {
 return (number < 1000) ? number + 1900 : number;
        }
today =  days[now.getDay()] + ", " +
         months[now.getMonth()] + " " +
         date + ", " +
         (fourdigits(now.getYear())) ;

document.write("Hello apples todays date is " + today);
</script>
7. Add the icon.png to the project , the one we use here is from the google demo below.

  http://code.google.com/chrome/extensions/getstarted.html

8. Your project would look as follows within JDeveloper. You will see a WEB-INF folder which
is there due to the fact the project has previously been run in the integrated WLS to test the popup.html



9. In Google Chrome bring up the extensions management page by clicking the wrench icon on the right hand side and choosing "Tools > Extensions". (On Mac, use Window > Extensions.)
10. If Developer mode has a + by it, click the + to add developer information to the page.
11. Click the Load unpacked extension button. A file dialog appears.
12. In the file dialog, navigate to your extension's folder within your JDeveloper project
and click OK.

eg:

C:\jdev\jdevprod\11113\jdeveloper\jdev\mywork\ChromeExtensionDemo\HelloApples\public_html

If all went well you should see your extension in the Google Chrome toolbar and when clicked it should show you todays date.

Wednesday, 17 November 2010

How to configure your own cache factory to access multiple caches?

I needed to be able to load multiple cache configurations files within the same JVM for different applications. I found that to do this I simply create my own Cache Factory and supply my own cache config file. Of course you are in the same cluster as that member but this allows you to load different configuration files as shown below.

1. Create two cache config files as follows.

Cache Config 1 - cache-config1.xml

<?xml version="1.0"?>
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">

<cache-config>

  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>config1</cache-name>
      <scheme-name>distributed</scheme-name>
    </cache-mapping>
  </caching-scheme-mapping>

  <caching-schemes>
    <distributed-scheme>
      <scheme-name>distributed</scheme-name>
      <service-name>DistributedCacheConfig1</service-name>
      <backing-map-scheme>
        <local-scheme>
          <high-units>10m</high-units>
        </local-scheme>
      </backing-map-scheme>
      <autostart>true</autostart>
    </distributed-scheme>
  </caching-schemes>

</cache-config> 

Cache Config 2 - cache-config2.xml
<?xml version="1.0"?>
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">

<cache-config>

  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>config2</cache-name>
      <scheme-name>distributed</scheme-name>
    </cache-mapping>
  </caching-scheme-mapping>

  <caching-schemes>
    <distributed-scheme>
      <scheme-name>distributed</scheme-name>
      <service-name>DistributedCacheConfig2</service-name>
      <backing-map-scheme>
        <local-scheme>
          <high-units>10m</high-units>
        </local-scheme>
      </backing-map-scheme>
      <autostart>true</autostart>
    </distributed-scheme>
  </caching-schemes>

</cache-config>

2. Create a test class as follows.
package pas.au.coheremce.demo;

import com.tangosol.net.ConfigurableCacheFactory;
import com.tangosol.net.DefaultConfigurableCacheFactory;
import com.tangosol.net.NamedCache;
import com.tangosol.net.DefaultConfigurableCacheFactory.CacheInfo;

public class CacheFactoryDemo
{
  private ClassLoader loader = null;
  
  public CacheFactoryDemo()
  {
    loader  = getClass().getClassLoader();
  }

  public void run ()
  {
    // access cache config cache-config1.xml
    accessCacheConfig("cache-config1.xml", "config1");
    
    // access cache config cache-config2.xml
    accessCacheConfig("cache-config2.xml", "config2");
  }
  
  private void accessCacheConfig(String configName, String cacheName)
  {
    ConfigurableCacheFactory factory = 
      new DefaultConfigurableCacheFactory(configName);
    
    NamedCache namedCache = factory.ensureCache(cacheName, loader);  
    
    // display scheme mapping to verify we are using the correct cache config file
    DefaultConfigurableCacheFactory dccf = (DefaultConfigurableCacheFactory) factory;
    CacheInfo info = dccf.findSchemeMapping(cacheName);
    System.out.println(String.valueOf(dccf.resolveScheme(info)));
  }
  
  public static void main(String[] args)
  {
    CacheFactoryDemo test = new CacheFactoryDemo();
    test.run();
    System.out.println("all done..");
  }
}

3. When run the output below shows how this works.In the code we display the scheme mapping to verify we have set this up correctly.

Access cache-config1.xml and the output is as follows
Oracle Coherence Version 3.6.0.0 Build 17229
 Grid Edition: Development mode
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

2010-11-17 12:57:53.461/0.473 Oracle Coherence GE 3.6.0.0 <Info> (thread=main, member=n/a): Loaded cache configuration from "file:/C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/CoherenceLoadCustomCacheConfig/Demo/classes/cache-config1.xml"
2010-11-17 12:57:53.821/0.833 Oracle Coherence GE 3.6.0.0 <D4> (thread=main, member=n/a): TCMP bound to /10.187.114.243:8088 using SystemSocketProvider
2010-11-17 12:57:57.215/4.227 Oracle Coherence GE 3.6.0.0 <Info> (thread=Cluster, member=n/a): Created a new cluster "cluster:0xC4DB" with Member(Id=1, Timestamp=2010-11-17 12:57:53.846, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:6608, Role=PasAuCoheremceCacheFactoryDemo, Edition=Grid Edition, Mode=Development, CpuCount=4, SocketCount=4) UID=0x0ABB72F30000012C578D6836C3F31F98
2010-11-17 12:57:57.224/4.236 Oracle Coherence GE 3.6.0.0 <Info> (thread=main, member=n/a): Started cluster Name=cluster:0xC4DB

...

2010-11-17 12:57:57.440/4.452 Oracle Coherence GE 3.6.0.0 <D5> (thread=DistributedCache:DistributedCacheConfig1, member=1): Service DistributedCacheConfig1 joined the cluster with senior service member 1
<distributed-scheme>
  <scheme-name>distributed</scheme-name>
  <service-name>DistributedCacheConfig1</service-name>
  <backing-map-scheme>
    <local-scheme>
      <high-units>10m</high-units>
    </local-scheme>
  </backing-map-scheme>
  <autostart>true</autostart>
</distributed-scheme>

Access cache-config2.xml and the output from that is as follows
2010-11-17 12:57:57.504/4.516 Oracle Coherence GE 3.6.0.0 <Info> (thread=main, member=1): Loaded cache configuration from "file:/C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/CoherenceLoadCustomCacheConfig/Demo/classes/cache-config2.xml"
2010-11-17 12:57:57.508/4.520 Oracle Coherence GE 3.6.0.0 <D5> (thread=DistributedCache:DistributedCacheConfig2, member=1): Service DistributedCacheConfig2 joined the cluster with senior service member 1
<distributed-scheme>
  <scheme-name>distributed</scheme-name>
  <service-name>DistributedCacheConfig2</service-name>
  <backing-map-scheme>
    <local-scheme>
      <high-units>10m</high-units>
    </local-scheme>
  </backing-map-scheme>
  <autostart>true</autostart>
</distributed-scheme>  

More information on  this can be found in the javadoc as follows:

http://download.oracle.com/otn_hosted_doc/coherence/330/com/tangosol/net/DefaultConfigurableCacheFactory.html

Friday, 12 November 2010

JDeveloper 11g - Using Coherence Resource Adapater (RA) Within Weblogic 11g

The following demo is an example on how to use the Coherence RA within Weblogic 11g (10.3.3). In this example we are using Coherence 3.6 and this setup is based on having the RA as a stand alone application which my web based application developed in JDeveloper 11g (11.1.1.3) would then use.

Steps for Setup in WLS 11g (10.3.3)

1. Place coherence.jar into $DOM_HOME/lib directory as shown below.

[oracle@wayne-p2 lib]$ pwd
/home/oracle/product/11gR3/user_projects/domains/cohtx-dom/lib
[oracle@wayne-p2 lib]$ ls -la
total 5324
drwxr-x---   2 oracle oinstall    4096 Nov 10 13:17 .
drwxr-x---  13 oracle oinstall    4096 Nov 10 08:38 ..
-rw-r-----   1 oracle oinstall 5409133 Nov 10 13:17 coherence.jar
-rw-r-----   1 oracle oinstall     702 Nov  7 13:29 readme.txt
[oracle@wayne-p2 lib]$

2. Deploy $COH_HOME/lib/coherence-transaction.rar (Coherence 3.6) to the WLS 10.3.3. Accept all the defaults here during deployment BUT ensure you target it to the managed server you wish to use.



For information on how to use the Coherence RA you just deployed use the documentation
link below.

http://download.oracle.com/docs/cd/E15357_01/coh.360/e15723/api_transactionslocks.htm#BEIEBGAH
Using the Coherence Resource Adapter

Steps for Application Side (JDeveloper 11g - 11.1.1.3)

In the steps below we just highlight what is needed from the JDeveloper project itself, rather then full steps on what to create. This demo was built using Struts/JSP.

1. In the web.xml create a resource reference as shown below.

<resource-ref>
    <res-ref-name>eis/CoherenceTxCF</res-ref-name>
    <res-type>com.tangosol.coherence.transaction.ConnectionFactory
    </res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

2. Create a weblogic.xml file as follows. You add a new one to a web project using "File -> New -> General -> Deployment Descriptors -> Weblogic Deployment Descriptor"
<resource-ref>
<?xml version = '1.0' encoding = 'windows-1252'?>
<weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd"
                  xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app">
    <resource-description>
      <res-ref-name>
        eis/CoherenceTxCF
      </res-ref-name>
      <jndi-name>
        tangosol.coherenceTx
      </jndi-name>
    </resource-description>
    <resource-description>
      <res-ref-name>
        eis/CoherenceTxCCICF
      </res-ref-name>
      <jndi-name>
        tangosol.coherenceTxCCI
      </jndi-name>
    </resource-description>
</weblogic-web-app>

Note: The JNDI resource description "tangosol.coherenceTx" is defined in the Coherence RA we deployed earlier. This maps back to our web.xml JNDI reference "eis/CoherenceTxCF".

3.The cache config file is included in the web project and so must be loaded at application startup. To do this we use a empty servlet and define this in the init() method as shown below.
package support.au.coherence.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class CacheSetupServlet
  extends HttpServlet
{
  private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

  public void init(ServletConfig config) throws ServletException
  {
    // servlet only required to ensure this application using our cache config
    System.setProperty("tangosol.coherence.cacheconfig", 
                       "coherence-tx-cache-config.xml");
    System.out.println("** CacheSetupServlet.init() called **");
    super.init(config);
  }
}  

Note: coherence-tx-cache-config.xml is defined as follows
<?xml version="1.0"?>

<!DOCTYPE cache-config SYSTEM "cache-config.dtd">

<cache-config>

  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>tx-*</cache-name>
      <scheme-name>transactional</scheme-name>
    </cache-mapping>
  </caching-scheme-mapping>

  <caching-schemes>
    <transactional-scheme>
      <scheme-name>transactional</scheme-name>
      <service-name>TestTxnService</service-name>
      <request-timeout>30000</request-timeout>
      <autostart>true</autostart>
    </transactional-scheme>

  </caching-schemes>

</cache-config>

4. In order for this HTTP Servlet to start up at application start up we define an entry in web.xml as follows.
<servlet>
    <servlet-name>CacheSetupServlet</servlet-name>
    <servlet-class>support.au.coherence.demo.CacheSetupServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet> 

5. Now we are ready to dpeloy our application which we can do from JDeveloper itself by creating a WAR deployment profile. A successful deployment is shown as follows

[09:08:54 AM] ----  Deployment started.  ----
[09:08:54 AM] Target platform is  (Weblogic 10.3).
[09:08:58 AM] Retrieving existing application information
[09:08:58 AM] Running dependency analysis...
[09:08:58 AM] Building...
[09:09:02 AM] Deploying profile...
[09:09:02 AM] Wrote Web Application Module to C:\jdev\jdevprod\11113\jdeveloper\jdev\mywork\CoherenceRAWebApplication\Demo\deploy\cohra-web.war
[09:09:02 AM] Redeploying Application...
[09:09:04 AM] [Deployer:149191]Operation 'deploy' on application 'cohra-web' is initializing on 'apple'
[09:09:05 AM] [Deployer:149192]Operation 'deploy' on application 'cohra-web' is in progress on 'apple'
[09:09:06 AM] [Deployer:149194]Operation 'deploy' on application 'cohra-web' has succeeded on 'apple'
[09:09:06 AM] Application Redeployed Successfully.
[09:09:06 AM] The following URL context root(s) were defined and can be used as a starting point to test your application:
[09:09:06 AM] http://10.187.81.36:7003/cohra-web
[09:09:06 AM] Elapsed time for deployment:  12 seconds
[09:09:06 AM] ----  Deployment finished.  ----

The Struts action which does the work here is as follows.

package support.au.coherence.demo;


import com.tangosol.coherence.transaction.Connection;
import com.tangosol.coherence.transaction.ConnectionFactory;

import com.tangosol.coherence.transaction.OptimisticNamedCache;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class TestCohRAAction extends Action
{
  private final String DEPT_TX_CACHE = "tx-dept";
  private final String EMP_TX_CACHE = "tx-emp";
  private final String TX_SERVICE = "TestTxnService";
  
  /**This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
    throws IOException, ServletException
  {
    InitialContext initCtx = null;
    ConnectionFactory factory = null;
    Connection coherenceTxConn = null;
    
    try
    {
      initCtx = getInititalContext();
      factory = (ConnectionFactory) 
          initCtx.lookup("java:comp/env/eis/CoherenceTxCF");
      
      coherenceTxConn = factory.createConnection(TX_SERVICE);
      coherenceTxConn.setAutoCommit(false);
      
      OptimisticNamedCache dept = coherenceTxConn.getNamedCache(DEPT_TX_CACHE);
      OptimisticNamedCache emp  = coherenceTxConn.getNamedCache(EMP_TX_CACHE);
      
      // Empty both caches we want to esnure no data exists prior to the run
      // as inserts will fail if they already exist
      dept.clear();
      emp.clear();
      
      dept.insert("10", "ACCOUNTING");
      emp.insert("1", "dept 10 : PAS");
      emp.insert("2", "dept 10 : LUCIA");
      emp.insert("3", "dept 10 : SIENA");
      emp.insert("4", "dept 10 : LUCAS");
      
      coherenceTxConn.commit();
      
      System.out.println(String.format("Size of dept cache = %s", dept.size()));
      System.out.println(String.format("Size of emp cache = %s", emp.size()));
      
      request.setAttribute
        ("deptcache", 
         String.format("Size of dept cache = %s", dept.size()));

      request.setAttribute
        ("empcache", 
         String.format("Size of emp cache is %s", emp.size()));
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
      coherenceTxConn.rollback();
    }
    finally 
    {
      if (coherenceTxConn != null)
      {
        coherenceTxConn.close();
      }
    }
    
    return mapping.findForward( "success");
  }
  
  private InitialContext getInititalContext () throws NamingException
  {
    return new InitialContext();
  }
} 

The resulting view page simply displays the cache sizes as part of the transaction once committed as shown below.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
  <title>Coherence RA Web Application</title>
</head>
<body>
<h2>Coherence RA Web Application</h2>

${deptcache}
${empcache}
<p />
<hr />
<b>Oracle Support Services</b>

</body>
</html>

The JDeveloper project would look something like this.

Thursday, 11 November 2010

Referencing Coherence from Web Applications (WAR) in WLS 11g

I am constantly providing coherence.jar in the WEB-INF/lib of my web based (WAR) applications in WLS 11g. So obviously it made more sense to deploy coherence.jar as library and then reference it but WLS 11g does not allow web based applications to reference shared library JAR files as per the link below.

http://download.oracle.com/docs/cd/E13222_01/wls/docs92/programming/libraries.html#wp1071062

"You cannot reference any other type of shared J2EE library (EJB, Enterprise application, or plain JAR file) from the weblogic.xml deployment descriptor file of a Web Application."

Here is what i did to get this to work.

1. Create a shared library coherence.jar for version 3.6 as shown below. I targeted this to the managed servers I was using.



2. In my WAR file create a META-INF/MANIFEST.MF with content as follows.

Extension-List: cohlib
cohlib-Extension-Name: coherence
cohlib-Specification-Version: 3.6.0.0
cohlib-Implementation-Version: 3.6.0.0

3. The JDeveloper 11g project would look something like this, as you can clearly see there is no coherence.jar in WEB-INF\lib folder with this setup.


I found this setup as follows enabling me to use JAR files as libraries from WAR / Web Based Applications.

http://download.oracle.com/docs/cd/E13222_01/wls/docs92/programming/libraries.html#wp1064645

Monday, 8 November 2010

Age Expiry Local Cache With Coherence

The local cache supports automatic expiration of entries based on the age of the value, as configured by the expiry-delay tag. The following example will show how to expire cache entries after the configured time as per expiry-delay, regardless of how many times the entry is updated, hence overriding the default behavior.

1. Create a java class as follows.

package support.au.coherence.examples;

import com.tangosol.net.cache.CacheLoader;
import com.tangosol.net.cache.LocalCache;
import com.tangosol.util.SafeHashMap;

public class AgeExpiryLocalCache extends LocalCache
{
  public AgeExpiryLocalCache()
  {
    super();
  }

  public AgeExpiryLocalCache(int cUnits)
  {
    super(cUnits);
  }

  public AgeExpiryLocalCache(int cUnits, int cExpiryMillis)
  {
    super(cUnits, cExpiryMillis);
  }

  public AgeExpiryLocalCache
  (int cUnits, int cExpiryMillis, CacheLoader loader)
  {
    super(cUnits, cExpiryMillis, loader);
  }

  protected SafeHashMap.Entry instantiateEntry()
  {
    return new Entry();
  }

  /**
   * Entry extension that will not reset expiry when entry
   * value is updated.
   */
  public class Entry extends LocalCache.Entry
  {
    public Entry()
    {
      super();
    }

    protected void scheduleExpiry()
    {
      // only set the expiry if it has not been set yet
      if (getExpiryMillis() > 0)
      {
        return;
      }
  
      super.scheduleExpiry();
    }
  }
}

2. Setup you cache config file to use this custom Local Cache as shown below.



 
   
     age-cache
     age-scheme
   
 
 
  
    age-scheme
      
        
           60s         
           
             support.au.coherence.examples.AgeExpiryLocalCache
           
        
      
      true
  
 


So in this example cache entries will expire 60 seconds after they are first inserted regardless of how often it is updated.

Tuesday, 2 November 2010

Connecting to WLS 11g MBeanServer using jconsole on a windows client

Viewing the MBeans available in WLS 11g from the client side with jconsole is done as follows. The key here is to create the necessary client side JAR file required to access WLS 11g using JMX. In this example we are using JDK 1.6.

Note: The steps for JDK 1.5 are NOT identical to these.

1. First create a wlfullclient.jar with steps as follows on the WLS server. This will give you what you need on the client side to connect to WLS MBean Server.

- Change directories to the server/lib directory.

cd WL_HOME/server/lib

- Use the following command to create wlfullclient.jar in the server/lib directory:

java -jar wljarbuilder.jar

2. Now add/provide wlfullclient.jar to the classpath for jconsole on the client side as follows.

jconsole -J-Djava.class.path=wlfullclient.jar;C:\jdev\jdk\jdk1.6.0_21\lib\jconsole.jar -J-Djmx.remote.protocol.provider.pkgs=weblogic.management.remote

3. Jconsole should display requesting you to provide the remote server you wish to connect to. In this example I am simply going to connect to the RUNTIME MBean Sever with connect details as follows for the "Remote Process" field. Also I have to add a username/password for the WLS 11g server in order to connect.

service:jmx:iiop://wayne-p2.au.oracle.com:7003/jndi/weblogic.management.mbeanservers.runtime


4. Press the connect button and now you can easily see which MBeans you wish to view.


For more information on the MBeans in WLS 11g refer to this URL.

http://download.oracle.com/docs/cd/E14571_01/apirefs.1111/e13951/core/index.html