0

I want to implement a custom FaceletCacheFactory providing a custom FaceletCache.

The reason I want to do it is to try out a fix for issue '[JAVASERVERFACES-4107] Facelet cache doesn't expire / refresh Facelets correctly' in the DefaultFaceletCache that is available in Mojarra javax.faces-2.3.0-m06, but not in Mojarra javax.faces-2.2.8-17.

I want to try the fix in the hope it addresses this strange recent problem I have encountered: Mac: JSF: why are development stage JSF web apps not always catching composite component changes?

My naive first attempt was to simply try to create a CustomFaceletFactory that provides a CustomFaceletCacheJSF3 reproducing the DefaultFaceletCache from Mojarra javax.faces-2.3.0-m06 as shown below, but it fails because com.sun.faces.facelets.impl.DefaultFacelet is not public and can't be imported:

public class CustomFaceletCacheJSF3 extends FaceletCache<DefaultFacelet> {

    private final static Logger LOGGER = FacesLogger.FACELETS_FACTORY.getLogger();

    /**
     *Constructor
     * @param refreshPeriod cache refresh period (in seconds).
     * 0 means 'always refresh', negative value means 'never refresh'
     */
    CustomFaceletCacheJSF3(final long refreshPeriod) {

        // We will be delegating object storage to the ExpiringCocurrentCache
        // Create Factory objects here for the cache. The objects will be delegating to our
        // own instance factories

        final boolean checkExpiry = (refreshPeriod > 0);

        ConcurrentCache.Factory<URL, Record> faceletFactory =
            new ConcurrentCache.Factory<URL, Record>() {
            @Override
            public Record newInstance(final URL key) throws IOException {
                // Make sure that the expensive timestamp retrieval is not done
                // if no expiry check is going to be performed
                long lastModified = checkExpiry ? Util.getLastModified(key) : 0;
                return new Record(System.currentTimeMillis(), lastModified,
                                  getMemberFactory().newInstance(key), refreshPeriod);
            }
        };

        ConcurrentCache.Factory<URL, Record> metadataFaceletFactory =
            new ConcurrentCache.Factory<URL, Record>() {
            @Override
            public Record newInstance(final URL key) throws IOException {
                // Make sure that the expensive timestamp retrieval is not done
                // if no expiry check is going to be performed
                long lastModified = checkExpiry ? Util.getLastModified(key) : 0;
                return new Record(System.currentTimeMillis(), lastModified,
                                  getMetadataMemberFactory().newInstance(key), refreshPeriod);
            }
        };

        // No caching if refreshPeriod is 0
        if (refreshPeriod == 0) {
            _faceletCache = new NoCache(faceletFactory);
            _metadataFaceletCache = new NoCache(metadataFaceletFactory);
        } else {
            ExpiringConcurrentCache.ExpiryChecker<URL, Record> checker = 
                (refreshPeriod > 0) ? new ExpiryChecker() : new NeverExpired();
            _faceletCache =
                    new ExpiringConcurrentCache<>(faceletFactory,
                                                             checker);
            _metadataFaceletCache =
                    new ExpiringConcurrentCache<>(metadataFaceletFactory,
                                                             checker);
        }
    }

    @Override
    public DefaultFacelet getFacelet(URL url) throws IOException {
        com.sun.faces.util.Util.notNull("url", url);
        DefaultFacelet f = null;

        try {
            f =  _faceletCache.get(url).getFacelet();
        } catch (ExecutionException e) {
            _unwrapIOException(e);
        }
        return f;
    }

    @Override
    public boolean isFaceletCached(URL url) {
        com.sun.faces.util.Util.notNull("url", url);

        return _faceletCache.containsKey(url);
    }


    @Override
    public DefaultFacelet getViewMetadataFacelet(URL url) throws IOException {
        com.sun.faces.util.Util.notNull("url", url);

        DefaultFacelet f = null;

        try {
            f = _metadataFaceletCache.get(url).getFacelet();
        } catch (ExecutionException e) {
            _unwrapIOException(e);
        }
        return f;
    }

    @Override
    public boolean isViewMetadataFaceletCached(URL url) {
        com.sun.faces.util.Util.notNull("url", url);

        return _metadataFaceletCache.containsKey(url);
    }

    private void _unwrapIOException(ExecutionException e) throws IOException {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException)t;
        }
        if (t.getCause() instanceof IOException) {
            throw (IOException)t.getCause();
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException)t;
        }
        throw new FacesException(t);
    }

    private final ConcurrentCache<URL, Record> _faceletCache;
    private final ConcurrentCache<URL, Record> _metadataFaceletCache;

    /**
     * This class holds the Facelet instance and its original URL's last modified time. It also produces
     * the time when the next expiry check should be performed
     */
    private static class Record {
        Record(long creationTime, long lastModified, DefaultFacelet facelet, long refreshInterval) {
            _facelet = facelet;
            _creationTime = creationTime;
            _lastModified = lastModified;
            _refreshInterval = refreshInterval;

            // There is no point in calculating the next refresh time if we are refreshing always/never
            _nextRefreshTime = (_refreshInterval > 0) ? new AtomicLong(creationTime + refreshInterval) : null;
        }

        DefaultFacelet getFacelet() {
            return _facelet;
        }

        long getLastModified() {
            return _lastModified;
        }

        long getNextRefreshTime() {
            // There is no point in calculating the next refresh time if we are refreshing always/never
            return (_refreshInterval > 0) ? _nextRefreshTime.get() : 0;
        }

        long getAndUpdateNextRefreshTime() {
            // There is no point in calculating the next refresh time if we are refreshing always/never
            return (_refreshInterval > 0) ? _nextRefreshTime.getAndAdd(_refreshInterval) : 0;
        }

        private final long _lastModified;
        private final long _refreshInterval;
        private final long _creationTime;
        private final AtomicLong _nextRefreshTime;
        private final DefaultFacelet _facelet;
    }

    private static class ExpiryChecker implements ExpiringConcurrentCache.ExpiryChecker<URL, Record> {

        @Override
        public boolean isExpired(URL url, Record record) {
            if (System.currentTimeMillis() > record.getNextRefreshTime()) {
                record.getAndUpdateNextRefreshTime();
                long lastModified = Util.getLastModified(url);
                // The record is considered expired if its original last modified time
                // is older than the URL's current last modified time
                return (lastModified > record.getLastModified());
            }
            return false;
        }
    }

    private static class NeverExpired implements ExpiringConcurrentCache.ExpiryChecker<URL, Record> {
        @Override
        public boolean isExpired(URL key, Record value) {
            return false;
        }
    }

    /**
     * ConcurrentCache implementation that does no caching (always creates new instances)
     */
    private static class NoCache extends ConcurrentCache<URL, Record> {
        public NoCache(ConcurrentCache.Factory<URL, Record> f) {
            super(f);
        }

        @Override
        public Record get(final URL key) throws ExecutionException {
            try {
                return this.getFactory().newInstance(key);
            } catch (Exception e) {
                throw new ExecutionException(e);
            }
        }

        @Override
        public boolean containsKey(final URL key) {
            return false;
        }
    }


}
Community
  • 1
  • 1
  • @MicheleMariotti has provided a simple "brute force" cache rewrite here: http://stackoverflow.com/questions/35680986/mac-jsf-why-are-development-stage-jsf-web-apps-not-always-catching-composite-c/38915829#38915829 in answer to http://stackoverflow.com/questions/35680986/mac-jsf-why-are-development-stage-jsf-web-apps-not-always-catching-composite-c/38915829 – Webel IT Australia - upvoter Aug 13 '16 at 13:01
  • That bug seem to be fixed in the 2.2.8-19 version released on 08/Feb/17. Here is the [link](https://javaserverfaces.java.net/2.2/releasenotes.html) to release notes – 1078081 Mar 17 '17 at 03:16

0 Answers0