Search This Blog

Showing posts with label Coherence. Show all posts
Showing posts with label Coherence. Show all posts

Thursday, 7 July 2011

Starting a Coherence Server From WLS 10.3.4 Console

Decided it might make sense to use Node Manager to stop/start my stand alone coherence servers which will be accessed by the WebLogic managed server instances as storage disabled members. The process is pretty straight forward and is shown in this blog entry below. However there is one thing to be aware of.

http://blogs.oracle.com/jamesbayer/entry/weblogic_server_1034_screencas

In my example I wanted to use Coherence 3.7 and so to do that I needed to add the following to the "Server Start" Classpath field

/u01/Middleware/coherence/370/coherence/lib/coherence.jar

Once I did that and tried to start the Coherence Server from the admin console , using node manager it failed with an error as follows.

Jul 8, 2011 4:36:25 AM> <INFO> <NodeManager> <Server output log file 
 is 
 '/u01/Middleware/domains/1034/acs_dom/servers_coherence/CoherenceServer1/logs/CoherenceServer1.out'>
 Exception in thread "Main Thread" java.lang.NoClassDefFoundError: 
 weblogic/nodemanager/server/provider/WeblogicCacheServer
 Caused by: java.lang.ClassNotFoundException: 
 weblogic.nodemanager.server.provider.WeblogicCacheServer
         at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
 
The poblem here is if you leave the classpath blank in the startup properties in the console configuration, then the two minimal jars (weblogic.server.modules.coherence.server_10.3.4.0.jar and coherence.jar) that are required are added for you. Once you specify a non-empty classpath (which is what I did), then you have to explicitly include those jars plus any others you want.

So what I needed was the following.

/u01/Middleware/coherence/370/coherence/lib/coherence.jar:/u01/Middleware/1034/modules/features/weblogic.server.modules.coherence.server_10.3.4.0.jar

Once started the Log file for the coherence server exists on the file system as follows:

$DOMAIN_HOME/servers_coherence/{COH_SERVER_NAME}/logs/{COH_SERVER_NAME}.out

The PID for the server is found here, I normally add that to the log file but it's not possible when starting Coherence this way.

$DOMAIN_HOME/servers_coherence/{COH_SERVER_NAME}/data/nodemanager/{COH_SERVER_NAME}.pid

Thursday, 5 May 2011

Thursday, 10 February 2011

JRuby script to access Oracle Coherence MBean attributes

I found a ruby gem known as "jmx4r" to use JMX from JRuby. The aim here was to use that to display details of an MBean's attributes but found it not as easy as I thought it would be. Here are 2 ways I did that, to be honest using option 2 seemed the better way to do this.

Option 1

In this example here I have using Ruby to make dynamic method calls based on the attribute value.
require 'java'
require 'rubygems'
require 'jmx4r'

def display_array (meth)
  data = ""
  
  meth.call.send("each") do |x|
    data += "\n\t" + x.to_s
  end
  
  return data
end

def display_attribute_data(key, mbean)
  meth = mbean.method(key)
  data = ""
  s = meth.call.to_s
  if (/^\[Ljava.lang.String/.match(s))
    # we have a String[] array with data
    return display_array meth
  elsif (/^\[I/.match(s))
    return display_array meth
  else
    return s
  end

end

url = "service:jmx:rmi://localhost:3000/jndi/rmi://localhost:9000/server"
conn = JMX::MBean.establish_connection :url => url
    
mbean = JMX::MBean.find_by_name "Coherence:type=Cluster"

# display attributes key/values
mbean.attributes.each do |key, value|  
 puts "Name: #{key}, Value: #{display_attribute_data key, mbean}\n"
end

# puts "\n\n** PRETTY PRINT DISPLAY attributes/method descriptions ** \n"
#JMX::MBean.pretty_print "Coherence:type=Cluster", :url => url
Output

Name: local_member_id, Value: 2
Name: cluster_size, Value: 2
Name: license_mode, Value: Development
Name: members_departed, Value:
Name: refresh_time, Value: Thu Feb 10 14:40:21 EST 2011
Name: cluster_name, Value: cluster:0xC4DB
Name: running, Value: true
Name: oldest_member_id, Value: 1
Name: members, Value:
        Member(Id=1, Timestamp=2011-02-10 14:38:05.783, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:662
0, Role=CoherenceServer)
        Member(Id=2, Timestamp=2011-02-10 14:38:15.57, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,process:2992
, Role=TangosolNetMBeanConnector)
Name: version, Value: 3.6.0.0
Name: members_departure_count, Value: 0
Name: member_ids, Value:
        1
        2


Option 2

In this example I get a JAVA javax.management.ObjectName so I can easily obtain attribute values by name. In this example I don't make any effort to format the value for the attribute should it be an array type. I could easily just use the code I did in option 1 above.
require 'java'
require 'rubygems'
require 'jmx4r'

java_import 'javax.management.ObjectName'

def display_attribute_data(conn, object_name, attribute)  
  return conn.get_attribute object_name, attribute
end

url = "service:jmx:rmi://localhost:3000/jndi/rmi://localhost:9000/server"
conn = JMX::MBean.establish_connection :url => url
    
mbean = JMX::MBean.find_by_name "Coherence:type=Cluster"
object_name = ObjectName.new "Coherence:type=Cluster"

# display attributes key/values
mbean.attributes.each do |key, value|  
 puts "Name: #{value}, Value: #{display_attribute_data conn, object_name, value}\n"
end 
Output

Name: LocalMemberId, Value: 2
Name: ClusterSize, Value: 2
Name: LicenseMode, Value: Development
Name: MembersDeparted, Value: [Ljava.lang.String;@725967
Name: RefreshTime, Value: Thu Feb 10 14:41:25 EST 2011
Name: ClusterName, Value: cluster:0xC4DB
Name: Running, Value: true
Name: OldestMemberId, Value: 1
Name: Members, Value: [Ljava.lang.String;@6e3e5e
Name: Version, Value: 3.6.0.0
Name: MembersDepartureCount, Value: 0
Name: MemberIds, Value: [I@9b87f6

Monday, 20 December 2010

Querying Coherence Cache from JRuby

To complete the Coherence/JRuby demos this final demo shows how we can query the cache using filters to show the data we are interested in. From this demo you can see our cache has the oracle data dictionary view ALL_DB_OBJECTS data which was loaded from an 11.2.0.2 RDBMS. The output will make that obvious.

JRuby script is as follows - coh-extend-client-query.rb
require 'java'
require 'C:/jdev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar'
require 'C:/jdev/coherence/36/coherence/lib/coherence.jar'

include_class "pas.au.coherence.extend.server.AllDBObject"
import com.tangosol.net.CacheFactory
import com.tangosol.net.NamedCache
import java.util.Date
import java.lang.System
import java.math.BigDecimal
import java.util.Set

puts "***********************************************"
puts "Coherence 3.6 Extend Client Example from JRUBY"
puts "***********************************************"

print "Started at ", Date.new.toString, "\n"

begin

  # setup required properties to connect to proxy server as extend client
  System.setProperty("tangosol.pof.enabled", "true")
  System.setProperty("tangosol.pof.config", "extend-pof-config.xml")
  System.setProperty("tangosol.coherence.cacheconfig", "client-cache-config.xml")
  System.setProperty("proxy.host", "papicell-au2.au.oracle.com")

  # get named cache alldbobjs
  alldbobjs = CacheFactory.getCache("alldbobjs")

  #retrieve size of cache
  print "\nCache [alldbobjs] size  = " + alldbobjs.size().to_s + "\n\n"
  
  #retrieve all SCOTT schema entries
  filter = com.tangosol.util.filter.EqualsFilter.new("getOwner", "SCOTT")
  scottObjects = alldbobjs.entrySet(filter)
  
  #iterate through SCOTT's objects 
  print "\nTotal of " + scottObjects.size().to_s + " cache entries found \n"

  print "Is scottObjects empty : ", scottObjects.empty?, "\n"
  puts
  
  iterator = scottObjects.iterator()
  while iterator.hasNext()
    entry = iterator.next()
    print "Key : [" + entry.getKey().to_s + "] "
    print "Value : [Owner=" + entry.getValue().getOwner() + 
          ", objectName=" + entry.getValue().getObjectName() +
          ", objectType=" + entry.getValue().getObjectType() + "]"
    puts
  end
  
rescue 
  print "\n** Error occured **\n"
 print "Failed to access Coherence Cluster from proxy server -> \n", $!, "\n\n"
  
end

puts
print "Ended at ", Date.new.toString, "\n"

The output when run shows the SCOTT schema objects being queried from the cache


C:\jdev\scripting\demos\jruby\extendclient-coherence>vi coh-extend-client-query.rb


C:\jdev\scripting\demos\jruby\extendclient-coherence>jrb coh-extend-client-query.rb
***********************************************
Coherence 3.6 Extend Client Example from JRUBY
***********************************************
Started at Mon Dec 20 07:36:52 EST 2010
2010-12-20 07:36:52.752/0.869 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational configuration from "jar:file:/C:
/jdev/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence.xml"
2010-12-20 07:36:52.756/0.873 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational overrides from "jar:file:/C:/jde
v/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence-override-dev.xml"
2010-12-20 07:36:52.756/0.873 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/tangosol-coherence-
override.xml" is not specified
2010-12-20 07:36:52.759/0.876 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/custom-mbeans.xml"
is not specified


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-12-20 07:36:52.945/1.062 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Loaded cache configuration from "jar:file:/C:/jd
ev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar!/client-cache-config.xml"
2010-12-20 07:36:53.107/1.224 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Loaded POF configuration fro
m "jar:file:/C:/jdev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar!/extend-pof-config.xml"
2010-12-20 07:36:53.111/1.228 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Loaded included POF configur
ation from "jar:file:/C:/jdev/coherence/36/coherence/lib/coherence.jar!/coherence-pof-config.xml"
2010-12-20 07:36:53.214/1.331 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Started: TcpInitiator{Name=Rem
oteCache:TcpInitiator, State=(SERVICE_STARTED), ThreadCount=0, Codec=Codec(Format=POF), PingInterval=0, PingTimeout=0, RequestTimeout=0, Con
nectTimeout=0, SocketProvider=SystemSocketProvider, RemoteAddresses=[papicell-au2.au.oracle.com/10.187.80.136:9099]}
2010-12-20 07:36:53.218/1.335 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Opening Socket connection to 10.187.80.136:9099
2010-12-20 07:36:53.220/1.337 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Connected to 10.187.80.136:9099


Cache [alldbobjs] size  = 99927




Total of 55 cache entries found
Is scottObjects empty : false


Key : [82967] Value : [Owner=SCOTT, objectName=TEST_STRING, objectType=TABLE]
Key : [126758] Value : [Owner=SCOTT, objectName=Host2, objectType=JAVA CLASS]
Key : [128400] Value : [Owner=SCOTT, objectName=DISPLAYPROPERTIES, objectType=FUNCTION]
Key : [173453] Value : [Owner=SCOTT, objectName=SYS_LOB0000173452C00002$$, objectType=LOB]
Key : [128399] Value : [Owner=SCOTT, objectName=CheckProperties, objectType=JAVA CLASS]
Key : [85457] Value : [Owner=SCOTT, objectName=JUNKPR, objectType=PROCEDURE]
Key : [150089] Value : [Owner=SCOTT, objectName=HELLOWORLDPKG, objectType=PACKAGE]
Key : [155471] Value : [Owner=SCOTT, objectName=CELCIUSTOFAHRENHEIT, objectType=FUNCTION]
Key : [91848] Value : [Owner=SCOTT, objectName=SYS_C0019928, objectType=INDEX]
Key : [82964] Value : [Owner=SCOTT, objectName=TEST_TYP, objectType=TYPE]
Key : [150088] Value : [Owner=SCOTT, objectName=pas/au/jsp/DemoJSP, objectType=JAVA CLASS]
Key : [82966] Value : [Owner=SCOTT, objectName=TEST_PROC1, objectType=PROCEDURE]
Key : [91846] Value : [Owner=SCOTT, objectName=SYS_LOB0000091845C00002$$, objectType=LOB]
Key : [73200] Value : [Owner=SCOTT, objectName=PK_DEPT, objectType=INDEX]
Key : [91849] Value : [Owner=SCOTT, objectName=xp_cmdshell, objectType=JAVA CLASS]
Key : [91855] Value : [Owner=SCOTT, objectName=xp_cmdshell, objectType=JAVA SOURCE]
Key : [126760] Value : [Owner=SCOTT, objectName=HOST_API, objectType=PACKAGE BODY]
Key : [173456] Value : [Owner=SCOTT, objectName=FORMMODEL_INS_TRG, objectType=TRIGGER]
Key : [73199] Value : [Owner=SCOTT, objectName=DEPT, objectType=TABLE]
Key : [155571] Value : [Owner=SCOTT, objectName=SAYHELLONAME, objectType=FUNCTION]
Key : [169925] Value : [Owner=SCOTT, objectName=DEPT_LIST_TABLE, objectType=TYPE]
Key : [173144] Value : [Owner=SCOTT, objectName=CUSTOMER, objectType=TABLE]
Key : [91850] Value : [Owner=SCOTT, objectName=DOIT, objectType=PROCEDURE]
Key : [160445] Value : [Owner=SCOTT, objectName=runhttprequest, objectType=JAVA SOURCE]
Key : [169926] Value : [Owner=SCOTT, objectName=WS_PACKAGE, objectType=PACKAGE]
Key : [73204] Value : [Owner=SCOTT, objectName=SALGRADE, objectType=TABLE]
Key : [160648] Value : [Owner=SCOTT, objectName=SYS_C0046421, objectType=INDEX]
Key : [140715] Value : [Owner=SCOTT, objectName=DRIVERVERSION, objectType=PROCEDURE]
Key : [160446] Value : [Owner=SCOTT, objectName=RunHttpRequest, objectType=JAVA CLASS]
Key : [173455] Value : [Owner=SCOTT, objectName=FORMMODEL_PK, objectType=INDEX]
Key : [73202] Value : [Owner=SCOTT, objectName=PK_EMP, objectType=INDEX]
Key : [169927] Value : [Owner=SCOTT, objectName=WS_PACKAGE, objectType=PACKAGE BODY]
Key : [173452] Value : [Owner=SCOTT, objectName=FORMMODEL, objectType=TABLE]
Key : [79037] Value : [Owner=SCOTT, objectName=XML_PACKAGE, objectType=PACKAGE]
Key : [91845] Value : [Owner=SCOTT, objectName=CREATE$JAVA$LOB$TABLE, objectType=TABLE]
Key : [160890] Value : [Owner=SCOTT, objectName=MYTEST3, objectType=TABLE]
Key : [160647] Value : [Owner=SCOTT, objectName=CAL, objectType=TABLE]
Key : [155581] Value : [Owner=SCOTT, objectName=SAYHELLONAME_SYS, objectType=FUNCTION]
Key : [79038] Value : [Owner=SCOTT, objectName=XML_PACKAGE, objectType=PACKAGE BODY]
Key : [169924] Value : [Owner=SCOTT, objectName=DEPT_TYPE, objectType=TYPE]
Key : [85455] Value : [Owner=SCOTT, objectName=Junk, objectType=JAVA SOURCE]
Key : [155472] Value : [Owner=SCOTT, objectName=CELCIUSTOFAHRENHEIT1, objectType=FUNCTION]
Key : [155473] Value : [Owner=SCOTT, objectName=CELCIUSTOFAHRENHEIT2, objectType=FUNCTION]
Key : [173457] Value : [Owner=SCOTT, objectName=FORMMODEL_UPD_TRG, objectType=TRIGGER]
Key : [180988] Value : [Owner=SCOTT, objectName=ALL_DB_OBJECTS, objectType=TABLE]
Key : [160447] Value : [Owner=SCOTT, objectName=FN_RUN_HTTP_REQUEST, objectType=FUNCTION]
Key : [150090] Value : [Owner=SCOTT, objectName=HELLOWORLDPKG, objectType=PACKAGE BODY]
Key : [91851] Value : [Owner=SCOTT, objectName=JAVA$OPTIONS, objectType=TABLE]
Key : [173458] Value : [Owner=SCOTT, objectName=FORMMODEL_ID_SEQ, objectType=SEQUENCE]
Key : [85456] Value : [Owner=SCOTT, objectName=Junk, objectType=JAVA CLASS]
Key : [162619] Value : [Owner=SCOTT, objectName=TMP_JD_TEST, objectType=TABLE]
Key : [126759] Value : [Owner=SCOTT, objectName=HOST_API, objectType=PACKAGE]
Key : [73201] Value : [Owner=SCOTT, objectName=EMP, objectType=TABLE]
Key : [73203] Value : [Owner=SCOTT, objectName=BONUS, objectType=TABLE]
Key : [126757] Value : [Owner=SCOTT, objectName=HOST2, objectType=JAVA SOURCE]


Ended at Mon Dec 20 07:36:54 EST 2010

Thursday, 16 December 2010

Access Coherence Cache from JRuby as an Extend client

In my previous example below I wanted to quickly join a coherence cluster from JRuby and basically did it the easiest way possible by simply becoming a member in the cluster.

Access Coherence Cache from JRuby/Jython scripts

In the example below we will we use JRuby as a Coherence*Extend client using POF (Portable Object Format) and we do this for the following reasons.

1. Being a console application we want to connect/disconnect many times a day and even though we are a storage disabled member it results in overhead which an extend client avoids.
2. Being an extend client we are storage disabled by default.
3. Using POF has many advantages ranging from performance benefits to language independence, although in this example we are using it from a Java enabled client.

So our JRuby code is now as follows.
require 'java'
require 'C:/jdev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar'
require 'C:/jdev/coherence/36/coherence/lib/coherence.jar'

include_class "pas.au.coherence.extend.server.AllDBObject"
import com.tangosol.net.CacheFactory
import com.tangosol.net.NamedCache
import java.util.Date
import java.lang.System
import java.math.BigDecimal

puts "***********************************************"
puts "Coherence 3.6 Extend Client Example from JRUBY"
puts "***********************************************"

print "Started at ", Date.new.toString, "\n"

begin

  # setup required properties to connect to proxy server as extend client
  System.setProperty("tangosol.coherence.cacheconfig", "client-cache-config.xml")
  System.setProperty("tangosol.pof.enabled", "true")
  System.setProperty("tangosol.pof.config", "extend-pof-config.xml")
  System.setProperty("proxy.host", "papicell-au2.au.oracle.com")

  # get named cache alldbobjs
  alldbobjs = CacheFactory.getCache("alldbobjs")

  #retrieve size of cache
  print "\nCache [alldbobjs] size  = " + alldbobjs.size().to_s + "\n\n"

  #retrieve one record
  objectid = BigDecimal.new(54)

  objectrecord = AllDBObject.new
  objectrecord = alldbobjs.get(objectid)

  puts "Record 54 = " + objectrecord.to_s
  puts

rescue
  print "\n** Error occured **\n"
        print "Failed to access Coherence Cluster from proxy server ", $!, "\n\n"

end

print "Ended at ", Date.new.toString, "\n"
From the code we have done the following.

1. Used a client cache config file to connect as an extend client, basically connect to an extend proxy which is a cluster member.

2. We provide a client JAR file which contains our domain objects and config files that being extenddemo.jar

3. The client cache config is defined as follows.
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">

<cache-config>
  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>alldbobjs</cache-name>
      <scheme-name>remote</scheme-name>
    </cache-mapping>
  </caching-scheme-mapping>
  <caching-schemes>
    <remote-cache-scheme>
      <scheme-name>remote</scheme-name>
      <initiator-config>
        <tcp-initiator>
          <remote-addresses>
            <socket-address>
              <address system-property="proxy.host">
  papicell-au2.au.oracle.com
       </address>
              <port system-property="proxy.port">
                9099
              </port>
              <reusable>true</reusable>
            </socket-address>
          </remote-addresses>
        </tcp-initiator>
      </initiator-config>
    </remote-cache-scheme>
  </caching-schemes>
</cache-config>

So when we run this we get output as follows.

C:\jdev\scripting\demos\jruby\extendclient-coherence>jrb coh-extend-client.rb
***********************************************
Coherence 3.6 Extend Client Example from JRUBY
***********************************************
Started at Thu Dec 16 14:08:06 EST 2010
2010-12-16 14:08:06.114/1.033 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational configuration from "jar:file:/C:
/jdev/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence.xml"
2010-12-16 14:08:06.118/1.037 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational overrides from "jar:file:/C:/jde
v/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence-override-dev.xml"
2010-12-16 14:08:06.118/1.037 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/tangosol-coherence-
override.xml" is not specified
2010-12-16 14:08:06.121/1.040 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/custom-mbeans.xml"
is not specified


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-12-16 14:08:06.304/1.223 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Loaded cache configuration from "jar:file:/C:/jd
ev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar!/client-cache-config.xml"
2010-12-16 14:08:06.472/1.391 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Loaded POF configuration fro
m "jar:file:/C:/jdev/scripting/demos/jruby/extendclient-coherence/extenddemo.jar!/extend-pof-config.xml"
2010-12-16 14:08:06.475/1.394 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Loaded included POF configur
ation from "jar:file:/C:/jdev/coherence/36/coherence/lib/coherence.jar!/coherence-pof-config.xml"
2010-12-16 14:08:06.567/1.486 Oracle Coherence GE 3.6.0.0 (thread=RemoteCache:TcpInitiator, member=n/a): Started: TcpInitiator{Name=Rem
oteCache:TcpInitiator, State=(SERVICE_STARTED), ThreadCount=0, Codec=Codec(Format=POF), PingInterval=0, PingTimeout=0, RequestTimeout=0, Con
nectTimeout=0, SocketProvider=SystemSocketProvider, RemoteAddresses=[papicell-au2.au.oracle.com/10.187.80.136:9099]}
2010-12-16 14:08:06.572/1.491 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Opening Socket connection to 10.187.80.136:9099
2010-12-16 14:08:06.580/1.499 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Connected to 10.187.80.136:9099


Cache [alldbobjs] size  = 99927


Record 54 = AllDbObject - owner: SYS ,objectName: I_CDEF2 ,subObjectName: null ,objectId: 54 ,dataObjectId: 54 ,objectType: INDEX ,created:
2009-08-15 ,lastDDLTime: 2009-08-15 ,timestamp: 2009-08-15:00:16:51 ,status: VALID ,temporrary: N ,generated: N ,secondary: N ,namespace: 4
,editionName: null


Ended at Thu Dec 16 14:08:06 EST 2010

Monday, 6 December 2010

Access Coherence Cache from JRuby/Jython scripts

The following example show how to use JRuby or Jython to access Coherence caches. Although this is basic and simply using the cache config file out of coherence.jar it gives you enough to see how simple it is to join the cluster as member and access coherence.jar from these 2 scripting languages.

I could of easily used groovy here as well but decided to stick with jruby and jython for now. Also the script members that join the cluster are storage disabled meaning that they must connect to node which is storage enabled to add data to the cache.

For this demo I have the following installed.
  • Coherence 3.6
  • JDK 1.6
  • JRuby 1.5.6
  • Jython 2.5.1
PRE STEPS

1. Start a cache server as follows. We do this to ensure we have a storage enabled node. The cache config file being used is the one inside coherence.jar. 

C:\jdev\coherence\36\coherence\bin>cache-server.cmd

In the example below jy = jython and jrb = jruby executables.

JRUBY

1. Create a ruby script as follows.
require 'java'
require 'C:/jdev/coherence/36/coherence/lib/coherence.jar'

import com.tangosol.net.CacheFactory
import com.tangosol.net.NamedCache
import java.util.Date
import java.lang.System

puts "*********************************"
puts "Coherence 3.6 Example from JRUBY"
puts "*********************************"

print "Started at ", Date.new.toString, "\n"

begin

  # ensure we are storage disabled
  System.setProperty("tangosol.coherence.distributed.localstorage", "false")
  
  CacheFactory.ensureCluster

  # get named cache
  testcache = CacheFactory.getCache("Test")

  # add data to cache
  testcache.put("1", "pas apicella")

  # retrive data from cache
  puts "Cache entry 1 = " + testcache.get("1")
  
rescue 
 print "Failed to access Coherence Cluster ", $!, "\n"
 
ensure 
  CacheFactory.shutdown
  
end

print "Ended at ", Date.new.toString, "\n"

2. Run it as follows ensuring your reference coherence.jar correctly

> jrb coherence.rb

Output as follows


C:\jdev\scripting\demos\jruby>jrb coherence.rb
*********************************
Coherence 3.6 Example from JRUBY
*********************************
Started at Mon Dec 06 11:38:09 EST 2010
2010-12-06 11:38:09.939/0.855 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational configuration from "jar:file:/C:
/jdev/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence.xml"
2010-12-06 11:38:09.942/0.858 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational overrides from "jar:file:/C:/jde
v/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence-override-dev.xml"
2010-12-06 11:38:09.943/0.859 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/tangosol-coherence-
override.xml" is not specified
2010-12-06 11:38:09.946/0.862 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/custom-mbeans.xml"
is not specified


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-12-06 11:38:10.474/1.390 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): TCMP bound to /10.187.114.243:8090 using SystemSoc
ketProvider
2010-12-06 11:38:11.683/2.600 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): This Member(Id=2, Timestamp=2010-12-06 11:38:
11.675, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,process:3824, Role=JrubyMain, Edition=Grid Edition, Mode=De
velopment, CpuCount=4, SocketCount=4) joined cluster "cluster:0xC4DB" with senior Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Address=10
.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:1280, Role=CoherenceServer, Edition=Grid Edition, Mode=Development, C
puCount=4, SocketCount=4)
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service Cluster with senior mem
ber 1
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service Management with senior
member 1
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service DistributedCache with s
enior member 1
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service ReplicatedCache with se
nior member 1
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service OptimisticCache with se
nior member 1
2010-12-06 11:38:11.693/2.609 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service InvocationService with
senior member 1
2010-12-06 11:38:11.697/2.613 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Started cluster Name=cluster:0xC4DB


Group{Address=224.3.6.0, Port=36000, TTL=4}


MasterMemberSet
  (
  ThisMember=Member(Id=2, Timestamp=2010-12-06 11:38:11.675, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,proces
s:3824, Role=JrubyMain)
  OldestMember=Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,proc
ess:1280, Role=CoherenceServer)
  ActualMemberSet=MemberSet(Size=2, BitSetCount=2
    Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:1280, R
ole=CoherenceServer)
    Member(Id=2, Timestamp=2010-12-06 11:38:11.675, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,process:3824, R
ole=JrubyMain)
    )
  RecycleMillis=1200000
  RecycleSet=MemberSet(Size=0, BitSetCount=0
    )
  )


TcpRing{Connections=[1]}
IpMonitor{AddressListSize=0}


2010-12-06 11:38:11.727/2.643 Oracle Coherence GE 3.6.0.0 (thread=Invocation:Management, member=2): Service Management joined the clust
er with senior service member 1
2010-12-06 11:38:11.788/2.704 Oracle Coherence GE 3.6.0.0 (thread=main, member=2): Loaded cache configuration from "jar:file:/C:/jdev
/coherence/36/coherence/lib/coherence.jar!/coherence-cache-config.xml"
2010-12-06 11:38:12.017/2.933 Oracle Coherence GE 3.6.0.0 (thread=DistributedCache, member=2): Service DistributedCache joined the clus
ter with senior service member 1
Cache entry 1 = pas apicella
2010-12-06 11:38:12.124/3.040 Oracle Coherence GE 3.6.0.0 (thread=Invocation:Management, member=2): Service Management left the cluster


2010-12-06 11:38:12.129/3.045 Oracle Coherence GE 3.6.0.0 (thread=DistributedCache, member=2): Service DistributedCache left the cluste
r
2010-12-06 11:38:12.222/3.138 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=2): Service Cluster left the cluster
Ended at Mon Dec 06 11:38:12 EST 2010


C:\jdev\scripting\demos\jruby>


JYTHON

1. Create a jython script as follows
from com.tangosol.net import CacheFactory, NamedCache
from java.util import Date
from java.lang import System as javasystem

print "*********************************"
print "Coherence 3.6 Example from JYTHON"
print "*********************************"

print "Started at " + Date().toString()

try:

 javasystem.setProperty("tangosol.coherence.distributed.localstorage", "false")
  
 CacheFactory.ensureCluster()
 
 # get named cache
 testcache = CacheFactory.getCache("Test")
 
 # add data to cache
 testcache.put("1", "pas apicella")

 # retrive data from cache
 print "Cache entry 1 = " + testcache.get("1")

except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
    
finally:
    CacheFactory.shutdown()
    
print "Ended at " + Date().toString()
    
    
2. Add coherence.jar to the classpath as shown below.

> set CLASSPATH=C:\jdev\coherence\36\coherence\lib\coherence.jar

3. Run it as follows ensuring your reference coherence.jar correctly

> jy coherence.py

Output as follows


C:\jdev\scripting\demos\jython>jy coherence.py
*********************************
Coherence 3.6 Example from JYTHON
*********************************
Started at Mon Dec 06 11:41:08 EST 2010
2010-12-06 11:41:08.838/1.916 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational configuration from "jar:file:/C:
/jdev/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence.xml"
2010-12-06 11:41:08.844/1.922 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Loaded operational overrides from "jar:file:/C:/jde
v/coherence/36/coherence/lib/coherence.jar!/tangosol-coherence-override-dev.xml"
2010-12-06 11:41:08.845/1.923 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/tangosol-coherence-
override.xml" is not specified
2010-12-06 11:41:08.851/1.929 Oracle Coherence 3.6.0.0 (thread=main, member=n/a): Optional configuration override "/custom-mbeans.xml"
is not specified


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-12-06 11:41:10.012/3.090 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): TCMP bound to /10.187.114.243:8090 using SystemSoc
ketProvider
2010-12-06 11:41:11.191/4.269 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): This Member(Id=3, Timestamp=2010-12-06 11:41:
11.172, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,process:6172, Role=PythonUtilJython, Edition=Grid Edition,
Mode=Development, CpuCount=4, SocketCount=4) joined cluster "cluster:0xC4DB" with senior Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Add
ress=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:1280, Role=CoherenceServer, Edition=Grid Edition, Mode=Develop
ment, CpuCount=4, SocketCount=4)
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service Cluster with senior mem
ber 1
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service Management with senior
member 1
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service DistributedCache with s
enior member 1
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service ReplicatedCache with se
nior member 1
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service OptimisticCache with se
nior member 1
2010-12-06 11:41:11.207/4.285 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=n/a): Member 1 joined Service InvocationService with
senior member 1
2010-12-06 11:41:11.210/4.288 Oracle Coherence GE 3.6.0.0 (thread=main, member=n/a): Started cluster Name=cluster:0xC4DB


Group{Address=224.3.6.0, Port=36000, TTL=4}


MasterMemberSet
  (
  ThisMember=Member(Id=3, Timestamp=2010-12-06 11:41:11.172, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,proces
s:6172, Role=PythonUtilJython)
  OldestMember=Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,proc
ess:1280, Role=CoherenceServer)
  ActualMemberSet=MemberSet(Size=2, BitSetCount=2
    Member(Id=1, Timestamp=2010-12-06 11:37:53.952, Address=10.187.114.243:8088, MachineId=50163, Location=machine:paslap-au,process:1280, R
ole=CoherenceServer)
    Member(Id=3, Timestamp=2010-12-06 11:41:11.172, Address=10.187.114.243:8090, MachineId=50163, Location=machine:paslap-au,process:6172, R
ole=PythonUtilJython)
    )
  RecycleMillis=1200000
  RecycleSet=MemberSet(Size=0, BitSetCount=0
    )
  )


TcpRing{Connections=[1]}
IpMonitor{AddressListSize=0}


2010-12-06 11:41:11.243/4.321 Oracle Coherence GE 3.6.0.0 (thread=Invocation:Management, member=3): Service Management joined the clust
er with senior service member 1
2010-12-06 11:41:11.300/4.378 Oracle Coherence GE 3.6.0.0 (thread=main, member=3): Loaded cache configuration from "jar:file:/C:/jdev
/coherence/36/coherence/lib/coherence.jar!/coherence-cache-config.xml"
2010-12-06 11:41:11.438/4.516 Oracle Coherence GE 3.6.0.0 (thread=DistributedCache, member=3): Service DistributedCache joined the clus
ter with senior service member 1
Cache entry 1 = pas apicella
2010-12-06 11:41:11.484/4.562 Oracle Coherence GE 3.6.0.0 (thread=Invocation:Management, member=3): Service Management left the cluster


2010-12-06 11:41:11.488/4.566 Oracle Coherence GE 3.6.0.0 (thread=DistributedCache, member=3): Service DistributedCache left the cluste
r
2010-12-06 11:41:11.580/4.658 Oracle Coherence GE 3.6.0.0 (thread=Cluster, member=3): Service Cluster left the cluster
Ended at Mon Dec 06 11:41:11 EST 2010


C:\jdev\scripting\demos\jython>

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.

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.

Thursday, 30 September 2010

Running Coherence Query/Command line clients in JDeveloper 11g

Always wanted to run the command line client and query client from JDeveloper but because JDeveloper does not allow you to specify a runnable class which belongs in a JAR file this is not possible. However thanks to the help of an internal employee I found you can do it as follows

The two clients are these two scripts below which use a class in coherence.jar as follows

coherence.cmd - com.tangosol.net.CacheFactory
query.cmd (New In Coherence 3.6) - com.tangosol.coherence.dslquery.QueryPlus

1. Create a new empty project in JDeveloper
2. Add 2 classes as follows for each client.

coherence.cmd - com.tangosol.net.CacheFactory
package pas.au.coherence.utils;

import com.tangosol.net.CacheFactory;

public class JdevCoherenceClient extends CacheFactory
{
  public JdevCoherenceClient()
  {
  }
}

query.cmd (New In Coherence 3.6) - com.tangosol.coherence.dslquery.QueryPlus
package pas.au.coherence.utils;

import com.tangosol.coherence.dslquery.QueryPlus;

public class JdevCoherenceQueryClient extends QueryPlus
{
  public JdevCoherenceQueryClient()
  {
  }
}

3.At a minimum if we use the default cache config file in coherence.jar we simply need to create a run/debug/profile for each client as follows. This is the example for the QueryPlus client where the config is called "CoherenceQueryClient"


Notice how I have set the JVM propery -Dtangosol.coherence.ttl=0 to avoid joining any clusters outside my own machine. Basically this will ensure no packets are sent from my machine. You would specify any other properties here for coherence such as -Dtangosol.coherence.cacheconfig if you have your own config file. Also the "Default Run target" is set to the class we created above which will then use the class we extended.

4. In that dialog select "Tool Settings" and ensure "Allow program Input" is checked as we need to type at the command prompt.

5. Now run your config select the Run icon in the toolbar and then selecting one of the 2 config you created.

Output in the log window would be as follows

Monday, 27 September 2010

Coherence - Continuous Query Caching

Coherence provides the ability to have a cache provide a feature that combines a query result with a continuous stream of related events to maintain an up-to-date query result in a real-time fashio. To demonstrate this here is a simple demo.

1. Create a very simple object which contains a single attribute "gender" for either male's or females.

package pas.au.coherence.querycaching;

public class DemoObject implements java.io.Serializable
{
  private String gender;

  public DemoObject ()
  {  
  }

  public DemoObject (String _gender)
  {  
   gender = _gender;
  }
  
  public String getGender() 
  {
    return gender;
  }

  public void setGender(String gender) 
  {
    this.gender = gender;
  }
  
}
2. Create a simple test class as follows.
package pas.au.coherence.querycaching;

import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
import com.tangosol.net.cache.ContinuousQueryCache;
import com.tangosol.util.Filter;
import com.tangosol.util.filter.EqualsFilter;

import java.util.logging.Level;
import java.util.logging.Logger;

public class ContinuousQueryCacheDemo
{
  private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
  
  public ContinuousQueryCacheDemo()
  {
  }

  public void doLogMessage (String message)
  {
    logger.log (Level.INFO, message);  
  }
  
  public void run()
  {
    NamedCache test = CacheFactory.getCache("mycache");
    
    // put some data in
    test.put("1", new DemoObject("male"));
    test.put("2", new DemoObject("female"));
    test.put("3", new DemoObject("female"));
    test.put("4", new DemoObject("female"));
    test.put("5", new DemoObject("female"));
    test.put("6", new DemoObject("male"));
    
    doLogMessage("Size of mycache [mycache] = " + test.size());
    
    Filter filter = new EqualsFilter("getGender", "male");
    // Create Continuous Query Cache
    ContinuousQueryCache allMales =
      new ContinuousQueryCache(test, filter);
    
    doLogMessage("Created Query Cache with just MALES [allmales]");
    doLogMessage("Size of Continuous Query Caching [allMales] = " + allMales.size());
    
    // add another male entry to test cache
    test.put("7", new DemoObject("male"));
    
    doLogMessage("New MALE object added");
    
    // check if Continuous Query Caching has that entry added
    doLogMessage("Size of Continuous Query Cache [allMales] = " + allMales.size());
    
    doLogMessage("all done.."); 
  }
  
  public static void main(String[] args) 
  {
    ContinuousQueryCacheDemo test = new ContinuousQueryCacheDemo();
    test.run();
  }
}  

3.When you run this example you can see how adding objects to the named cache "mycache" it automatically maintains the ContinuousQueryCache locally on the client.

OUTPUT from an ANT client

....
     [java]   ThisMember=Member(Id=1, Timestamp=2010-09-27 09:36:06.633, Address=10.187.114.243:8088, MachineId=50163, L
ocation=machine:paslap-au,process:4176, Role=PasAuContinuousQueryCacheDemo)
     [java]   OldestMember=Member(Id=1, Timestamp=2010-09-27 09:36:06.633, Address=10.187.114.243:8088, MachineId=50163,
 Location=machine:paslap-au,process:4176, Role=PasAuContinuousQueryCacheDemo)
     [java]   ActualMemberSet=MemberSet(Size=1, BitSetCount=2
     [java]     Member(Id=1, Timestamp=2010-09-27 09:36:06.633, Address=10.187.114.243:8088, MachineId=50163, Location=m
achine:paslap-au,process:4176, Role=PasAuContinuousQueryCacheDemo)
     [java]     )
     [java]   RecycleMillis=1200000
     [java]   RecycleSet=MemberSet(Size=0, BitSetCount=0
     [java]     )
     [java]   )
     [java]
     [java] TcpRing{Connections=[]}
     [java] IpMonitor{AddressListSize=0}
     [java]
     [java] 2010-09-27 09:36:10.003/4.197 Oracle Coherence GE 3.6.0.0 (thread=Invocation:Management, member=1): Ser
vice Management joined the cluster with senior service member 1
     [java] 2010-09-27 09:36:10.174/4.368 Oracle Coherence GE 3.6.0.0 (thread=DistributedCache, member=1): Service
DistributedCache joined the cluster with senior service member 1
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: Size of mycache [mycache] = 6
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: Created Query Cache with just MALES [allmales]
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: Size of Continuous Query Caching [allMales] = 2
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: New MALE object added
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: Size of Continuous Query Cache [allMales] = 3
     [java] 27/09/2010 9:36:10 AM pas.au.coherence.querycaching.ContinuousQueryCacheDemo doLogMessage
     [java] INFO: all done..
     [java]


More info on this as follows

Oracle® Coherence Developer's Guide
Release 3.6

Part Number E15723-01
http://download.oracle.com/docs/cd/E15357_01/coh.360/e15723/api_continuousquery.htm

Monday, 20 September 2010

Display Cache Scheme from Coherence

Whenever I run coherence.cmd (windows) and I ask for a NamedCache using "cache pastest" for example it prints out the current scheme which I thought was handy for my own testing. After help from Patrick here is what your own code would like like to get that information yourself, if required.

 Note: I was using Coherence 3.6 but same code should work in 3.5 as well

1. Create a class as follows.
package pas.au.coherence.utils;

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

public class DisplaySchemeName 
{
    private static final String CACHE_NAME = "repl-pas";
  
    public DisplaySchemeName() 
    {
    }

    public static void main(String[] args) 
    {
      // TODO Auto-generated method stub
      NamedCache pastest = CacheFactory.getCache(CACHE_NAME);
      
      DefaultConfigurableCacheFactory factory = 
       (DefaultConfigurableCacheFactory) CacheFactory.getConfigurableCacheFactory();

      CacheInfo info = factory.findSchemeMapping(CACHE_NAME);
      
      System.out.println(String.valueOf(factory.resolveScheme(info)));
      System.out.println("all done..");
  
    }
}

2. Run it to verify it displays the cache scheme we are using as shown below.

....
....
TcpRing{Connections=[]}
IpMonitor{AddressListSize=0}

2010-09-20 12:43:17.259/4.898 Oracle Coherence GE 3.6.0.0 <D5> (thread=Invocation:Management, member=1): Service Management joined the cluster with senior service member 1
2010-09-20 12:43:17.463/5.102 Oracle Coherence GE 3.6.0.0 <D5> (thread=ReplicatedCache, member=1): Service ReplicatedCache joined the cluster with senior service member 1
<replicated-scheme>
  <scheme-name>example-replicated</scheme-name>
  <service-name>ReplicatedCache</service-name>
  <backing-map-scheme>
    <local-scheme>
      <scheme-ref>unlimited-backing-map</scheme-ref>
    </local-scheme>
  </backing-map-scheme>
  <autostart>true</autostart>
</replicated-scheme>
all done..
2010-09-20 12:43:17.510/5.149 Oracle Coherence GE 3.6.0.0 <D4> (thread=ShutdownHook, member=1): ShutdownHook: stopping cluster node
2010-09-20 12:43:17.510/5.149 Oracle Coherence GE 3.6.0.0 <D5> (thread=Cluster, member=1): Service Cluster left the cluster

Wednesday, 4 August 2010

Coherence Extend client from Oracle 11g RDBMS

Given coherence JAR file isn't that large I have always wanted a coherence client to run from the database itself by connecting to extend proxy client. Here is how I did this and what is required on the Oracle DB side to ensure you can run java code within the database to connect to a coherence extend proxy client.

Note: This was done with Oracle 11g r2 (11.2.0.1) RDBMS. The JVM in the DB is a 1.5 JVM version. So you won't be able to use JDK 1.6 for this.

1. First we create a new schema called COHERENCE in our database. The script to create this user is as follows.

drop user coherence cascade;

create user coherence identified by coherence
default tablespace users
temporary tablespace temp;

grant dba to coherence;

execute dbms_java.grant_permission('COHERENCE','SYS:java.util.PropertyPermission','*', 'read,write');

execute dbms_java.grant_permission('COHERENCE','SYS:java.lang.RuntimePermission', 'accessClassInPackage.sun.util.calendar','');

execute dbms_java.grant_permission('COHERENCE','SYS:java.lang.RuntimePermission','getClassLoader','');

execute dbms_java.grant_permission('COHERENCE','SYS:java.lang.RuntimePermission','createClassLoader','');

execute dbms_java.grant_permission('COHERENCE','SYS:java.net.SocketPermission','*','listen,connect,resolve');

execute dbms_java.grant_permission('COHERENCE','SYS:java.util.PropertyPermission','*','read,write');

execute dbms_java.grant_permission('COHERENCE','SYS:java.lang.RuntimePermission','setFactory','');

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.net.SocketPermission', 'localhost:8088', 'listen,resolve' );

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.io.FilePermission', '/tangosol-coherence-override-dev.xml', 'read');

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.io.FilePermission', '/tangosol-coherence-override.xml', 'read');

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.io.FilePermission', '/custom-mbeans.xml', 'read');

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.net.SocketPermission', 'papicell-au.au.oracle.com:9099', 'connect,accept,resolve');

execute dbms_java.grant_permission('COHERENCE', 'SYS:java.security.SecurityPermission', 'getDomainCombiner', '' );

prompt
prompt COHERENCE user ready to roll
prompt
prompt all done..

As you can see I granted DBA to the user coherence only because I wanted to get this up and running quickly but in theory the DBA role should not be required. Also all those privileges are required in order to create a socket connection to the extend proxy client.

2. Load the following 3 JAR files into the database using the new user coherence. In order for the database to load/resolve coherence.jar it will require the log4j and sleepycat JAR files. I tried to avoid loading them as coherence outside of the database runs fine with just coherence.jar but inside the database it needed to compile/resolve the class files which meant it needed those 2 JAR files to do that. To me it's not a big issue as there quite small JAR files as well.

loadjava -u coherence/coherence -r -v -f -s -grant public log4j-1.2.15.jar

loadjava -u coherence/coherence -r -v -f -s -grant public je.jar

loadjava -u coherence/coherence -r -v -f -s -grant public coherence.jar

Note: There will be some errors resolving some of the classes but the main ones needed will resolve/compile fine so just ignore the errors. In fact a query as follow should show most of classes as VALID.

COHERENCE@linux11gr2> @check

STATUS    COUNT(*)
------- ----------
INVALID         11
VALID         3200


Java Name                                                    STATUS
------------------------------------------------------------ ----------
com/tangosol/util/internal/SunMiscCounter                    INVALID
com/tangosol/util/internal/SunMiscCounter$1                  INVALID
com/sleepycat/persist/model/ClassEnhancerTask                INVALID
org/apache/log4j/jmx/Agent                                   INVALID
com/tangosol/run/jca/CacheAdapter                            INVALID
com/tangosol/run/jca/CacheAdapter$CacheConnectionSpec        INVALID
com/tangosol/engarde/websphere/SecurityHelper                INVALID
com/tangosol/engarde/StubManagerHookup                       INVALID
com/tangosol/engarde/StubManager                             INVALID
com/tangosol/engarde/EjbRouter                               INVALID
com/tangosol/engarde/DebugStubManagerHookup                  INVALID

11 rows selected.

COHERENCE@linux11gr2> l
  1  select dbms_java.longname(object_name) "Java Name", status
  2  from user_objects
  3  where object_type like '%JAVA%'
  4* and status = 'INVALID'

3.Now we have a proxy client running on "papicell-au.au.oracle.com:9099" which is storage disabled but we have other cluster nodes which are storage enabled. In this setup the extend proxy client  is the node the database client will connect to and hence why we set it up with this privilege.

execute dbms_java.grant_permission( 'COHERENCE', 'SYS:java.net.SocketPermission', 'papicell-au.au.oracle.com:9099', 'connect,accept,resolve');

4. Now we are ready to actually create a Java Stored procedure which will connect to the extend proxy client and put/get data off the cache. The code for this is as follows and must be loaded into the database.

import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;

public class CoherenceClient
{
  public CoherenceClient()
  {
  }
  
  public static void getData ()
  {
    System.setProperty("tangosol.coherence.cacheconfig", "jserver:/resource/schema/COHERENCE/client-cache-config.xml");
    System.setProperty("tangosol.coherence.distributed.localstorage", "false");
    
    NamedCache cache = CacheFactory.getCache("test");

    System.out.println("Key 1 = " + cache.get(1));
    
    CacheFactory.shutdown();
  }
  
  public static void putData ()
  {
    System.setProperty("tangosol.coherence.cacheconfig", "jserver:/resource/schema/COHERENCE/client-cache-config.xml");
    System.setProperty("tangosol.coherence.distributed.localstorage", "false");
    
    NamedCache cache = CacheFactory.getCache("test");

    cache.put(1, "Pas Apicella");
    
    CacheFactory.shutdown();   
  }
} 

5. The client cache config file which needs to be loaded into the database with the Java Class is as follows. You can see it connects to "papicell-au.au.oracle.com:9099" which is our extend proxy client host:port. This file is called "client-cache-config.xml" which is loaded into the database itself.

<?xml version="1.0"?>
<?xml version="1.0"?>

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

<cache-config>
  <caching-scheme-mapping>
    <cache-mapping>
      <cache-name>*</cache-name>
      <scheme-name>remote</scheme-name>
    </cache-mapping>
  </caching-scheme-mapping>
  <caching-schemes>
    <remote-cache-scheme>
      <scheme-name>remote</scheme-name>
      <initiator-config>
        <tcp-initiator>
          <remote-addresses>
            <socket-address>
              <address>papicell-au.au.oracle.com</address>
              <port>9099</port>
              <reusable>true</reusable>
            </socket-address>
          </remote-addresses>
        </tcp-initiator>
      </initiator-config>
    </remote-cache-scheme>
  </caching-schemes>
</cache-config>

6. The Java Stored procedure was created in JDeveloper 10g given we are using JDK 1.5 that made it easier to deploy from JDeveloper itself. The project is as follows. In this setup we simply exposed the Java Stored procedure static methods as 2 PLSQL procedures, but it would make sense to use a PLSQL package here rather then stand alone procedures.



7. You will see we reference the client cache config file as follows in our Java Stored procedure which is how it's done in the Oracle JVM.

System.setProperty("tangosol.coherence.cacheconfig", 
                               "jserver:/resource/schema/COHERENCE/client-cache-config.xml");

8. Finally we are ready to invoke our Java Stored Procedure which was loaded as follows. By creating a Java Stored procedure we are making it available in SQL terms. This means any client can invoke the coherence client , meaning even a PLSQL client if it wanted to or a .NET client. You simple call the stored procedures like any other procedures in the database. Basically when we test this we will use SQL*Plus to verify it works.

JDEV Log window which shows a successful deployment.

Invoking loadjava on connection 'coherence-11gr2' with arguments:
-order -resolve -thin
Loadjava finished.
Executing SQL Statement:
CREATE OR REPLACE PROCEDURE getData AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'CoherenceClient.getData()';
Success.
Executing SQL Statement:
CREATE OR REPLACE PROCEDURE putData AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'CoherenceClient.putData()';
Success.
Publishing finished.
----  Stored procedure deployment finished.  ----

9. Now we can write a very basic SQL file as follows which will put data onto the coherence cache and then retrieve it calling our 2 stored procedures.

set serveroutput on
call dbms_java.set_output(100000);

exec putData;
exec getData;

SQL*PLus Output

COHERENCE@linux11gr2> @run

Call completed.

2010-08-04 14:15:19.750/0.077 Oracle Coherence 3.5.3/465 (thread=Root Thread, member=n/a): Loaded operational
configuration from resource "jserver:/resource/schema/COHERENCE/tangosol-coherence.xml"
2010-08-04 14:15:19.755/0.082 Oracle Coherence 3.5.3/465 (thread=Root Thread, member=n/a): Loaded operational
overrides from resource "jserver:/resource/schema/COHERENCE/tangosol-coherence-override-dev.xml"
2010-08-04 14:15:19.756/0.083 Oracle Coherence 3.5.3/465 (thread=Root Thread, member=n/a): Optional configuration
override "/tangosol-coherence-override.xml" is not specified
2010-08-04 14:15:19.758/0.085 Oracle Coherence 3.5.3/465 (thread=Root Thread, member=n/a): Optional configuration
override "/custom-mbeans.xml" is not specified
Oracle Coherence Version 3.5.3/465
Grid Edition: Development mode
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
2010-08-04 14:15:19.876/0.203 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Loaded cache
configuration from "jserver:/resource/schema/COHERENCE/client-cache-config.xml"

2010-08-04 14:15:19.975/0.302 Oracle Coherence GE 3.5.3/465 (thread=RemoteCache:TcpInitiator, member=n/a): Started:
TcpInitiator{Name=RemoteCache:TcpInitiator, State=(SERVICE_STARTED), ThreadCount=0, Codec=Codec(Format=POF),
PingInterval=0, PingTimeout=0, RequestTimeout=0, ConnectTimeout=0,
RemoteAddresses=[papicell-au.au.oracle.com/10.187.80.135:9099], KeepAliveEnabled=true, TcpDelayEnabled=false,
ReceiveBufferSize=0, SendBufferSize=0, LingerTimeout=-1}
2010-08-04 14:15:19.976/0.303 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Opening Socket
connection to 10.187.80.135:9099

2010-08-04 14:15:19.979/0.306 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Connected to
10.187.80.135:9099
2010-08-04 14:15:20.013/0.340 Oracle Coherence GE 3.5.3/465 (thread=RemoteCache:TcpInitiator, member=n/a): Stopped:
TcpInitiator{Name=RemoteCache:TcpInitiator, State=(SERVICE_STOPPED), ThreadCount=0, Codec=Codec(Format=POF),
PingInterval=0, PingTimeout=0, RequestTimeout=0, ConnectTimeout=0,
RemoteAddresses=[papicell-au.au.oracle.com/10.187.80.135:9099], KeepAliveEnabled=true, TcpDelayEnabled=false,
ReceiveBufferSize=0, SendBufferSize=0, LingerTimeout=-1}

PL/SQL procedure successfully completed.

2010-08-04 14:15:20.031/0.358 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Loaded operational
configuration from resource "jserver:/resource/schema/COHERENCE/tangosol-coherence.xml"
2010-08-04 14:15:20.034/0.361 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Loaded operational
overrides from resource "jserver:/resource/schema/COHERENCE/tangosol-coherence-override-dev.xml"
2010-08-04 14:15:20.035/0.362 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Optional
configuration override "/tangosol-coherence-override.xml" is not specified
2010-08-04 14:15:20.036/0.363 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Optional
configuration override "/custom-mbeans.xml" is not specified
Oracle Coherence Version 3.5.3/465
Grid Edition: Development mode
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
2010-08-04 14:15:20.047/0.374 Oracle Coherence GE 3.5.3/465 (thread=Root Thread, member=n/a): Loaded cache
configuration from "jserver:/resource/schema/COHERENCE/client-cache-config.xml"
2010-08-04 14:15:20.062/0.389 Oracle Coherence GE 3.5.3/465 (thread=RemoteCache:TcpInitiator, member=n/a): Started:
TcpInitiator{Name=RemoteCache:TcpInitiator, State=(SERVICE_STARTED), ThreadCount=0, Codec=Codec(Format=POF),
PingInterval=0, PingTimeout=0, RequestTimeout=0, ConnectTimeout=0,
RemoteAddresses=[papicell-au.au.oracle.com/10.187.80.135:9099], KeepAliveEnabled=true, TcpDelayEnabled=false,
ReceiveBufferSize=0, SendBufferSize=0, LingerTimeout=-1}
2010-08-04 14:15:20.063/0.390 Oracle Coherence GE 3.5.3/465
(thread=Root Thread, member=n/a): Opening Socket
connection to 10.187.80.135:9099
2010-08-04 14:15:20.065/0.392 Oracle Coherence GE 3.5.3/465
(thread=Root Thread, member=n/a): Connected to
10.187.80.135:9099

Key 1 = Pas Apicella
2010-08-04 14:15:20.082/0.409 Oracle Coherence GE 3.5.3/465 (thread=RemoteCache:TcpInitiator, member=n/a): Stopped:
TcpInitiator{Name=RemoteCache:TcpInitiator, State=(SERVICE_STOPPED), ThreadCount=0, Codec=Codec(Format=POF),
PingInterval=0, PingTimeout=0, RequestTimeout=0, ConnectTimeout=0,
RemoteAddresses=[papicell-au.au.oracle.com/10.187.80.135:9099], KeepAliveEnabled=true, TcpDelayEnabled=false,
ReceiveBufferSize=0, SendBufferSize=0, LingerTimeout=-1}

PL/SQL procedure successfully completed.

COHERENCE@linux11gr2>


In this example we turn on debug output on the database side using DBMS_JAVA package to get console messages displayed when invoking the Java Stored procedure to verify indeed coherence is being used and what cache config file we are using. The fact that we now can access the coherence cluster from the database in SQL makes this worth the effort.

I also make sure I disconnect from the cluster once done in this simple example using "CacheFactory.shutdown();" in my Java Stored Procedures, assuming that database clients just need to read/put data from the cache and then there done.