Carmelo Cascone | 7e73fa1 | 2019-07-15 18:29:01 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 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 | |
| 17 | package org.opencord.kafka.integrations; |
| 18 | |
| 19 | import org.onosproject.event.EventListener; |
| 20 | import org.onosproject.event.ListenerService; |
| 21 | import org.slf4j.Logger; |
| 22 | import org.slf4j.LoggerFactory; |
| 23 | |
| 24 | import java.util.concurrent.atomic.AtomicReference; |
| 25 | |
| 26 | /** |
| 27 | * Abstract implementation of a service-specific Kafka integration which provide |
| 28 | * convenience methods to dynamically bind/unbind event listener services. |
| 29 | */ |
| 30 | class AbstractKafkaIntegration { |
| 31 | |
| 32 | Logger log = LoggerFactory.getLogger(getClass()); |
| 33 | |
| 34 | // OSGi demands dynamic @Reference to use volatile fields. We use a second |
| 35 | // field to store the actual service implementation reference and use that |
| 36 | // in the bind/unbind methods. We make sure to add listeners only if one was |
| 37 | // not already added. |
| 38 | |
| 39 | <S extends ListenerService<?, L>, L extends EventListener<?>> void bindAndAddListener( |
| 40 | S incomingService, AtomicReference<S> serviceRef, L listener) { |
| 41 | if (incomingService == null) { |
| 42 | return; |
| 43 | } |
| 44 | if (serviceRef.compareAndSet(null, incomingService)) { |
| 45 | log.info("Adding listener on {}", incomingService.getClass().getSimpleName()); |
| 46 | incomingService.addListener(listener); |
| 47 | } else { |
| 48 | log.warn("Trying to bind AccessDeviceService but it is already bound"); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | <S extends ListenerService<?, L>, L extends EventListener<?>> void unbindAndRemoveListener( |
| 53 | S outgoingService, AtomicReference<S> serviceRef, L listener) { |
| 54 | if (outgoingService != null && |
| 55 | serviceRef.compareAndSet(outgoingService, null)) { |
| 56 | log.info("Removing listener on {}", outgoingService.getClass().getSimpleName()); |
| 57 | outgoingService.removeListener(listener); |
| 58 | } |
| 59 | // Else, ignore. This is not the instance currently bound, or the |
| 60 | // outgoing service is null. |
| 61 | } |
| 62 | } |