Do not use RpcService in toaster-consumer
[controller.git] / opendaylight / md-sal / samples / toaster-consumer / src / main / java / org / opendaylight / controller / sample / kitchen / impl / KitchenServiceImpl.java
1 /*
2  * Copyright (c) 2014, 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sample.kitchen.impl;
9
10 import com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableList.Builder;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import java.util.List;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.ExecutorService;
18 import java.util.concurrent.Executors;
19 import javax.annotation.PreDestroy;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
23 import org.opendaylight.controller.sample.kitchen.api.EggsType;
24 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
25 import org.opendaylight.controller.sample.kitchen.api.KitchenServiceRuntimeMXBean;
26 import org.opendaylight.mdsal.binding.api.NotificationService;
27 import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
28 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
29 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
30 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
31 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
32 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
33 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterListener;
34 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBread;
35 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
36 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
37 import org.opendaylight.yangtools.concepts.Registration;
38 import org.opendaylight.yangtools.yang.common.ErrorTag;
39 import org.opendaylight.yangtools.yang.common.ErrorType;
40 import org.opendaylight.yangtools.yang.common.RpcError;
41 import org.opendaylight.yangtools.yang.common.RpcResult;
42 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
43 import org.opendaylight.yangtools.yang.common.Uint32;
44 import org.osgi.service.component.annotations.Activate;
45 import org.osgi.service.component.annotations.Component;
46 import org.osgi.service.component.annotations.Deactivate;
47 import org.osgi.service.component.annotations.Reference;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Singleton
52 @Component(service = KitchenService.class, immediate = true)
53 public final class KitchenServiceImpl extends AbstractMXBean
54         implements KitchenService, KitchenServiceRuntimeMXBean, ToasterListener {
55
56     private static final Logger LOG = LoggerFactory.getLogger(KitchenServiceImpl.class);
57     private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
58
59     private final ExecutorService executor = Executors.newCachedThreadPool();
60     private final MakeToast makeToast;
61     private final Registration reg;
62
63     private volatile boolean toasterOutOfBread;
64
65     @Inject
66     @Activate
67     public KitchenServiceImpl(@Reference final RpcConsumerRegistry rpcRegistry,
68             @Reference final NotificationService notifService) {
69         super("KitchenService", "toaster-consumer", null);
70         makeToast = rpcRegistry.getRpc(MakeToast.class);
71         reg = notifService.registerNotificationListener(this);
72         register();
73     }
74
75     @PreDestroy
76     @Deactivate
77     public void close() {
78         unregister();
79         reg.close();
80     }
81
82     @Override
83     public ListenableFuture<RpcResult<Void>> makeBreakfast(final EggsType eggsType, final ToastType toastType,
84             final int toastDoneness) {
85         // Call makeToast, The OpendaylightToaster impl already returns a ListenableFuture so the conversion is
86         // actually a no-op.
87
88         ListenableFuture<RpcResult<MakeToastOutput>> makeToastFuture = makeToast(toastType, toastDoneness);
89
90         ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType);
91
92         // Combine the 2 ListenableFutures into 1 containing a list RpcResults.
93
94         ListenableFuture<List<RpcResult<? extends Object>>> combinedFutures = Futures
95                 .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture));
96
97         // Then transform the RpcResults into 1.
98
99         return Futures.transformAsync(combinedFutures, results -> {
100             boolean atLeastOneSucceeded = false;
101             Builder<RpcError> errorList = ImmutableList.builder();
102             for (RpcResult<? extends Object> result : results) {
103                 if (result.isSuccessful()) {
104                     atLeastOneSucceeded = true;
105                 }
106
107                 if (result.getErrors() != null) {
108                     errorList.addAll(result.getErrors());
109                 }
110             }
111
112             return RpcResultBuilder.<Void>status(atLeastOneSucceeded).withRpcErrors(errorList.build()).buildFuture();
113         }, MoreExecutors.directExecutor());
114     }
115
116     private ListenableFuture<RpcResult<Void>> makeEggs(final EggsType eggsType) {
117         return Futures.submit(() -> RpcResultBuilder.<Void>success().build(), executor);
118     }
119
120     private ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final ToastType toastType, final int toastDoneness) {
121         if (toasterOutOfBread) {
122             LOG.info("We're out of toast but we can make eggs");
123             return RpcResultBuilder.success(EMPTY_MAKE_OUTPUT)
124                 .withWarning(ErrorType.APPLICATION, ErrorTag.PARTIAL_OPERATION,
125                     "Toaster is out of bread but we can make you eggs")
126                 .buildFuture();
127         }
128
129         // Access the ToasterService to make the toast.
130         return makeToast.invoke(new MakeToastInputBuilder()
131             .setToasterDoneness(Uint32.valueOf(toastDoneness))
132             .setToasterToastType(toastType)
133             .build());
134     }
135
136     @Override
137     public Boolean makeScrambledWithWheat() {
138         try {
139             // This call has to block since we must return a result to the JMX client.
140             RpcResult<Void> result = makeBreakfast(EggsType.SCRAMBLED, WheatBread.VALUE, 2).get();
141             if (result.isSuccessful()) {
142                 LOG.info("makeBreakfast succeeded");
143             } else {
144                 LOG.warn("makeBreakfast failed: {}", result.getErrors());
145             }
146
147             return result.isSuccessful();
148         } catch (InterruptedException | ExecutionException e) {
149             LOG.warn("An error occurred while maing breakfast", e);
150         }
151
152         return Boolean.FALSE;
153     }
154
155     /**
156      * Implemented from the ToasterListener interface.
157      */
158     @Override
159     public void onToasterOutOfBread(final ToasterOutOfBread notification) {
160         LOG.info("ToasterOutOfBread notification");
161         toasterOutOfBread = true;
162     }
163
164     /**
165      * Implemented from the ToasterListener interface.
166      */
167     @Override
168     public void onToasterRestocked(final ToasterRestocked notification) {
169         LOG.info("ToasterRestocked notification - amountOfBread: {}", notification.getAmountOfBread());
170         toasterOutOfBread = false;
171     }
172 }