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

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the

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

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio