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

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when>         <c:otherwise>             Do something otherwise         </c:otherwise>     </c:choose> Att