JSF2.2: Mojarra: как реализовать пользовательский FaceletCacheFactory, возвращающий пользовательский FaceletCache

Я хочу реализовать собственную FaceletCacheFactory предоставление пользовательского FaceletCache.

Причина, по которой я хочу это сделать, — попробовать исправить проблему '[JAVASERVERFACES-4107] Кэш Facelet не истекает/обновляет Facelets правильно' в DefaultFaceletCache, который доступен в Mojarra javax.faces-2.3.0-m06, но не в Mojarra javax.faces-2.2.8-17.

Я хочу попробовать исправление в надежде, что оно решит эту странную недавнюю проблему, с которой я столкнулся: Mac: JSF: почему веб-приложения JSF на стадии разработки не всегда фиксируют изменения составных компонентов?

Моя наивная первая попытка заключалась в том, чтобы просто попытаться создать CustomFaceletFactory, который предоставляет CustomFaceletCacheJSF3, воспроизводящий DefaultFaceletCache из Mojarra javax.faces-2.3.0-m06, как показано ниже, но это не удается потому что com.sun.faces.facelets.impl .DefaultFacelet не является общедоступным и не может быть импортирован:

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;
        }
    }


}

person Webel IT Australia - upvoter    schedule 11.08.2016    source источник
comment
@MicheleMariotti предоставил здесь простую переписку кеша грубой силы: -catch-composite-c/38915829#38915829" title="mac jsf, почему веб-приложения jsf на стадии разработки не всегда улавливают составной c">stackoverflow.com/questions/35680986/ в ответ на stackoverflow.com/questions/35680986/   -  person Webel IT Australia - upvoter    schedule 13.08.2016
comment
Похоже, эта ошибка исправлена ​​в версии 2.2.8-19, выпущенной 08/февраль/17. Вот ссылка на примечания к выпуску.   -  person 1078081    schedule 17.03.2017