HIGUCHI Yuta | 34a3f69 | 2016-01-09 21:08:57 -0800 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2016-present Open Networking Foundation |
HIGUCHI Yuta | 34a3f69 | 2016-01-09 21:08:57 -0800 | [diff] [blame] | 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package org.onosproject.net.optical.device.port; |
| 17 | |
| 18 | import java.util.Optional; |
| 19 | |
| 20 | import org.onosproject.net.Port; |
| 21 | |
| 22 | import com.google.common.annotations.Beta; |
| 23 | import com.google.common.cache.CacheBuilder; |
| 24 | import com.google.common.cache.CacheLoader; |
| 25 | import com.google.common.cache.LoadingCache; |
| 26 | |
| 27 | /** |
| 28 | * PortMapper which caches mapped Port instance. |
| 29 | */ |
| 30 | @Beta |
| 31 | public abstract class AbstractPortMapper<P extends Port> implements PortMapper<P> { |
| 32 | |
| 33 | private final LoadingCache<Port, Optional<P>> cache |
| 34 | = CacheBuilder.newBuilder() |
| 35 | .weakKeys() // use == to compare keys |
| 36 | .maximumSize(100) |
| 37 | .build(CacheLoader.from(this::mapPort)); |
| 38 | |
| 39 | /** |
| 40 | * {@inheritDoc} |
| 41 | * |
| 42 | * <p> |
| 43 | * Note: Subclasses should override and implement short-cut conditions |
| 44 | * and call {@code super.is(port)}. |
| 45 | */ |
| 46 | @Override |
| 47 | public boolean is(Port port) { |
| 48 | return as(port).isPresent(); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * {@inheritDoc} |
| 53 | * |
| 54 | * <p> |
| 55 | * Note: Subclasses should override and check if {@code port} is |
| 56 | * already of type {@code P} and directly return {@code Optional.of((P) port)}, |
| 57 | * if not call {@code super.as(port)}. |
| 58 | */ |
| 59 | @Override |
| 60 | public Optional<P> as(Port port) { |
| 61 | if (port == null) { |
| 62 | return Optional.empty(); |
| 63 | } |
| 64 | return cache.getUnchecked(port); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Returns {@code port} mapped to {@code <P>}. |
| 69 | * |
| 70 | * @param port Port to map |
| 71 | * @return {@code port} mapped to {@code <P>} |
| 72 | */ |
| 73 | protected abstract Optional<P> mapPort(Port port); |
| 74 | |
| 75 | } |