Skip to main content

.Net Callback from Java Cache Invalidate Message

The problem this post solves is as follows: the Content Delivery API has a mechanism called Cache Decorator, which allows the implementor to define custom code that will be called when things are added/removed/flushed from the internal Tridion Broker Cache. This mechanism allows external actors to interact and synchronize with the Tridion Broker Cache.

Namely, a DD4T cache should listen to Tridion Broker Cache messages in order to invalidate its own entries. In Java world, this is simply implemented by extending the CacheDecorator Tridion class. However, in a .NET environment, there is no easy way of intercepting Java method execution back in .NET. This is precisely what this post describes.

In a .NET architecture, the Tridion Content Delivery API runs as a Java byte code embedded inside the .NET runtime inside IIS worker process. Communication between .NET and Java happens using a standard called JNI (Java Native Interfaces). Namely the .NET runtime calls Java code that is mapped class to class and method to method from .NET classes/methods to their Java counterparts.

The solution this post presents enables communication from the Java embedded API back into .NET by means of defining a custom interface that is implemented in both Java and .NET and mapping it as callback method using JNI (namely JuggerNET package used internally by the Content Delivery framework).

There are two assumptions in this approach:
  • there is a Content Delivery stack present in your web application. In other words, the web application does not use the CIL (or REST client providers) or SDL Web 8 for DD4T or DXA. In that case a simple Time-To-Live cache would suffice;
  • the Cache Channel Service is already configured and running. The invalidate messages coming from the Cache Channel Service are received in the Tridion Content Delivery stack by either means of RMI or JMS;
The entire code presented below is available in this blog's GIT repository. You can find there both Java IntelliJ and Visual Studio .NET projects. Link here.

Java Stuff

Lets start with the Java part, with a class called DD4TDependencyTracker that extends class com.tridion.DependencyTracker.

package com.tridion.cache;

import com.mihaiconsulting.cache.CacheNotifier;

public class DD4TDependencyTracker extends DependencyTracker {

    public DD4TDependencyTracker(CacheProcessor cache, Region region) {
        super(cache, region);
    }

    @Override
    public boolean processRemove(CacheElement element, boolean force)
            throws CacheException {
        if (element != null) {
            String key = element.getKey().toString();
            CacheNotifier.getInstance().notify(key);
        }

        return super.processRemove(element, force);
    }
}

The custom processRemove method invokes a notify method on a CacheNotifier class. The notifier class is simply a singleton that proxies the notify call to a specially crafter CacheInvalidator class that makes use of JNI (JuggerNet) code to register itself as a proxy for a .NET counterpart class.

package com.mihaiconsulting.cache;

public class CacheNotifier {

    private static final CacheNotifier instance = new CacheNotifier();
    private CacheInvalidator invalidator = new CacheInvalidator() {
        @Override
        public void invalidate(String key) {
            //Using empty CacheInvalidator
        }
    };

    private CacheNotifier() {
    }

    public static CacheNotifier getInstance() {
        return instance;
    }

    public void setInvalidator(CacheInvalidator invalidator) {
        if (invalidator == null) {
            throw new IllegalStateException("Invalid null CacheInvalidator");
        }

        this.invalidator = invalidator;
    }

    public void notify(String key) {
        invalidator.invalidate(key);
    }
}

CacheInvalidator is an interface defining an invalidate method. In Java, we define an implementing class that makes the actual (callback) call into .NET using JNI. We will later see that the same CacheInvalidator interface has a counterpart interface in .NET. All implementations on the .NET CacheInvalidator interface will be called when the Java callback is called.

The following implementing class, CacheInvalidatorCallback is only given for reference purpose only. It contains specific code from JuggerNet and its relevance to this post is minor. The actual code is available in the full solution in GIT.

package com.mihaiconsulting.cache;

public class CacheInvalidatorCallback implements CacheInvalidator {

    @Override
    public void invalidate(String key) {
        Value value = new Value();
        Value.callback_opt(this, _xmog_inst, _xmog_cbs[0], value, key);
    }
}

.NET Stuff

In .NET, we define proxy classes for each class and interface from Java. These are specially crafted objects that use JNI (JuggerNet API) to define counterparts for their Java correspondents.

Interface ICacheInvalidator declared below defines the Invalidate method that an implementing class will have it called by the JNI callback:

namespace Com.MihaiConsulting.Cache
{
    public interface ICacheInvalidator
    {
        void Invalidate(string key);
    }
}

Class CacheNotifier maps the Java counterpart class and defines proxy methods for the Instance and Invalidator properties:

using Codemesh.JuggerNET;

namespace Com.MihaiConsulting.Cache
{
    public class CacheNotifier : JuggerNETProxyObject
    {
        private static JavaClass _cmj_theClass = JavaClass.RegisterClass("com.mihaiconsulting.cache.CacheNotifier", typeof(CacheNotifier));
        private static JavaMethod _getInstance = new JavaMethod(_cmj_theClass, typeof(CacheNotifier), "getInstance", "()Lcom/mihaiconsulting/cache/CacheNotifier;", true, false, false);
        private static JavaMethod _setInvalidator = new JavaMethod(_cmj_theClass, typeof(void), "setInvalidator", "(Lcom/mihaiconsulting/cache/CacheInvalidator;)V", false, false, false);

        public CacheNotifier(JNIHandle objectHandle) : base(objectHandle) { }

        public static CacheNotifier Instance
        {
            get
            {
                return (CacheNotifier)_getInstance.CallObject(null, typeof(CacheNotifier), false);
            }
        }

        public ICacheInvalidator Invalidator
        {
            set
            {
                jvalue[] cmj_jargs = new jvalue[1];
                using (JavaMethodArguments cmj_jmargs = new JavaMethodArguments(cmj_jargs).Add(value, typeof(ICacheInvalidator)))
                {
                    _setInvalidator.CallVoid(this, cmj_jmargs);
                }
            }
        }
    }
}

Class CacheInvalidatorCallback is the one defining the mapping between .NET and Java for the call back instance. This mapping is responsible for calling the Invalidate method on the .NET class provided as parameter in the constructor:

using Codemesh.JuggerNET;
using System;
using System.IO;
using System.Reflection;

namespace Com.MihaiConsulting.Cache
{
    public class CacheInvalidatorCallback : JuggerNETProxyObject
    {
        private static JavaClass _cmj_theClass = new JavaClass("com/mihaiconsulting/cache/CacheInvalidatorCallback", typeof(CacheInvalidatorCallback));
        private static JavaMethod _constructor;
        private GenericCallback _callback;
        private ICacheInvalidator _invalidator;

        static CacheInvalidatorCallback()
        {
            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Com.MihaiConsulting.Cache.JuggerNET.CacheInvalidatorCallback.class"))
            {
                Byte[] buffer = new Byte[resourceStream.Length];
                resourceStream.Read(buffer, 0, (int)resourceStream.Length);

                _cmj_theClass.ByteCode = buffer;
            }

            _constructor = new JavaMethod(_cmj_theClass, null, "<init>", "(J[J)V", false);
        }

        public CacheInvalidatorCallback(ICacheInvalidator cacheInvalidator)
        {
            _invalidator = cacheInvalidator;
            _callback = new GenericCallback((out int return_type, out jvalue return_value, IntPtr input) =>
            {
                try
                {
                    string key = (string)JavaClass.GetTypedInstance(typeof(string), jvalue.From(input).l);
                    _invalidator.Invalidate(key);

                    return_value = new jvalue();
                    return_type = 0;
                }
                catch (Exception exception)
                {
                    return_value = jvalue.CreateCBRetVal(exception);
                    return_type = 1;
                }

                return 0;
            });

            base.JObject = _constructor.construct(0, _callback);
        }
    }
}

Class CacheInvalidator brings all mappings together -- ICacheInvalidator, CacheInvalidator, CacheInvalidatorCallback and the Java counterpart for CacheInvalidator:

using Codemesh.JuggerNET;

namespace Com.MihaiConsulting.Cache
{
    public class CacheInvalidator : JuggerNETProxyObject
    {
        private static JavaClass _cmj_theClass = JavaClass.RegisterClass(
            "com.mihaiconsulting.cache.CacheInvalidator",
            typeof(ICacheInvalidator),
            typeof(CacheInvalidator),
            typeof(CacheInvalidatorCallback));

        public CacheInvalidator(JNIHandle objectHandle) : base(objectHandle) { }
    }
}

The code above is available in this blog's GIT repository. You can find there both Java IntelliJ and Visual Studio .NET projects. Link here.



Comments

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

Debugging a Tridion 2011 Event System

OK, so you wrote your Tridion Event System. Now it's time to debug it. I know this is a hypothetical situtation -- your code never needs any kind of debugging ;) but indulge me... Recently, Alvin Reyes ( @nivlong ) blogged about being difficult to know how exactly to debug a Tridion Event System. More exactly, the question was " What process do I attach to for debugging even system code? ". Unfortunately, there is no simple or generic answer for it. Different events are fired by different Tridion CM modules. These modules run as different programs (or services) or run inside other programs (e.g. IIS). This means that you will need to monitor (or debug) different processes, based on which events your code handles. So the usual suspects are: dllhost.exe (or dllhost3g.exe ) - running as the MTSUser is the SDL Tridion Content Manager COM+ application and it fires events on generic TOM objects (e.g. events based on Tridion.ContentManager.Extensibility.Events.CrudEven