/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.model.repo.util; import com.google.common.base.Preconditions; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; public class InMemorySchemaSourceCache extends AbstractSchemaSourceCache { private static final class CacheEntry { private final SchemaSourceRegistration reg; private final T source; public CacheEntry(final T source, final SchemaSourceRegistration reg) { this.source = Preconditions.checkNotNull(source); this.reg = Preconditions.checkNotNull(reg); } } private static final RemovalListener> LISTENER = new RemovalListener>() { @Override public void onRemoval(final RemovalNotification> notification) { notification.getValue().reg.close(); } }; private final Cache> cache; protected InMemorySchemaSourceCache(final SchemaSourceRegistry consumer, final Class representation, final int maxSize) { super(consumer, representation, Costs.IMMEDIATE); cache = CacheBuilder.newBuilder().softValues().maximumSize(maxSize).removalListener(LISTENER).build(); } @Override public CheckedFuture getSource(final SourceIdentifier sourceIdentifier) { final CacheEntry present = cache.getIfPresent(sourceIdentifier); if (present != null) { return Futures.immediateCheckedFuture(present.source); } return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found")); } @Override protected void offer(final T source) { final CacheEntry present = cache.getIfPresent(source.getIdentifier()); if (present == null) { final SchemaSourceRegistration reg = register(source.getIdentifier()); cache.put(source.getIdentifier(), new CacheEntry(source, reg)); } } }